991 lines
66 KiB
Python
991 lines
66 KiB
Python
"""Streamable HTTP MCP adapter. All application operations cross the HTTP API."""
|
||
import base64
|
||
import binascii
|
||
import logging
|
||
import os
|
||
import uuid
|
||
from datetime import datetime
|
||
from decimal import Decimal
|
||
from typing import Any, Literal
|
||
from urllib.parse import urlsplit
|
||
|
||
import httpx2
|
||
from mcp.server.auth.middleware.auth_context import get_access_token
|
||
from mcp.server.auth.provider import AccessToken, TokenVerifier
|
||
from mcp.server.auth.routes import create_protected_resource_routes
|
||
from mcp.server.auth.settings import AuthSettings
|
||
from mcp.server.mcpserver import MCPServer
|
||
from mcp.server.mcpserver.exceptions import ToolError
|
||
from mcp.server.transport_security import TransportSecuritySettings
|
||
from pydantic import AnyHttpUrl, BaseModel, ConfigDict, Field
|
||
|
||
API_BASE = os.environ.get('TASKNEST_API_BASE_URL', 'http://127.0.0.1:1234/api/v1').rstrip('/')
|
||
MCP_PUBLIC_URL = os.environ.get('TASKNEST_MCP_PUBLIC_URL', 'https://tasksnest.jorendegraaf.eu/mcp')
|
||
OAUTH_ISSUER_URL = os.environ.get('TASKNEST_OAUTH_ISSUER_URL', 'https://tasksnest.jorendegraaf.eu/')
|
||
MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||
SUPPORTED_SCOPES = ['food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write']
|
||
FILE_HOSTS = tuple(host.strip().lower().lstrip('.') for host in
|
||
os.environ.get('TASKNEST_MCP_FILE_HOSTS', 'openai.com,oaiusercontent.com,chatgpt.com').split(',') if host.strip())
|
||
CHATGPT_BLOB_HOST = 'oaisdmntprukwest.blob.core.windows.net'
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
class ClientImageFile(BaseModel):
|
||
"""File object supplied by a client such as ChatGPT, not a server-side path."""
|
||
model_config = ConfigDict(extra='forbid')
|
||
download_url: str
|
||
file_id: str
|
||
mime_type: str | None = None
|
||
file_name: str | None = None
|
||
|
||
|
||
class FoodInput(BaseModel):
|
||
"""Food details; use product_id for a saved product or product_name for an estimate."""
|
||
meal: Literal['breakfast', 'lunch', 'dinner', 'snacks']
|
||
amount: Decimal = Field(gt=0)
|
||
unit: Literal['g', 'ml']
|
||
product_id: str | None = None
|
||
inventory_package_id: str | None = None
|
||
product_name: str | None = None
|
||
brand: str | None = None
|
||
barcode: str | None = None
|
||
portion_label: str | None = None
|
||
calories_kcal: Decimal | None = Field(default=None, ge=0)
|
||
carbohydrates_g: Decimal | None = Field(default=None, ge=0)
|
||
protein_g: Decimal | None = Field(default=None, ge=0)
|
||
fat_g: Decimal | None = Field(default=None, ge=0)
|
||
fibre_g: Decimal | None = Field(default=None, ge=0)
|
||
sugars_g: Decimal | None = Field(default=None, ge=0)
|
||
salt_g: Decimal | None = Field(default=None, ge=0)
|
||
time: str | None = None
|
||
date: str | None = None
|
||
|
||
|
||
class FoodUpdate(BaseModel):
|
||
meal: Literal['breakfast', 'lunch', 'dinner', 'snacks'] | None = None
|
||
amount: Decimal | None = Field(default=None, gt=0)
|
||
unit: Literal['g', 'ml'] | None = None
|
||
product_id: str | None = None
|
||
product_name: str | None = None
|
||
brand: str | None = None
|
||
barcode: str | None = None
|
||
portion_label: str | None = None
|
||
calories_kcal: Decimal | None = Field(default=None, ge=0)
|
||
carbohydrates_g: Decimal | None = Field(default=None, ge=0)
|
||
protein_g: Decimal | None = Field(default=None, ge=0)
|
||
fat_g: Decimal | None = Field(default=None, ge=0)
|
||
fibre_g: Decimal | None = Field(default=None, ge=0)
|
||
sugars_g: Decimal | None = Field(default=None, ge=0)
|
||
salt_g: Decimal | None = Field(default=None, ge=0)
|
||
time: str | None = None
|
||
date: str | None = None
|
||
|
||
|
||
class ProductInput(BaseModel):
|
||
name: str
|
||
brand: str = ''
|
||
barcode: str | None = None
|
||
package_quantity: Decimal | None = None
|
||
package_unit: Literal['g', 'ml'] | None = None
|
||
nutrition_per_100: dict[str, Decimal | None] | None = None
|
||
source: Literal['manual'] = 'manual'
|
||
|
||
|
||
class GroceryInput(BaseModel):
|
||
product_id: str | None = None
|
||
name: str | None = None
|
||
brand: str | None = None
|
||
barcode: str | None = None
|
||
quantity: int = 1
|
||
package_quantity: Decimal | None = None
|
||
package_unit: Literal['g', 'ml'] | None = None
|
||
nutrition_per_100: dict[str, Decimal | None] | None = None
|
||
location: str = ''
|
||
category: str | None = None
|
||
notes: str = ''
|
||
opened: bool = False
|
||
best_before: str | None = None
|
||
original_amount: Decimal | None = Field(default=None, gt=0)
|
||
unit: Literal['mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions'] | None = None
|
||
pieces_per_package: int | None = Field(default=None, ge=1)
|
||
remaining_pieces: int | None = Field(default=None, ge=0)
|
||
piece_amount: Decimal | None = Field(default=None, gt=0)
|
||
inner_packs_per_package: int | None = Field(default=None, ge=1)
|
||
pieces_per_inner_pack: int | None = Field(default=None, ge=1)
|
||
inner_pack_amount: Decimal | None = Field(default=None, gt=0)
|
||
inner_pack_label: str | None = None
|
||
piece_label: str | None = None
|
||
|
||
|
||
class InventoryUpdate(BaseModel):
|
||
product_id: str | None = None
|
||
quantity: int | None = Field(default=None, ge=1)
|
||
location: str | None = None
|
||
category: str | None = None
|
||
notes: str | None = None
|
||
opened: bool | None = None
|
||
remaining_amount: Decimal | None = Field(default=None, ge=0)
|
||
original_amount: Decimal | None = Field(default=None, gt=0)
|
||
unit: Literal['mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions'] | None = None
|
||
pieces_per_package: int | None = Field(default=None, ge=1)
|
||
remaining_pieces: int | None = Field(default=None, ge=0)
|
||
piece_amount: Decimal | None = Field(default=None, gt=0)
|
||
inner_packs_per_package: int | None = Field(default=None, ge=1)
|
||
pieces_per_inner_pack: int | None = Field(default=None, ge=1)
|
||
inner_pack_amount: Decimal | None = Field(default=None, gt=0)
|
||
inner_pack_label: str | None = None
|
||
piece_label: str | None = None
|
||
best_before: str | None = None
|
||
|
||
|
||
class InventoryBulkUpdateEntry(BaseModel):
|
||
item_id: str
|
||
changes: InventoryUpdate
|
||
expected_updated_at: 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
|
||
|
||
|
||
class RecipeInput(BaseModel):
|
||
title: str
|
||
description: str = ''
|
||
instructions_markdown: str = ''
|
||
notes_markdown: str = ''
|
||
preparation_minutes: int = Field(default=0, ge=0)
|
||
cooking_minutes: int = Field(default=0, ge=0)
|
||
default_servings: Decimal = Field(default=Decimal('2'), gt=0)
|
||
yield_amount: Decimal | None = Field(default=None, gt=0)
|
||
yield_unit: Literal['g', 'ml'] | None = None
|
||
category: str = ''
|
||
tags: list[str] = Field(default_factory=list)
|
||
status: Literal['draft', 'published'] = 'draft'
|
||
|
||
|
||
class RecipeChanges(BaseModel):
|
||
title: str | None = None
|
||
description: str | None = None
|
||
instructions_markdown: str | None = None
|
||
notes_markdown: str | None = None
|
||
preparation_minutes: int | None = Field(default=None, ge=0)
|
||
cooking_minutes: int | None = Field(default=None, ge=0)
|
||
default_servings: Decimal | None = Field(default=None, gt=0)
|
||
yield_amount: Decimal | None = Field(default=None, gt=0)
|
||
yield_unit: Literal['g', 'ml'] | None = None
|
||
category: str | None = None
|
||
tags: list[str] | None = None
|
||
status: Literal['draft', 'published'] | None = None
|
||
is_favourite: bool | None = None
|
||
|
||
|
||
class RecipeIngredientInput(BaseModel):
|
||
name: str
|
||
quantity: Decimal = Field(gt=0)
|
||
unit: Literal['g', 'kg', 'ml', 'L', 'pieces', 'tsp', 'tbsp', 'portions']
|
||
amount_per_unit: Decimal | None = Field(default=None, gt=0)
|
||
amount_per_unit_unit: Literal['g', 'ml'] | None = None
|
||
inventory_product_id: str | None = None
|
||
nutrition_product_id: str | None = None
|
||
preparation_note: str = ''
|
||
is_optional: bool = False
|
||
display_order: int = Field(default=0, ge=0)
|
||
|
||
|
||
class RecipeIngredientChanges(BaseModel):
|
||
name: str | None = None
|
||
quantity: Decimal | None = Field(default=None, gt=0)
|
||
unit: Literal['g', 'kg', 'ml', 'L', 'pieces', 'tsp', 'tbsp', 'portions'] | None = None
|
||
amount_per_unit: Decimal | None = Field(default=None, gt=0)
|
||
amount_per_unit_unit: Literal['g', 'ml'] | None = None
|
||
inventory_product_id: str | None = None
|
||
nutrition_product_id: str | None = None
|
||
preparation_note: str | None = None
|
||
is_optional: bool | None = None
|
||
display_order: int | None = Field(default=None, ge=0)
|
||
|
||
|
||
class RecipeAnalysisInput(BaseModel):
|
||
servings: Decimal | None = Field(default=None, gt=0)
|
||
include_optional: bool = False
|
||
substitutions: dict[str, str] = Field(default_factory=dict)
|
||
|
||
|
||
class RecipeComponentInput(BaseModel):
|
||
recipe_id: str
|
||
servings: Decimal = Field(gt=0, le=Decimal('99999.99'))
|
||
|
||
|
||
class RecipeCompositionInput(BaseModel):
|
||
title: str = Field(min_length=1, max_length=180)
|
||
default_servings: Decimal = Field(default=Decimal('2'), gt=0, le=Decimal('99999.99'))
|
||
components: list[RecipeComponentInput] = Field(min_length=1, max_length=10)
|
||
|
||
|
||
class RecipeLinkInput(BaseModel):
|
||
recipe_id: str
|
||
relationship: Literal['goes_well_with', 'try_with', 'alternative_to'] = 'goes_well_with'
|
||
note: str = Field(default='', max_length=255)
|
||
reciprocal: bool = True
|
||
|
||
|
||
class RecipeLinkChanges(BaseModel):
|
||
relationship: Literal['goes_well_with', 'try_with', 'alternative_to'] | None = None
|
||
note: str | None = Field(default=None, max_length=255)
|
||
reciprocal: bool | None = None
|
||
|
||
|
||
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
|
||
timing: Literal['anytime', 'before_sleep', 'after_waking'] = 'anytime'
|
||
note: str = ''
|
||
tags: list[str] = Field(default_factory=list)
|
||
symptoms: list[Literal['tension', 'headache', 'fatigue', 'restlessness']] = Field(default_factory=list)
|
||
|
||
|
||
class StressChanges(BaseModel):
|
||
score: int | None = Field(default=None, ge=0, le=10)
|
||
recorded_at: str | None = None
|
||
timing: Literal['anytime', 'before_sleep', 'after_waking'] | None = None
|
||
note: str | None = None
|
||
tags: list[str] | None = None
|
||
symptoms: list[Literal['tension', 'headache', 'fatigue', 'restlessness']] | None = None
|
||
|
||
|
||
class DreamInput(BaseModel):
|
||
wake_up_date: str
|
||
title: str
|
||
narrative: str
|
||
dreamed_at: str | None = None
|
||
interpretation: str = ''
|
||
tags: list[str] = Field(default_factory=list)
|
||
emotions: list[str] = Field(default_factory=list)
|
||
vividness: int | None = Field(default=None, ge=0, le=10)
|
||
is_nightmare: bool = False
|
||
after_waking_notes: str = ''
|
||
|
||
|
||
class DreamChanges(BaseModel):
|
||
wake_up_date: str | None = None
|
||
title: str | None = None
|
||
narrative: str | None = None
|
||
dreamed_at: str | None = None
|
||
interpretation: str | None = None
|
||
tags: list[str] | None = None
|
||
emotions: list[str] | None = None
|
||
vividness: int | None = Field(default=None, ge=0, le=10)
|
||
is_nightmare: bool | None = None
|
||
after_waking_notes: str | None = None
|
||
append_narrative: str | None = None
|
||
append_after_waking_notes: str | None = None
|
||
|
||
|
||
def _token() -> str:
|
||
access = get_access_token()
|
||
if access is None:
|
||
raise ToolError('Authentication required. Connect with a TaskNest token or OAuth account.')
|
||
return access.token
|
||
|
||
|
||
def _api_error(response: httpx2.Response) -> ToolError:
|
||
try:
|
||
detail = response.json().get('error', {})
|
||
code = detail.get('code', 'api_error')
|
||
message = detail.get('message', 'TaskNest request failed.')
|
||
except (ValueError, AttributeError):
|
||
code, message = 'api_error', 'TaskNest request failed.'
|
||
return ToolError(f'{code}: {message}')
|
||
|
||
|
||
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:
|
||
async with httpx2.AsyncClient(timeout=20, follow_redirects=False) as client:
|
||
response = await client.request(method, f'{API_BASE}/{path.lstrip("/")}', headers=headers,
|
||
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()
|
||
raise _api_error(response)
|
||
if response.headers.get('content-type', '').startswith('application/json'):
|
||
return response.json()
|
||
return response.content
|
||
|
||
|
||
class ApiTokenVerifier(TokenVerifier):
|
||
async def verify_token(self, token: str) -> AccessToken | None:
|
||
if len(token) > 512 or not token.startswith('tn_'):
|
||
return None
|
||
try:
|
||
info = await api_request('GET', 'auth/whoami/', token=token)
|
||
except ToolError:
|
||
return None
|
||
expiry = datetime.fromisoformat(info['expires_at']).timestamp() if info.get('expires_at') else None
|
||
return AccessToken(token=token, client_id='tasknest', scopes=info['scopes'],
|
||
subject=info['subject'], expires_at=int(expiry) if expiry else None)
|
||
|
||
|
||
def _entry(entry):
|
||
return {'id': entry['id'], 'name': entry['product_name_snapshot'], 'meal': entry['meal'],
|
||
'date': entry['date'], 'amount': entry['amount'], 'unit': entry['unit'],
|
||
'calories_kcal': entry['calories_kcal'], 'carbohydrates_g': entry['carbohydrates_g'],
|
||
'protein_g': entry['protein_g'], 'fat_g': entry['fat_g'], 'fibre_g': entry['fibre_g'],
|
||
'attachments': [{'id': a['id'], 'caption': a['caption']} for a in entry.get('attachments', [])]}
|
||
|
||
|
||
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', 'original_amount', 'unit', 'package_count', 'pieces_per_package',
|
||
'remaining_pieces', 'piece_amount', 'inner_packs_per_package', 'pieces_per_inner_pack',
|
||
'inner_pack_amount', 'inner_pack_label', 'piece_label', 'remaining_full_inner_packs',
|
||
'opened_inner_pack_pieces', 'status', 'archived_at')}
|
||
|
||
|
||
def _key(value):
|
||
return value or str(uuid.uuid4())
|
||
|
||
|
||
def _allowed_file_host(host):
|
||
return host == CHATGPT_BLOB_HOST or any(
|
||
host == allowed or host.endswith('.' + allowed) for allowed in FILE_HOSTS
|
||
)
|
||
|
||
|
||
async def _resolve_image(image_base64, image_file, mime_type, filename):
|
||
if bool(image_base64) == bool(image_file):
|
||
raise ToolError('Provide exactly one image: image_base64 or image_file.')
|
||
if image_file:
|
||
try:
|
||
parsed = urlsplit(image_file.download_url)
|
||
port = parsed.port
|
||
except ValueError:
|
||
raise ToolError('Image download URL is invalid.') from None
|
||
host = (parsed.hostname or '').lower()
|
||
if parsed.scheme != 'https' or not host:
|
||
raise ToolError('Image download URL must be HTTPS with a hostname.')
|
||
if parsed.username or parsed.password or port not in (None, 443):
|
||
raise ToolError('Image download URL contains unsupported credentials or port.')
|
||
if not _allowed_file_host(host):
|
||
# Never log or return the path/query: they may contain a signed URL.
|
||
logger.warning('Rejected image download host %r', host)
|
||
raise ToolError('Image download URL is not an allowed HTTPS file host.')
|
||
try:
|
||
async with httpx2.AsyncClient(timeout=20, follow_redirects=False) as client:
|
||
async with client.stream('GET', image_file.download_url) as response:
|
||
if response.status_code != 200:
|
||
raise ToolError('Could not download the supplied image.')
|
||
if int(response.headers.get('content-length', '0')) > MAX_IMAGE_BYTES:
|
||
raise ToolError('image_too_large: Image exceeds 5 MiB.')
|
||
chunks, size = [], 0
|
||
async for chunk in response.aiter_bytes():
|
||
size += len(chunk)
|
||
if size > MAX_IMAGE_BYTES:
|
||
raise ToolError('image_too_large: Image exceeds 5 MiB.')
|
||
chunks.append(chunk)
|
||
raw = b''.join(chunks)
|
||
mime_type = image_file.mime_type or response.headers.get('content-type', '').split(';', 1)[0]
|
||
filename = image_file.file_name or filename
|
||
except (httpx2.RequestError, TimeoutError):
|
||
raise ToolError('Could not download the supplied image.') from None
|
||
else:
|
||
if len(image_base64) > (MAX_IMAGE_BYTES * 4 // 3) + 16:
|
||
raise ToolError('image_too_large: Image exceeds 5 MiB.')
|
||
try:
|
||
raw = base64.b64decode(image_base64, validate=True)
|
||
except (binascii.Error, ValueError):
|
||
raise ToolError('unsupported_image_type: Invalid base64 image.') from None
|
||
return raw, mime_type, filename
|
||
|
||
|
||
async def _attach(entry_id, image_base64, image_file, mime_type, filename, caption, idempotency_key=None):
|
||
raw, mime_type, filename = await _resolve_image(image_base64, image_file, mime_type, filename)
|
||
if mime_type not in ('image/jpeg', 'image/png', 'image/webp'):
|
||
raise ToolError('unsupported_image_type: Use JPEG, PNG, or WebP.')
|
||
if len(raw) > MAX_IMAGE_BYTES:
|
||
raise ToolError('image_too_large: Image exceeds 5 MiB.')
|
||
safe_name = filename.rsplit('/', 1)[-1].rsplit('\\', 1)[-1][:100] or 'image'
|
||
result = await api_request('POST', f'food/log/{entry_id}/attachments/',
|
||
files={'image': (safe_name, raw, mime_type)}, form={'caption': caption or ''},
|
||
idempotency_key=idempotency_key)
|
||
return {'id': result['id'], 'caption': result['caption'], 'content_type': result['content_type']}
|
||
|
||
|
||
def create_server() -> MCPServer:
|
||
server = MCPServer('TaskNest', description='Private TasksNest tools for Food Diary, saved products, hydration, kitchen inventory, groceries, recipes, nutrition sources, dietary preferences, and stress and dream journals. Read tools inspect the authenticated user’s data; write tools change it and require the corresponding OAuth scope. Search or preview before ambiguous or consequential writes, and reuse idempotency keys on retries. Never infer permission to delete, consume stock, log a meal, or accept a dietary warning from tool availability alone.',
|
||
token_verifier=ApiTokenVerifier(), auth=AuthSettings(
|
||
issuer_url=AnyHttpUrl(OAUTH_ISSUER_URL), resource_server_url=AnyHttpUrl(MCP_PUBLIC_URL),
|
||
required_scopes=[], validate_token_resource=False))
|
||
|
||
@server.tool(structured_output=True, description='Read the authenticated user’s food diary for a specific local calendar day, grouped by meal with totals, goals, and remaining calories/macros. Optional date must be YYYY-MM-DD; omit it for today in the user’s time zone. For “yesterday”, pass yesterday’s calendar date. Does not change data.')
|
||
async def food_get_today(date: str | None = None) -> dict[str, Any]:
|
||
data = await api_request('GET', 'food/today/', params={'date': date} if date is not None else None)
|
||
entries = {meal: [_entry(item) for item in items] for meal, items in data['meals'].items()}
|
||
goals = data.get('goals', {})
|
||
mapping = {'calories_kcal': 'daily_calorie_goal', 'carbohydrates_g': 'carbohydrate_goal_g',
|
||
'protein_g': 'protein_goal_g', 'fat_g': 'fat_goal_g', 'fibre_g': 'fibre_goal_g'}
|
||
remaining = {name: str(Decimal(goals[goal]) - Decimal(data['totals'][name]))
|
||
for name, goal in mapping.items() if goals.get(goal) is not None and
|
||
data['totals'][name] is not None and not data.get('incomplete', {}).get(name, False)}
|
||
return {'date': data['date'], 'meals': entries, 'totals': data['totals'], 'goals': goals,
|
||
'remaining': remaining, 'incomplete': data.get('incomplete', {}),
|
||
'fibre_incomplete': data.get('fibre_incomplete', False)}
|
||
|
||
@server.tool(structured_output=True, description='Search the authenticated user’s saved TaskNest food products before logging a known food. Returns serving sizes, portions, and nutrition per 100 g/ml. Does not change data.')
|
||
async def food_search_products(query: str, limit: int = 20) -> dict[str, Any]:
|
||
data = await api_request('GET', 'food/products/', params={'search': query, 'limit': min(max(limit, 1), 100)})
|
||
fields = ('id', 'product_name', 'brand', 'barcode', 'base_unit', 'package_amount', 'package_unit', 'serving_size_text',
|
||
'serving_amount', 'serving_unit', 'energy_kcal_100', 'carbohydrates_100',
|
||
'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100', 'portions')
|
||
return {'count': data['count'], 'products': [{k: item.get(k) for k in fields} for item in data['results']]}
|
||
|
||
@server.tool(structured_output=True, description='Find food product candidates in saved products and optionally Open Food Facts. Requires food:read. Use for “identify this barcode”; use food_search_products for saved-only search. Read only: never saves a result. Exact barcodes rank first; ask the user to choose an ambiguous match. External lookup may be unavailable.')
|
||
async def food_lookup_product(query: str = '', barcode: str | None = None, brand: str = '',
|
||
package_quantity: Decimal | None = None,
|
||
package_unit: Literal['g', 'ml'] | None = None,
|
||
limit: int = 10, include_open_food_facts: bool = True) -> dict[str, Any]:
|
||
params = {'query': query, 'barcode': barcode or '', 'brand': brand, 'limit': limit,
|
||
'include_open_food_facts': str(include_open_food_facts).lower()}
|
||
if package_quantity is not None:
|
||
params['package_quantity'] = str(package_quantity)
|
||
if package_unit is not None:
|
||
params['package_unit'] = package_unit
|
||
return await api_request('GET', 'food/products/lookup/', params=params)
|
||
|
||
@server.tool(structured_output=True, description='Create a manual food product owned by the authenticated user from supplied facts. No external lookup. Missing nutrition remains unknown; possible duplicates require review. Returns a product_id when created or reused. Reuse idempotency_key on retries.')
|
||
async def food_create_product(product: ProductInput, idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
data = await api_request('POST', 'food/products/create/',
|
||
payload=product.model_dump(mode='json', exclude_none=True), idempotency_key=key)
|
||
return {**data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Save a selected Open Food Facts product by numeric barcode into your product catalogue. Requires food:write. Use after the user selects a lookup candidate; do not use for manual facts or an ambiguous barcode. Changes data, does not invent missing nutrition, and returns a local product_id or a failed-status result. Reuse idempotency_key on retries.')
|
||
async def food_import_product(barcode: str, idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
try:
|
||
data = await api_request('POST', 'food/products/import/', payload={'barcode': barcode}, idempotency_key=key)
|
||
except ToolError as exc:
|
||
return {'status': 'failed', 'reason': str(exc), 'idempotency_key': key}
|
||
return {**data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Create one food log entry for the authenticated user. For known foods, search TaskNest products first and use product_id; do not fabricate nutrition when reliable product data exists. Optional inventory_package_id atomically consumes the logged g/ml from that exact owned package; use a saved product portion conversion and inventory_get_stock to resolve natural units, never guess piece weights. Inventory logging requires idempotency_key; reuse it on retries. Uses the user’s local date unless date is supplied.')
|
||
async def food_log(food: FoodInput, idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
data = await api_request('POST', 'food/log/', payload=food.model_dump(mode='json', exclude_none=True), idempotency_key=key)
|
||
return {'success': True, 'entry': _entry(data), 'inventory_consumption_id': data.get('inventory_consumption_id'), 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Update only the supplied fields of one owned food log entry by opaque ID. Changes existing data; product nutrition is recalculated by TaskNest when applicable.')
|
||
async def food_update_entry(entry_id: str, changes: FoodUpdate) -> dict[str, Any]:
|
||
data = await api_request('PATCH', f'food/log/{entry_id}/', payload=changes.model_dump(mode='json', exclude_unset=True))
|
||
return {'success': True, 'entry': _entry(data)}
|
||
|
||
@server.tool(structured_output=True, description='Permanently delete one food log entry belonging to the authenticated user. This is destructive and also removes its image attachments. Require the user’s clear intent.')
|
||
async def food_delete_entry(entry_id: str) -> dict[str, Any]:
|
||
await api_request('DELETE', f'food/log/{entry_id}/')
|
||
return {'success': True, 'deleted_entry_id': entry_id}
|
||
|
||
@server.tool(structured_output=True, meta={'openai/fileParams': ['image_file']}, description='Attach a client-supplied JPEG, PNG, or WebP image to one owned food entry. Supply either image_file from ChatGPT or image_base64 from a generic client; maximum 5 MiB and 25 megapixels. This adds a private attachment. Reuse idempotency_key on retries.')
|
||
async def food_attach_image(entry_id: str, image_base64: str | None = None, image_file: ClientImageFile = None,
|
||
mime_type: str | None = None, filename: str = 'image', caption: str = '',
|
||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
attachment = await _attach(entry_id, image_base64, image_file, mime_type, filename, caption, key)
|
||
return {'success': True, 'entry_id': entry_id, 'attachment': attachment, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, meta={'openai/fileParams': ['image_file']}, description='Create one food entry and attach the user-supplied image in one operation. Use for “log this photo as dinner.” Supply image_file from ChatGPT or image_base64 from a generic client. Search saved products first when appropriate; knowingly estimated nutrition is allowed. If image upload fails after entry creation, the result explicitly says the entry was created and gives its ID. Reuse idempotency_key on retries.')
|
||
async def food_log_with_image(food: FoodInput, image_base64: str | None = None,
|
||
image_file: ClientImageFile = None, mime_type: str | None = None,
|
||
filename: str = 'image', caption: str = '',
|
||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
created = await api_request('POST', 'food/log/', payload=food.model_dump(mode='json', exclude_none=True), idempotency_key=key)
|
||
result = {'entry_created': True, 'entry': _entry(created), 'idempotency_key': key}
|
||
try:
|
||
result['attachment'] = await _attach(created['id'], image_base64, image_file, mime_type, filename, caption, key + ':image')
|
||
result['attachment_added'] = True
|
||
except ToolError as exc:
|
||
result['attachment_added'] = False
|
||
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)})
|
||
return {'count': data['count'], 'items': [_inventory(item) for item in data['results']]}
|
||
|
||
@server.tool(structured_output=True, description='Search the authenticated user’s current kitchen inventory by food name, brand, barcode, location, or category. Useful for “Do I still have pasta?” Does not change data.')
|
||
async def inventory_search(query: str, limit: int = 30) -> dict[str, Any]:
|
||
data = await api_request('GET', 'kitchen/items/', params={'search': query, 'limit': min(max(limit, 1), 100)})
|
||
return {'count': data['count'], 'items': [_inventory(item) for item in data['results']]}
|
||
|
||
@server.tool(structured_output=True, description='Add an owned saved food product to the authenticated user’s kitchen inventory. Quantity counts outer packages. Optional nested fields define inner_packs_per_package × pieces_per_inner_pack; inner_pack_amount is the measured amount per inner pack, from which per-piece weight is estimated. Do not infer measured amounts. Reuse idempotency_key on retries.')
|
||
async def inventory_add(product_id: str, quantity: int, location: str, category: str | None = None,
|
||
notes: str = '', opened: bool = False, best_before: str | None = None,
|
||
original_amount: Decimal | None = None,
|
||
unit: Literal['mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions'] | None = None,
|
||
pieces_per_package: int | None = None, remaining_pieces: int | None = None,
|
||
piece_amount: Decimal | None = None,
|
||
inner_packs_per_package: int | None = None, pieces_per_inner_pack: int | None = None,
|
||
inner_pack_amount: Decimal | None = None, inner_pack_label: str | None = None,
|
||
piece_label: str | None = None,
|
||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
payload = {'product_id': product_id, 'quantity': quantity, 'location': location,
|
||
'notes': notes, 'opened': opened}
|
||
if category is not None: payload['category'] = category
|
||
if best_before is not None: payload['best_before'] = best_before
|
||
for name, value in (('original_amount', original_amount), ('unit', unit),
|
||
('pieces_per_package', pieces_per_package),
|
||
('remaining_pieces', remaining_pieces), ('piece_amount', piece_amount),
|
||
('inner_packs_per_package', inner_packs_per_package),
|
||
('pieces_per_inner_pack', pieces_per_inner_pack),
|
||
('inner_pack_amount', inner_pack_amount), ('inner_pack_label', inner_pack_label),
|
||
('piece_label', piece_label)):
|
||
if value is not None: payload[name] = str(value) if isinstance(value, Decimal) else value
|
||
item = await api_request('POST', 'kitchen/items/', payload=payload, idempotency_key=key)
|
||
return {'success': True, 'item': _inventory(item), 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Add up to 20 groceries to your inventory in one operation. Resolves owned products, may query Open Food Facts, optionally creates manual products from supplied facts, and adds separate inventory rows. Ambiguous matches require review; each item reports success or failure. Does not interpret images. Reuse idempotency_key with the same payload on retries; changed payloads conflict.')
|
||
async def inventory_import_groceries(items: list[GroceryInput], idempotency_key: str,
|
||
create_missing_products: bool = False) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
data = await api_request('POST', 'kitchen/import-groceries/', payload={
|
||
'items': [item.model_dump(mode='json', exclude_none=True) for item in items],
|
||
'create_missing_products': create_missing_products}, idempotency_key=key)
|
||
return {**data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Update only supplied inventory fields. Quantity is outer-package count. Nested packages can specify inner-pack count, pieces per inner pack, and measured amount per inner pack; estimated piece amounts are derived from those values. Partial deductions by pieces, inner_packs, or matching g/ml are atomic; unsupported conversions return an error.')
|
||
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), 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='Preview or update up to 50 owned inventory rows. Uses inventory_update field rules and returns per-item before/after values and counts. Dry run is default and writes nothing. Partial success is default for compatibility; atomic=true rolls back all updates if any item fails. Actual execution requires an idempotency_key; reuse the same key and payload on retry. Supply expected_updated_at per item to reject concurrent edits.')
|
||
async def inventory_bulk_update(items: list[InventoryBulkUpdateEntry], idempotency_key: str | None = None,
|
||
dry_run: bool = True, atomic: bool = False) -> dict[str, Any]:
|
||
if not dry_run and not idempotency_key:
|
||
raise ToolError('idempotency_key_required: provide an idempotency key for updates')
|
||
data = await api_request('POST', 'kitchen/bulk-update/', payload={
|
||
'items': [{'item_id': row.item_id, 'changes': row.changes.model_dump(mode='json', exclude_unset=True),
|
||
**({'expected_updated_at': row.expected_updated_at} if row.expected_updated_at else {})}
|
||
for row in items], 'dry_run': dry_run, 'atomic': atomic}, idempotency_key=idempotency_key)
|
||
return {**data, 'idempotency_key': idempotency_key}
|
||
|
||
@server.tool(structured_output=True, description='Preview or archive up to 20 explicit owned inventory rows, without deleting products or consumption history. Dry run is default. Actual deletion requires confirm=true, a unique idempotency_key, and clear user intent. Partial success is default; atomic=true rolls back all deletions if any item fails.')
|
||
async def inventory_bulk_delete(item_ids: list[str], idempotency_key: str | None = None,
|
||
dry_run: bool = True, confirm: bool = False, atomic: bool = False) -> dict[str, Any]:
|
||
if not dry_run and (not confirm or not idempotency_key):
|
||
raise ToolError('confirmation_required: confirm=true and idempotency_key are required for deletion')
|
||
data = await api_request('POST', 'kitchen/bulk-delete/', payload={
|
||
'item_ids': item_ids, 'dry_run': dry_run, 'confirm': confirm, 'atomic': atomic},
|
||
idempotency_key=idempotency_key)
|
||
return {**data, 'idempotency_key': idempotency_key}
|
||
|
||
@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.')
|
||
async def inventory_remove(item_id: str) -> dict[str, Any]:
|
||
await api_request('DELETE', f'kitchen/items/{item_id}/')
|
||
return {'success': True, 'removed_item_id': item_id}
|
||
|
||
@server.tool(structured_output=True, description='Read stock for an owned product ID or search query, optionally limited to a location ID. Returns package details and remaining totals. Does not change stock.')
|
||
async def inventory_get_stock(product_id: str | None = None, query: str | None = None,
|
||
location_id: int | None = None) -> dict[str, Any]:
|
||
params = {'product_id': product_id, 'query': query, 'location_id': location_id}
|
||
return await api_request('GET', 'kitchen/stock/', params={k: v for k, v in params.items() if v is not None})
|
||
|
||
@server.tool(structured_output=True, description='Preview package deductions for one owned product without changing stock. Requires inventory:read even though the underlying API uses POST. Use before inventory_consume, especially when stock may be short. Supports configured pieces, inner_packs and matching g/ml; derived per-piece weights are estimates. Unsupported conversions return an error.')
|
||
async def inventory_preview_consumption(product_id: str, amount: Decimal, unit: str,
|
||
package_id: str | None = None) -> dict[str, Any]:
|
||
return await api_request('POST', 'kitchen/consumption/preview/', payload={
|
||
'product_id': product_id, 'amount': str(amount), 'unit': unit, 'package_id': package_id})
|
||
|
||
@server.tool(structured_output=True, description='Consume an exact quantity from owned inventory packages atomically. Requires inventory:write, the user’s clear intent and a unique idempotency key. Preview with inventory_preview_consumption first; use allow_partial only if the user accepts the specific shortage. This changes stock but does not log a Food Diary meal.')
|
||
async def inventory_consume(product_id: str, amount: Decimal, unit: str, idempotency_key: str,
|
||
package_id: str | None = None, source_reference: str = '',
|
||
description: str = '', allow_partial: bool = False) -> dict[str, Any]:
|
||
return await api_request('POST', 'kitchen/consumption/', payload={
|
||
'product_id': product_id, 'amount': str(amount), 'unit': unit,
|
||
'package_id': package_id, 'source_reference': source_reference,
|
||
'description': description, 'allow_partial': allow_partial},
|
||
idempotency_key=idempotency_key)
|
||
|
||
@server.tool(structured_output=True, description='Undo a previous owned inventory consumption transaction when its affected packages have not changed since. Records an auditable reversal.')
|
||
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 by ID. Requires food:write and the user’s clear intent. Does not affect Food Diary entries. Use hydration_update to correct an entry instead of deleting it.')
|
||
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))
|
||
|
||
@server.tool(structured_output=True, description='Search your own recipes by title, description, or ingredient name. Returns recipe IDs and summaries; read only.')
|
||
async def recipe_search(query: str = '', category: str = '', limit: int = 20) -> dict[str, Any]:
|
||
return await api_request('GET', 'recipes/', params={'query': query, 'category': category, 'limit': limit})
|
||
|
||
@server.tool(structured_output=True, description='Read one owned recipe with Markdown instructions, ingredients, substitutions, related variations, and subrecipes. Read only.')
|
||
async def recipe_get(recipe_id: str) -> dict[str, Any]:
|
||
return await api_request('GET', f'recipes/{recipe_id}/')
|
||
|
||
@server.tool(structured_output=True, description='List up to 100 linked recipe suggestions for an owned recipe. Includes incoming suggestions only when the other owner-visible link is reciprocal. Suggestions are not recipe ingredients.')
|
||
async def recipe_link_list(recipe_id: str) -> dict[str, Any]:
|
||
return await api_request('GET', f'recipes/{recipe_id}/links/')
|
||
|
||
@server.tool(structured_output=True, description='Create a one-way or reciprocal suggestion between two owned recipes. This does not add ingredients or change nutrition. Reuse idempotency_key on retries.')
|
||
async def recipe_link_create(recipe_id: str, link: RecipeLinkInput,
|
||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
data = await api_request('POST', f'recipes/{recipe_id}/links/',
|
||
payload=link.model_dump(mode='json'), idempotency_key=key)
|
||
return {**data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Edit the relationship, note, or reciprocal visibility of an owned recipe link.')
|
||
async def recipe_link_update(recipe_id: str, link_id: str,
|
||
changes: RecipeLinkChanges) -> dict[str, Any]:
|
||
return await api_request('PATCH', f'recipes/{recipe_id}/links/{link_id}/',
|
||
payload=changes.model_dump(mode='json', exclude_unset=True))
|
||
|
||
@server.tool(structured_output=True, description='Remove an owned suggestion link. The linked recipe remains unchanged.')
|
||
async def recipe_link_remove(recipe_id: str, link_id: str) -> dict[str, Any]:
|
||
return await api_request('DELETE', f'recipes/{recipe_id}/links/{link_id}/')
|
||
|
||
@server.tool(structured_output=True, description='Preview an explicitly selected set of owned component recipes. Requires food:read, although the API uses POST. Returns ingredient details, nutrition completeness, duplicate ingredient warnings, and issues. Suggestion links are excluded; this does not create a recipe, log a meal, or deduct inventory.')
|
||
async def recipe_composition_preview(components: list[RecipeComponentInput]) -> dict[str, Any]:
|
||
return await api_request('POST', 'recipes/compositions/preview/',
|
||
payload={'components': [item.model_dump(mode='json') for item in components]})
|
||
|
||
@server.tool(structured_output=True, description='Create a new draft recipe that explicitly includes selected owned component recipes. Existing source recipes remain intact. This does not log a meal or deduct inventory. Reuse idempotency_key on retries.')
|
||
async def recipe_composition_create(composition: RecipeCompositionInput,
|
||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
data = await api_request('POST', 'recipes/compositions/',
|
||
payload=composition.model_dump(mode='json'), idempotency_key=key)
|
||
return {'recipe': data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Save one owned recipe to your Cook Later list. Idempotent; does not log a meal or use inventory.')
|
||
async def recipe_cook_later_add(recipe_id: str) -> dict[str, Any]:
|
||
return await api_request('POST', 'recipes/cook-later/', payload={'recipe_id': recipe_id})
|
||
|
||
@server.tool(structured_output=True, description='Remove one owned recipe from your Cook Later list. Repeated removal is safe.')
|
||
async def recipe_cook_later_remove(recipe_id: str) -> dict[str, Any]:
|
||
return await api_request('DELETE', f'recipes/cook-later/{recipe_id}/')
|
||
|
||
@server.tool(structured_output=True, description='List your Cook Later recipes with stable recipe IDs, titles, summaries and save dates. Read only.')
|
||
async def recipe_cook_later_list(search: str = '', limit: int = 20, offset: int = 0) -> dict[str, Any]:
|
||
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. Requires inventory:read and changes nothing. This is a shopping list, not current kitchen stock; use inventory_search for stock.')
|
||
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. Requires inventory:write. Use for “put milk on my shopping list”; use inventory_add only for food already owned. Does not change Kitchen Inventory. Reuse the same idempotency key and payload 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. Preview requires inventory:read; confirm=true requires inventory:write and the user’s approval of the reviewed list. Uncertain matches additionally require confirm_uncertain=true. This changes groceries only, never 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)
|
||
data = await api_request('POST', 'recipes/create/',
|
||
payload=recipe.model_dump(mode='json', exclude_none=True), idempotency_key=key)
|
||
return {'recipe': data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Update supplied fields of one owned recipe, including Markdown and serving yield. Existing variations remain independent.')
|
||
async def recipe_update(recipe_id: str, changes: RecipeChanges) -> dict[str, Any]:
|
||
return await api_request('PATCH', f'recipes/{recipe_id}/',
|
||
payload=changes.model_dump(mode='json', exclude_unset=True))
|
||
|
||
@server.tool(structured_output=True, description='Delete one owned recipe and its ingredients. Existing Food Diary nutrition snapshots remain unchanged. Require clear user intent.')
|
||
async def recipe_delete(recipe_id: str) -> dict[str, Any]:
|
||
return await api_request('DELETE', f'recipes/{recipe_id}/')
|
||
|
||
@server.tool(structured_output=True, description='Create an independently editable copy linked as a variation of the owned recipe. Copies ingredients, substitutions, and subrecipes. Reuse idempotency_key on retries.')
|
||
async def recipe_create_variation(recipe_id: str, title: str | None = None,
|
||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
data = await api_request('POST', f'recipes/{recipe_id}/variations/',
|
||
payload={'title': title} if title else {}, idempotency_key=key)
|
||
return {'recipe': data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Add a measured ingredient to one owned recipe. Use owned food product IDs for unambiguous stock and nutrition matching.')
|
||
async def recipe_ingredient_add(recipe_id: str, ingredient: RecipeIngredientInput,
|
||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
data = await api_request('POST', f'recipes/{recipe_id}/ingredients/',
|
||
payload=ingredient.model_dump(mode='json', exclude_none=True), idempotency_key=key)
|
||
return {'ingredient': data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Correct only the supplied fields of an ingredient in an owned recipe.')
|
||
async def recipe_ingredient_update(recipe_id: str, ingredient_id: int,
|
||
changes: RecipeIngredientChanges) -> dict[str, Any]:
|
||
return await api_request('PATCH', f'recipes/{recipe_id}/ingredients/{ingredient_id}/',
|
||
payload=changes.model_dump(mode='json', exclude_unset=True))
|
||
|
||
@server.tool(structured_output=True, description='Remove one ingredient from an owned recipe. Require clear user intent.')
|
||
async def recipe_ingredient_delete(recipe_id: str, ingredient_id: int) -> dict[str, Any]:
|
||
return await api_request('DELETE', f'recipes/{recipe_id}/ingredients/{ingredient_id}/')
|
||
|
||
@server.tool(structured_output=True, description='Attach another owned recipe as a reusable subrecipe. Cycles and cross-user references are rejected. Reuse idempotency_key on retries.')
|
||
async def recipe_subrecipe_add(recipe_id: str, component_id: str,
|
||
quantity: Decimal = Decimal('1'),
|
||
unit: Literal['servings', 'g', 'ml'] = 'servings',
|
||
note: str = '', idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
data = await api_request('POST', f'recipes/{recipe_id}/subrecipes/',
|
||
payload={'component_id': component_id, 'quantity': str(quantity),
|
||
'unit': unit, 'note': note}, idempotency_key=key)
|
||
return {'subrecipe': data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Remove one reusable subrecipe link from an owned recipe; the component recipe remains.')
|
||
async def recipe_subrecipe_remove(recipe_id: str, subrecipe_id: int) -> dict[str, Any]:
|
||
return await api_request('DELETE', f'recipes/{recipe_id}/subrecipes/{subrecipe_id}/')
|
||
|
||
@server.tool(structured_output=True, description='Check scaled ingredient availability and nutrition, with exact package deductions. Read only. If ready, returns a short-lived confirmation token for explicit inventory deduction.')
|
||
async def recipe_check_inventory(recipe_id: str, options: RecipeAnalysisInput = None) -> dict[str, Any]:
|
||
return await api_request('POST', f'recipes/{recipe_id}/stock/preview/',
|
||
payload=(options or RecipeAnalysisInput()).model_dump(mode='json'))
|
||
|
||
@server.tool(structured_output=True, description='Deduct the exact recipe packages approved in a recent recipe_check_inventory preview. Requires the user’s explicit approval and the returned confirmation token. Replays of the same token do not double count.')
|
||
async def recipe_deduct_inventory(recipe_id: str, confirmation: str) -> dict[str, Any]:
|
||
return await api_request('POST', f'recipes/{recipe_id}/stock/confirm/',
|
||
payload={'confirmation': confirmation})
|
||
|
||
@server.tool(structured_output=True, description='Undo a confirmed recipe inventory deduction when the affected packages have not changed since. Does not remove Food Diary entries.')
|
||
async def recipe_undo_inventory(stock_use_id: str) -> dict[str, Any]:
|
||
return await api_request('POST', f'recipes/stock-use/{stock_use_id}/undo/', payload={})
|
||
|
||
@server.tool(structured_output=True, description='Log a personally consumed portion of an owned recipe to Food Diary using a historical nutrition snapshot. This never deducts inventory. Specify prepared and consumed servings separately; reuse idempotency_key on retries.')
|
||
async def recipe_log_meal(recipe_id: str, consumed_servings: Decimal,
|
||
meal: Literal['breakfast', 'lunch', 'dinner', 'snacks'],
|
||
servings: Decimal | None = None, date: str | None = None,
|
||
time: str | None = None, include_optional: bool = False,
|
||
substitutions: dict[str, str] | None = None,
|
||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
payload = {'consumed_servings': str(consumed_servings), 'meal': meal,
|
||
'include_optional': include_optional,
|
||
'substitutions': substitutions or {}}
|
||
if servings is not None:
|
||
payload['servings'] = str(servings)
|
||
if date is not None:
|
||
payload['date'] = date
|
||
if time is not None:
|
||
payload['time'] = time
|
||
data = await api_request('POST', f'recipes/{recipe_id}/log/',
|
||
payload=payload, idempotency_key=key)
|
||
return {**data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Search or list your private stress check-ins. Optional date is a local YYYY-MM-DD day; timing distinguishes before sleep from after waking. Read only.')
|
||
async def stress_search(query: str = '', date: str | None = None,
|
||
timing: Literal['anytime', 'before_sleep', 'after_waking'] | None = None,
|
||
limit: int = 30, offset: int = 0) -> dict[str, Any]:
|
||
params = {'query': query, 'limit': min(max(limit, 1), 100), 'offset': max(offset, 0)}
|
||
if date is not None:
|
||
params['date'] = date
|
||
if timing is not None:
|
||
params['timing'] = timing
|
||
return await api_request('GET', 'stress/', params=params)
|
||
|
||
@server.tool(structured_output=True, description='Read one stress check-in owned by the authenticated user using its ID. Read only.')
|
||
async def stress_get(entry_id: str) -> dict[str, Any]:
|
||
return await api_request('GET', f'stress/{entry_id}/')
|
||
|
||
@server.tool(structured_output=True, description='Create a private 0–10 stress check-in. Use before_sleep for stress before sleeping and after_waking for stress noticed after waking; do not conflate the two. Reuse idempotency_key on retries and update the returned ID for follow-up details.')
|
||
async def stress_create(entry: StressInput, idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
data = await api_request('POST', 'stress/', payload=entry.model_dump(mode='json', exclude_none=True),
|
||
idempotency_key=key)
|
||
return {**data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Update only supplied fields of one owned stress check-in. Use for conversational corrections or adding details to the existing ID instead of creating a duplicate.')
|
||
async def stress_update(entry_id: str, changes: StressChanges) -> dict[str, Any]:
|
||
return await api_request('PATCH', f'stress/{entry_id}/',
|
||
payload=changes.model_dump(mode='json', exclude_unset=True))
|
||
|
||
@server.tool(structured_output=True, description='Permanently delete one owned stress check-in. Require the user’s clear intent.')
|
||
async def stress_delete(entry_id: str) -> dict[str, Any]:
|
||
return await api_request('DELETE', f'stress/{entry_id}/')
|
||
|
||
@server.tool(structured_output=True, description='List or search your private dreams by keywords, tag, wake-up date or date range. Dates are local YYYY-MM-DD wake-up dates matching Health > Sleep. Read only.')
|
||
async def dream_search(query: str = '', tag: str = '', date: str | None = None,
|
||
date_from: str | None = None, date_to: str | None = None,
|
||
limit: int = 30, offset: int = 0) -> dict[str, Any]:
|
||
params = {'query': query, 'tag': tag, 'limit': min(max(limit, 1), 100), 'offset': max(offset, 0)}
|
||
for key, value in [('date', date), ('date_from', date_from), ('date_to', date_to)]:
|
||
if value is not None:
|
||
params[key] = value
|
||
return await api_request('GET', 'dreams/', params=params)
|
||
|
||
@server.tool(structured_output=True, description='Read one private dream entry by ID, including its original narrative and separately stored interpretation. Read only.')
|
||
async def dream_get(entry_id: str) -> dict[str, Any]:
|
||
return await api_request('GET', f'dreams/{entry_id}/')
|
||
|
||
@server.tool(structured_output=True, description='Create a private dream for its wake-up date. Record only details supplied by the user; do not invent or interpret. Use the returned ID for follow-ups and reuse idempotency_key on retries.')
|
||
async def dream_create(entry: DreamInput, idempotency_key: str | None = None) -> dict[str, Any]:
|
||
key = _key(idempotency_key)
|
||
data = await api_request('POST', 'dreams/', payload=entry.model_dump(mode='json', exclude_none=True),
|
||
idempotency_key=key)
|
||
return {**data, 'idempotency_key': key}
|
||
|
||
@server.tool(structured_output=True, description='Update or append user-supplied corrections to an existing owned dream ID. For append fields, reuse idempotency_key on retries; follow-ups must not create duplicate dreams.')
|
||
async def dream_update(entry_id: str, changes: DreamChanges,
|
||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||
payload = changes.model_dump(mode='json', exclude_unset=True)
|
||
key = _key(idempotency_key) if any(name.startswith('append_') for name in payload) else idempotency_key
|
||
data = await api_request('PATCH', f'dreams/{entry_id}/', payload=payload, idempotency_key=key)
|
||
return {**data, **({'idempotency_key': key} if key else {})}
|
||
|
||
@server.tool(structured_output=True, description='Permanently delete an owned dream entry by ID. Require the user’s clear intent.')
|
||
async def dream_delete(entry_id: str) -> dict[str, Any]:
|
||
return await api_request('DELETE', f'dreams/{entry_id}/')
|
||
|
||
return server
|
||
|
||
|
||
app = create_server().streamable_http_app(
|
||
streamable_http_path='/mcp', stateless_http=True, json_response=True,
|
||
max_request_body_size=8 * 1024 * 1024,
|
||
transport_security=TransportSecuritySettings(
|
||
allowed_hosts=[urlsplit(MCP_PUBLIC_URL).netloc, '127.0.0.1:*', 'localhost:*'],
|
||
allowed_origins=[f'{urlsplit(MCP_PUBLIC_URL).scheme}://{urlsplit(MCP_PUBLIC_URL).netloc}',
|
||
'https://chatgpt.com', 'http://127.0.0.1:*', 'http://localhost:*'],
|
||
),
|
||
)
|
||
|
||
# The SDK uses required_scopes for both metadata and transport authorization.
|
||
# TaskNest authorizes each API operation separately, so leave transport scopes
|
||
# empty and advertise the supported scopes only in the resource metadata route.
|
||
metadata_route = create_protected_resource_routes(
|
||
resource_url=AnyHttpUrl(MCP_PUBLIC_URL),
|
||
authorization_servers=[AnyHttpUrl(OAUTH_ISSUER_URL)],
|
||
scopes_supported=SUPPORTED_SCOPES,
|
||
)[0]
|
||
for index, route in enumerate(app.router.routes):
|
||
if getattr(route, 'path', None) == metadata_route.path:
|
||
app.router.routes[index] = metadata_route
|
||
break
|
||
else:
|
||
raise RuntimeError('MCP protected-resource metadata route is missing.')
|