"""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 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 best_before: 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): 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: 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'], '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')} 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'} remaining = {name: str(Decimal(goals[goal]) - Decimal(data['totals'][name])) for name, goal in mapping.items() if goals.get(goal) is not None} return {'date': data['date'], 'meals': entries, 'totals': data['totals'], 'goals': goals, 'remaining': remaining} @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='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='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 {'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} 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.')