653 lines
41 KiB
Python
653 lines
41 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']
|
||
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
|
||
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
|
||
|
||
|
||
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)
|
||
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
|
||
|
||
|
||
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)
|
||
|
||
|
||
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()}'}
|
||
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 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', '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='Food diary and kitchen inventory for the authenticated TaskNest user.',
|
||
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 (name == 'fibre_g' and data.get('fibre_incomplete'))}
|
||
return {'date': data['date'], 'meals': entries, 'totals': data['totals'], 'goals': goals,
|
||
'remaining': remaining, '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', '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 your saved products and optionally Open Food Facts. Read only: never saves a search result. Exact barcodes rank first; ambiguous matches are candidates for user selection. 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. Changes data; uses the configured cached external import. Does not invent missing nutrition. Returns a local product_id, or a structured not-found/error response. 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. For a user-requested estimated meal, product_name and estimated nutrition are allowed. Uses the user’s local date unless date is supplied. Reuse idempotency_key on retries.')
|
||
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), '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='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 whole items; location and category use TaskNest’s existing names. 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,
|
||
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
|
||
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 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), 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.')
|
||
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 exact package deductions for one owned product without changing stock. A shortage is reported rather than silently consumed.')
|
||
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 a unique idempotency key. If stock is short, preview first and use allow_partial only with explicit user choice.')
|
||
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. 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))
|
||
|
||
@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='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}
|
||
|
||
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.')
|