Compare commits

...
2 Commits
Author SHA1 Message Date
Joren de Graaf c825cd474e in between state for mcp implementation 2026-10-07 15:49:38 +02:00
Joren de Graaf 4f8c3272aa Added food api endpoints prep for mcp 2026-10-07 14:56:24 +02:00
30 changed files with 1823 additions and 115 deletions
+3 -1
View File
@@ -10,6 +10,7 @@ venv/
env/
ENV/
tasksnest-host/
tasksnest/
# Environment / secrets
.env
@@ -24,6 +25,7 @@ local_settings.py
# User-uploaded media
media/
main/private_media/
# Collected static files
staticfiles/
@@ -62,4 +64,4 @@ Thumbs.db
*.sqlite3
playwright/.auth/
#AGENTS.md
#AGENTS.md
+8 -100
View File
@@ -1,113 +1,21 @@
Please update the project's `AGENTS.md` to document our browser-based UI testing workflow.
Playwright MCP is now available to you and should be used when working on frontend, UI, UX, responsive-layout, JavaScript, HTMX, accessibility, or other browser-visible changes.
Add an appropriate section to `AGENTS.md` covering the following requirements.
If needed you can install the required modules for it.
# Project working instructions
## Browser and visual testing
Playwright MCP is available for interacting with and inspecting the actual rendered application.
Use Playwright MCP for frontend, UI, UX, responsive layout, JavaScript, HTMX, accessibility, and other browser-visible changes. Open the running Django application and inspect the rendered result; source inspection alone does not verify appearance or behavior. After a significant change, reload the affected page, inspect it, exercise relevant controls and HTMX interactions, and check the browser console after JavaScript or HTMX changes. Use screenshots for appearance, spacing, typography, sizing, alignment, colour, hierarchy, overflow, and responsive behavior. Use the accessibility/DOM representation for structure, names, labels, state, and interactions. Test desktop and mobile viewports for responsive interfaces, plus intermediate widths where useful. A visual task is incomplete until the rendered result has been inspected.
When working on browser-visible changes:
- Use Playwright to open the running Django application and inspect the actual rendered result.
- Do not judge whether a visual change is correct solely by reading Django templates, HTML, SCSS/CSS, or JavaScript.
- After significant UI changes, reload the relevant page and inspect the result in the browser.
- Use screenshots when evaluating visual appearance, spacing, typography, sizing, alignment, colour, hierarchy, overflow, or responsive behaviour.
- Use the accessibility/DOM representation where it is more appropriate for understanding page structure, controls, labels, state, and interactions.
- Test relevant interactions rather than assuming they work from reading the implementation.
- Check browser console errors after changes involving JavaScript or HTMX.
- Verify important HTMX interactions in the browser.
- Test both desktop and mobile-sized viewports when the affected interface is responsive.
- When appropriate, test intermediate viewport widths as well rather than only the two extremes.
- Do not consider a visual task complete until the rendered result has actually been inspected.
When reporting findings from browser inspection, distinguish between:
1. problems actually observed in the rendered application;
2. accessibility or functional problems discovered through browser inspection;
3. optional design suggestions.
Do not present subjective redesign suggestions as bugs.
Do not redesign unrelated parts of the application simply because browser inspection reveals opportunities for improvement. Keep changes within the requested scope unless explicitly asked otherwise.
In findings, distinguish observed visual problems, accessibility or functional problems found in the browser, and optional design suggestions. Do not present subjective redesign suggestions as bugs or redesign unrelated areas.
## Authentication and demo account
The application has a dedicated demo/test account intended for development and browser testing.
Playwright may use the dedicated demo account to navigate authenticated pages and create, edit, or delete its own test data. Never modify another user's data. Reuse an authenticated Playwright session when available. Credentials may be supplied interactively; never commit passwords, cookies, session or CSRF tokens, or other credentials. Never put demo credentials in this file or source/configuration files. If browser authentication state is exported, store it in `playwright/.auth/` and keep that directory in `.gitignore`.
Playwright may use this account when authentication is required.
## Browser testing behavior
The demo account may be used to:
- navigate authenticated parts of the application;
- create test data;
- edit test data belonging to the demo user;
- delete test data belonging to the demo user;
- exercise forms and interactive features;
- test authenticated HTMX/browser behaviour.
Browser access is for verification and debugging, not permission for arbitrary changes. For an inspection-only request, reproduce and inspect the relevant state, take screenshots when useful, report findings, and leave project files untouched. For an implementation request, inspect the current rendered state when useful, make the requested change, reload and inspect the page, test relevant interactions, check browser errors, inspect relevant viewport sizes, and fix introduced problems. Prefer rendered observations over assumptions from templates or styles.
Never modify data belonging to other users.
Prefer reusing an existing authenticated Playwright browser session when one is available rather than repeatedly logging in.
The demo account credentials should not be written into `AGENTS.md`, source code, committed configuration, or other repository files. They can be supplied interactively when authentication is required.
Do not copy authentication cookies, session tokens, CSRF tokens, passwords, or other credentials into committed files.
If Playwright authentication state is ever exported to a file, store it in a dedicated location such as:
`playwright/.auth/`
and ensure that directory is excluded by `.gitignore`.
## Browser testing behaviour
Browser access is a verification and debugging tool, not permission to make arbitrary changes.
When asked to inspect something without modifying it:
- browse the application;
- reproduce the relevant state;
- inspect it;
- take screenshots if useful;
- report findings;
- do not change project files.
When asked to implement a browser-visible change:
1. inspect the current rendered state when useful;
2. implement the requested change;
3. reload/open the affected page;
4. inspect the rendered result;
5. exercise the relevant interaction if applicable;
6. check for browser/console errors;
7. inspect responsive behaviour where relevant;
8. fix problems introduced by the change before considering the task complete.
For visual verification, prefer observations from the actual rendered application over assumptions derived from source code.
If the Django development server is not running, determine the project's normal development command from the repository rather than inventing a new development setup. Starting the existing development server for browser testing is allowed when appropriate.
Do not alter production configuration merely to make browser testing easier.
If the Django server is stopped, find and use the repository's normal development command. Do not change production configuration to ease testing.
## Accessibility
Use browser testing to help catch accessibility regressions when working on UI.
Where relevant, verify:
- semantic controls and headings;
- accessible names and labels;
- keyboard-operable interactive elements;
- visible focus behaviour;
- sensible form validation/error presentation;
- appropriate ARIA state where custom controls require it;
- obvious colour/contrast or readability problems;
- behaviour at narrow/mobile viewport sizes.
Do not treat the accessibility tree alone as proof that the visual interface is correct. Likewise, do not treat a screenshot alone as proof that the interface is accessible. Use the appropriate browser information for each.
Please integrate these rules cleanly into the existing `AGENTS.md` rather than blindly appending duplicate or conflicting instructions.
Preserve any existing useful project-specific instructions.
Before editing, read the current `AGENTS.md` if one exists and adapt the new section to its existing structure and terminology.
Afterwards, show me the resulting section or summarise exactly what you added. Do not make unrelated project changes.
For UI changes, check relevant semantic headings and controls, accessible names and labels, keyboard operation and visible focus, form errors, ARIA state for custom controls, obvious contrast/readability problems, and narrow viewport behavior. Use both visual inspection and the accessibility/DOM representation where each is appropriate; neither alone proves the other.
+47
View File
@@ -0,0 +1,47 @@
# TaskNest Food and Kitchen API v1
The API is intended for a future thin MCP adapter. It is available under `/api/v1/`; machine-readable OpenAPI 3.1 is at `/api/v1/schema/`. No MCP server or interactive production API UI is included.
## Authentication and permissions
Create a personal token in Settings → API access. The full `tn_...` token is shown once. Send it as `Authorization: Bearer <token>`. A token identifies its owner; API requests do not accept a user identifier. Tokens can have `food:read`, `food:write`, `inventory:read`, and `inventory:write`. A missing, invalid, revoked, or expired token returns HTTP 401. A missing scope returns HTTP 403. The token management screen supports optional expiry and revocation. HTTPS is required in deployment to protect bearer tokens in transit.
Each resource lookup filters by the token owner. An unknown UUID and another user's UUID both return 404. The API does not use session authentication, and its bearer-token views are CSRF exempt. Default Django CORS policy does not grant cross-origin browser access. Do not log `Authorization` headers.
## Endpoints
| Method | Route | Scope | Purpose |
| --- | --- | --- | --- |
| GET | `/food/today/` | `food:read` | User-local date, entries grouped by meal, seven daily totals, and existing goals |
| GET | `/food/products/?search=&limit=30&offset=0` | `food:read` | Own products, nutrition per 100, and portions; no `raw_data` |
| POST | `/food/log/` | `food:write` | Create from an owned `product_id` or manual snapshot |
| GET/PATCH/DELETE | `/food/log/{id}/` | read/write | Own log entry |
| POST | `/food/log/{id}/attachments/` | `food:write` | Multipart image upload to an owned entry |
| GET | `/food/attachments/{id}/file/` | `food:read` | Authenticated image retrieval |
| DELETE | `/food/attachments/{id}/` | `food:write` | Delete an owned image |
| GET/POST | `/kitchen/items/` | read/write | Search/list or create inventory item |
| GET/PATCH/DELETE | `/kitchen/items/{id}/` | read/write | Own inventory item |
Collection responses use `count`, `limit`, `offset`, and `results`. The default limit is 30 and maximum is 100; `offset` is capped at 10,000. Product and inventory search checks name, brand, and barcode; inventory search also checks location and category. `GET /food/today/` is naturally bounded by one day.
JSON decimal values are strings to preserve precision. For food creation, send `meal`, positive decimal `amount`, and `unit` (`g` or `ml`). With `product_id`, nutrition and name snapshots are calculated from that owned product using the same service as the web UI, and the unit must match its basis. Without a product, send `product_name` and optional `brand`, `barcode`, `portion_label`, and nutrition totals (`calories_kcal`, `carbohydrates_g`, `protein_g`, `fat_g`, `fibre_g`, `sugars_g`, `salt_g`). Manual entries are snapshot-only, so repeat estimates do not create duplicate products. `date` defaults to the user's saved local time zone date; an explicit ISO date and optional time can be supplied. API entries have `created_via: api`, separate from their nutrition `source`.
Inventory creation requires an owned product UUID, positive integer `quantity`, and a location name. Optional fields are `category`, `notes`, `opened`, and `best_before`. Location and category names reuse the application's owned lookup records. There is no invented inventory unit: the existing model counts whole items. DELETE removes the item, matching the API operation; the web inventory still has its separate archive behavior.
For attachment upload, send multipart `image` and optional `caption`. JPEG, PNG, and WebP are accepted after decoding and format/MIME checks. The file limit is 5 MiB and the pixel limit is 25 million. Images are stored under `main/private_media/`, which has no public media URL; download requires `food:read` and ownership of the parent entry. Filenames on disk are random. The original filename is metadata only.
POST creation routes accept an optional `Idempotency-Key` header. Repeating the same token, route, key, and body returns the stored result and creates no second record. Reusing a key with a different body or route returns 409. Keys are per token. JSON errors use `{"error":{"code":"...","message":"..."}}`; validation may include `details`. Common codes include `invalid_token`, `expired_token`, `insufficient_scope`, `entry_not_found`, `product_not_found`, `inventory_item_not_found`, `image_too_large`, and `unsupported_image_type`.
## Example requests
```sh
TOKEN='<token-shown-once-in-settings>'
curl -H "Authorization: Bearer $TOKEN" https://example.com/api/v1/food/today/
curl -H "Authorization: Bearer $TOKEN" 'https://example.com/api/v1/food/products/?search=pasta'
curl -X POST https://example.com/api/v1/food/log/ \
-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-H 'Idempotency-Key: dinner-2026-10-07-1' \
-d '{"meal":"dinner","product_name":"Homemade satay","amount":"1","unit":"g","calories_kcal":"850"}'
curl -X POST https://example.com/api/v1/food/log/ENTRY_UUID/attachments/ \
-H "Authorization: Bearer $TOKEN" -F 'image=@meal.jpg;type=image/jpeg' -F 'caption=Dinner'
```
+497
View File
@@ -0,0 +1,497 @@
"""Token-authenticated, owner-scoped HTTP API for future MCP adapters."""
import hashlib
import hmac
import json
import secrets
from django.conf import settings
from decimal import Decimal
from functools import wraps
from uuid import UUID
from PIL import Image, UnidentifiedImageError
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Q
from django.http import FileResponse, JsonResponse
from django.utils import timezone
from django.utils.dateparse import parse_date, parse_time
from django.views.decorators.csrf import csrf_exempt
from planner.models import UserSettings
from planner.timezones import localdate_for_user
from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, FoodProduct,
InventoryCategory, InventoryLocation, KitchenInventoryItem,
MealType, PersonalAccessToken, Unit)
from .services.logging import apply_product_snapshot
SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write'}
NUTRIENTS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
MANUAL_FIELDS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
MAX_IMAGE_BYTES = 5 * 1024 * 1024
def error(code, message, status=400, details=None):
payload = {'error': {'code': code, 'message': message}}
if details:
payload['error']['details'] = details
return JsonResponse(payload, status=status)
def token_value():
prefix = secrets.token_hex(8)
secret = secrets.token_urlsafe(32)
return prefix, f'tn_{prefix}_{secret}'
def create_token(user, name, scopes, expires_at=None):
prefix, value = token_value()
token = PersonalAccessToken.objects.create(user=user, name=name, prefix=prefix,
token_hash=hashlib.sha256(value.encode()).hexdigest(), scopes=sorted(set(scopes)), expires_at=expires_at)
return token, value
def _authenticate(request):
header = request.headers.get('Authorization', '')
if not header.startswith('Bearer '):
return None, error('authentication_required', 'Provide a Bearer API token.', 401)
raw = header[7:]
if len(raw) > 512:
return None, error('invalid_token', 'Invalid API token.', 401)
parts = raw.split('_', 2)
prefix = parts[1] if len(parts) == 3 and parts[0] == 'tn' else ''
token = PersonalAccessToken.objects.select_related('user').filter(prefix=prefix).first() if prefix else None
if token is None or not hmac.compare_digest(token.token_hash, hashlib.sha256(raw.encode()).hexdigest()):
return None, error('invalid_token', 'Invalid API token.', 401)
if token.revoked_at:
return None, error('revoked_token', 'API token has been revoked.', 401)
if token.expires_at and token.expires_at <= timezone.now():
return None, error('expired_token', 'API token has expired.', 401)
PersonalAccessToken.objects.filter(pk=token.pk).update(last_used_at=timezone.now())
return token, None
def api_view(scope, methods):
def decorator(view):
@csrf_exempt
@wraps(view)
def wrapped(request, *args, **kwargs):
if request.method not in methods:
return error('method_not_allowed', 'Method not allowed.', 405)
token, failure = _authenticate(request)
if failure:
return failure
required_scope = scope.get(request.method) if isinstance(scope, dict) else scope
if required_scope and required_scope not in token.scopes:
return error('insufficient_scope', f'Missing {required_scope} scope.', 403)
request.api_token = token
request.api_user = token.user
try:
return view(request, *args, **kwargs)
except (ValueError, ValidationError) as exc:
return error('invalid_request', 'Invalid request data.', 400, str(exc))
return wrapped
return decorator
def _json(request):
if request.content_type != 'application/json':
raise ValueError('Use application/json.')
try:
payload = json.loads(request.body)
except (UnicodeDecodeError, json.JSONDecodeError):
raise ValueError('Malformed JSON.') from None
if not isinstance(payload, dict):
raise ValueError('Expected a JSON object.')
return payload
def _decimal(value, name, positive=False):
try:
result = Decimal(str(value))
except Exception:
raise ValueError(f'Invalid {name}.') from None
if not result.is_finite() or result < 0 or (positive and result == 0):
raise ValueError(f'Invalid {name}.')
return result
def _uuid(value):
try:
return UUID(str(value))
except (TypeError, ValueError, AttributeError):
raise ValueError('Invalid API identifier.') from None
def _date(value, user):
if value is None:
return localdate_for_user(user)
result = parse_date(str(value))
if result is None or result.isoformat() != value:
raise ValueError('Enter date as YYYY-MM-DD.')
return result
def _time(value):
if value is None or value == '':
return None
result = parse_time(str(value))
if result is None:
raise ValueError('Invalid time.')
return result
def _page(request, queryset):
try:
limit = int(request.GET.get('limit', 30))
offset = int(request.GET.get('offset', 0))
except ValueError:
raise ValueError('Invalid pagination.') from None
if not 1 <= limit <= 100 or not 0 <= offset <= 10000:
raise ValueError('Pagination out of range.')
return {'count': queryset.count(), 'limit': limit, 'offset': offset,
'results': queryset[offset:offset + limit]}
def _attachment_data(item):
return {'id': str(item.api_id), 'original_filename': item.original_filename,
'content_type': item.content_type, 'file_size': item.file_size,
'caption': item.caption, 'created_at': item.created_at.isoformat(),
'download_url': f'/api/v1/food/attachments/{item.api_id}/file/'}
def _entry_data(entry):
data = {name: getattr(entry, name) for name in (
'meal', 'product_name_snapshot', 'brand_snapshot', 'barcode_snapshot',
'portion_label_snapshot', 'amount', 'unit', *NUTRIENTS, 'source', 'created_via')}
data.update(id=str(entry.api_id), date=entry.date.isoformat(),
time=entry.time.isoformat() if entry.time else None,
product_id=str(entry.product.api_id) if entry.product_id else None,
attachments=[_attachment_data(item) for item in entry.attachments.all()],
created_at=entry.created_at.isoformat(), updated_at=entry.updated_at.isoformat())
for name in ('amount', *NUTRIENTS):
data[name] = str(data[name]) if data[name] is not None else None
return data
def _product_data(product):
fields = ('product_name', 'brand', 'barcode', 'image_url', 'package_quantity',
'serving_size_text', 'serving_amount', 'serving_unit', 'base_unit',
'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
'fibre_100', 'sugars_100', 'salt_100', 'source')
data = {name: getattr(product, name) for name in fields}
for name in fields:
if isinstance(data[name], Decimal):
data[name] = str(data[name])
data['id'] = str(product.api_id)
data['portions'] = [{'label': p.label, 'amount': str(p.amount), 'unit': p.unit,
'is_default': p.is_default} for p in product.portions.all()]
return data
def _inventory_data(item):
return {'id': str(item.api_id), 'product_id': str(item.product.api_id),
'product_name': item.product.product_name, 'brand': item.product.brand,
'barcode': item.product.barcode, 'quantity': item.quantity,
'location': item.location.name, 'category': item.category.name if item.category else None,
'notes': item.notes, 'opened': item.opened,
'best_before': item.best_before.isoformat() if item.best_before else None,
'added_at': item.added_at.isoformat(), 'updated_at': item.updated_at.isoformat()}
def _idempotent(request, payload, action, digest_override=None):
key = request.headers.get('Idempotency-Key')
if not key:
return action()
if len(key) > 128 or not key.isascii() or any(ord(ch) < 33 or ord(ch) > 126 for ch in key):
return error('invalid_idempotency_key', 'Invalid Idempotency-Key.')
digest = digest_override or hashlib.sha256(request.path.encode() + b'\0' + request.body).hexdigest()
with transaction.atomic():
# Lock the token row so concurrent retries serialize on databases with row locking.
PersonalAccessToken.objects.select_for_update().get(pk=request.api_token.pk)
record = ApiIdempotencyRecord.objects.filter(token=request.api_token, key=key).first()
if record:
if not hmac.compare_digest(record.request_hash, digest):
return error('idempotency_conflict', 'This key was used with another request.', 409)
return JsonResponse(record.response, status=200)
response = action()
if response.status_code < 400:
ApiIdempotencyRecord.objects.create(token=request.api_token, key=key,
request_hash=digest, response=json.loads(response.content))
return response
@api_view('food:read', ('GET',))
def today(request):
day = localdate_for_user(request.api_user)
entries = list(FoodLogEntry.objects.filter(user=request.api_user, date=day)
.select_related('product').prefetch_related('attachments'))
meals = {meal: [_entry_data(e) for e in entries if e.meal == meal] for meal in MealType.values}
totals = {name: str(sum((getattr(e, name) or Decimal('0') for e in entries), Decimal('0')))
for name in NUTRIENTS}
goals = UserSettings.objects.filter(user=request.api_user).first()
goal_data = {name: str(getattr(goals, name)) if goals and getattr(goals, name) is not None else None
for name in ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g')}
return JsonResponse({'date': day.isoformat(), 'meals': meals, 'totals': totals, 'goals': goal_data})
@api_view(None, ('GET',))
def whoami(request):
subject = hashlib.sha256(f'{request.api_user.pk}:{settings.SECRET_KEY}'.encode()).hexdigest()[:24]
return JsonResponse({'subject': subject, 'scopes': request.api_token.scopes,
'expires_at': request.api_token.expires_at.isoformat() if request.api_token.expires_at else None})
@api_view('food:read', ('GET',))
def products(request):
query = request.GET.get('search', '').strip()[:100]
qs = FoodProduct.objects.filter(owner=request.api_user).prefetch_related('portions').order_by('product_name', 'pk')
if query:
qs = qs.filter(Q(product_name__icontains=query) | Q(brand__icontains=query) | Q(barcode__icontains=query))
page = _page(request, qs)
page['results'] = [_product_data(p) for p in page['results']]
return JsonResponse(page)
def _save_entry(request, data, entry=None):
creating = entry is None
if creating:
entry = FoodLogEntry(user=request.api_user, created_via='api')
allowed = {'date', 'time', 'meal', 'product_id', 'product_name', 'brand', 'barcode',
'portion_label', 'amount', 'unit', *MANUAL_FIELDS}
unknown = set(data) - allowed
if unknown:
raise ValueError(f'Unknown fields: {", ".join(sorted(unknown))}.')
if 'date' in data or creating:
entry.date = _date(data.get('date'), request.api_user)
if 'time' in data:
entry.time = _time(data['time'])
if 'meal' in data:
if data['meal'] not in MealType.values:
raise ValueError('Invalid meal.')
entry.meal = data['meal']
if 'amount' in data:
entry.amount = _decimal(data['amount'], 'amount', positive=True)
if 'unit' in data:
if data['unit'] not in Unit.values:
raise ValueError('Invalid unit.')
entry.unit = data['unit']
if 'portion_label' in data:
entry.portion_label_snapshot = str(data['portion_label'])
if not entry.meal or entry.amount is None or not entry.unit:
raise ValueError('meal, amount, and unit are required.')
if 'product_id' in data:
product = FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(data['product_id'])).first()
if product is None:
return None, error('product_not_found', 'Food product not found.', 404)
entry.product = product
if entry.product_id:
if entry.unit != entry.product.base_unit:
raise ValueError('Unit must match the product nutrition basis.')
if any(field in data for field in ('product_name', 'brand', 'barcode', *MANUAL_FIELDS)):
raise ValueError('Product entries calculate nutrition from the product.')
apply_product_snapshot(entry, entry.product)
else:
if 'product_name' in data:
entry.product_name_snapshot = str(data['product_name']).strip()
if 'brand' in data:
entry.brand_snapshot = str(data['brand'])
if 'barcode' in data:
entry.barcode_snapshot = str(data['barcode'])
if not entry.product_name_snapshot:
raise ValueError('product_name is required for manual food.')
entry.source = FoodProduct.Source.MANUAL
for name in MANUAL_FIELDS:
if name in data:
setattr(entry, name, _decimal(data[name], name) if data[name] is not None else None)
entry.full_clean()
entry.save()
return entry, None
@api_view('food:write', ('POST',))
def log_create(request):
data = _json(request)
def create():
entry, failure = _save_entry(request, data)
return failure or JsonResponse(_entry_data(entry), status=201)
return _idempotent(request, data, create)
@api_view('food:read', ('GET',))
def log_detail(request, identifier):
entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).select_related('product').prefetch_related('attachments').first()
return JsonResponse(_entry_data(entry)) if entry else error('entry_not_found', 'Food log entry not found.', 404)
@api_view('food:write', ('PATCH', 'DELETE'))
def log_change(request, identifier):
entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).select_related('product').first()
if entry is None:
return error('entry_not_found', 'Food log entry not found.', 404)
if request.method == 'DELETE':
entry.delete()
return JsonResponse({'deleted': True})
entry, failure = _save_entry(request, _json(request), entry)
return failure or JsonResponse(_entry_data(entry))
@api_view('inventory:read', ('GET',))
def inventory_list(request):
qs = KitchenInventoryItem.objects.filter(user=request.api_user, archived_at__isnull=True)
query = request.GET.get('search', '').strip()[:100]
if query:
qs = qs.filter(Q(product__product_name__icontains=query) | Q(product__brand__icontains=query) |
Q(product__barcode__icontains=query) | Q(location__name__icontains=query) |
Q(category__name__icontains=query))
qs = qs.select_related('product', 'location', 'category').order_by('-added_at', '-pk')
page = _page(request, qs)
page['results'] = [_inventory_data(item) for item in page['results']]
return JsonResponse(page)
def _save_inventory(request, data, item=None):
if item is None:
item = KitchenInventoryItem(user=request.api_user)
allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before'}
if set(data) - allowed:
raise ValueError('Unknown inventory fields.')
if 'product_id' in data:
product = FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(data['product_id'])).first()
if product is None:
return None, error('product_not_found', 'Food product not found.', 404)
item.product = product
if 'quantity' in data:
if isinstance(data['quantity'], bool) or not isinstance(data['quantity'], int) or data['quantity'] < 1:
raise ValueError('Quantity must be a positive integer.')
item.quantity = data['quantity']
if 'location' in data:
name = ' '.join(str(data['location']).split())
if not name or len(name) > 100:
raise ValueError('Invalid location.')
item.location, _ = InventoryLocation.objects.get_or_create(user=request.api_user, name__iexact=name, defaults={'name': name})
if 'category' in data:
name = ' '.join(str(data['category'] or '').split())
if len(name) > 100:
raise ValueError('Invalid category.')
item.category = (InventoryCategory.objects.get_or_create(user=request.api_user, name__iexact=name,
defaults={'name': name})[0] if name else None)
if 'notes' in data:
item.notes = str(data['notes'])
if 'opened' in data:
if not isinstance(data['opened'], bool):
raise ValueError('opened must be a boolean.')
item.opened = data['opened']
if 'best_before' in data:
item.best_before = _date(data['best_before'], request.api_user) if data['best_before'] else None
if not item.product_id or not item.location_id:
raise ValueError('product_id and location are required.')
item.full_clean()
item.save()
return item, None
@api_view('inventory:write', ('POST',))
def inventory_create(request):
data = _json(request)
def create():
item, failure = _save_inventory(request, data)
return failure or JsonResponse(_inventory_data(item), status=201)
return _idempotent(request, data, create)
@api_view('inventory:read', ('GET',))
def inventory_detail(request, identifier):
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier).select_related('product', 'location', 'category').first()
return JsonResponse(_inventory_data(item)) if item else error('inventory_item_not_found', 'Inventory item not found.', 404)
@api_view('inventory:write', ('PATCH', 'DELETE'))
def inventory_change(request, identifier):
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier).select_related('product', 'location', 'category').first()
if item is None:
return error('inventory_item_not_found', 'Inventory item not found.', 404)
if request.method == 'DELETE':
item.delete()
return JsonResponse({'deleted': True})
item, failure = _save_inventory(request, _json(request), item)
return failure or JsonResponse(_inventory_data(item))
@api_view('food:write', ('POST',))
def attachment_create(request, identifier):
entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).first()
if entry is None:
return error('entry_not_found', 'Food log entry not found.', 404)
if int(request.META.get('CONTENT_LENGTH') or 0) > MAX_IMAGE_BYTES + 65536:
return error('image_too_large', 'Image exceeds 5 MB.', 413)
upload = request.FILES.get('image')
if upload is None:
return error('image_required', 'Upload an image field.')
if upload.size > MAX_IMAGE_BYTES:
return error('image_too_large', 'Image exceeds 5 MB.', 413)
try:
image = Image.open(upload)
if image.width * image.height > 25_000_000:
return error('image_too_large', 'Image dimensions are too large.', 413)
image.verify()
image_format = image.format
except (UnidentifiedImageError, OSError, ValueError):
return error('unsupported_image_type', 'Use a valid JPEG, PNG, or WebP image.')
content_types = {'JPEG': 'image/jpeg', 'PNG': 'image/png', 'WEBP': 'image/webp'}
if image_format not in content_types or upload.content_type != content_types[image_format]:
return error('unsupported_image_type', 'Use a valid JPEG, PNG, or WebP image.')
upload.seek(0)
extension = {'JPEG': 'jpg', 'PNG': 'png', 'WEBP': 'webp'}[image_format]
attachment = FoodLogAttachment(log_entry=entry, image=upload,
original_filename=upload.name.rsplit('/', 1)[-1].rsplit('\\', 1)[-1][:255],
content_type=content_types[image_format], file_size=upload.size,
caption=request.POST.get('caption', '')[:255])
attachment.image.name = f'{secrets.token_hex(16)}.{extension}'
def create():
attachment.save()
return JsonResponse(_attachment_data(attachment), status=201)
digest = hashlib.sha256(str(entry.api_id).encode() + b'\0' + upload.read() +
b'\0' + attachment.caption.encode()).hexdigest()
upload.seek(0)
return _idempotent(request, None, create, digest_override=digest)
@api_view('food:read', ('GET',))
def attachment_file(request, identifier):
item = FoodLogAttachment.objects.filter(api_id=identifier, log_entry__user=request.api_user).first()
if item is None:
return error('attachment_not_found', 'Attachment not found.', 404)
response = FileResponse(item.image.open('rb'), content_type=item.content_type)
response['Content-Disposition'] = 'inline'
response['X-Content-Type-Options'] = 'nosniff'
return response
@api_view('food:write', ('DELETE',))
def attachment_delete(request, identifier):
item = FoodLogAttachment.objects.filter(api_id=identifier, log_entry__user=request.api_user).first()
if item is None:
return error('attachment_not_found', 'Attachment not found.', 404)
item.delete()
return JsonResponse({'deleted': True})
@api_view({'GET': 'food:read', 'PATCH': 'food:write', 'DELETE': 'food:write'}, ('GET', 'PATCH', 'DELETE'))
def log_item(request, identifier):
if request.method == 'GET':
return log_detail.__wrapped__(request, identifier)
return log_change.__wrapped__(request, identifier)
@api_view({'GET': 'inventory:read', 'POST': 'inventory:write'}, ('GET', 'POST'))
def inventory_collection(request):
if request.method == 'GET':
return inventory_list.__wrapped__(request)
return inventory_create.__wrapped__(request)
@api_view({'GET': 'inventory:read', 'PATCH': 'inventory:write', 'DELETE': 'inventory:write'}, ('GET', 'PATCH', 'DELETE'))
def inventory_item(request, identifier):
if request.method == 'GET':
return inventory_detail.__wrapped__(request, identifier)
return inventory_change.__wrapped__(request, identifier)
+16
View File
@@ -0,0 +1,16 @@
from django.http import JsonResponse
class ApiErrorMiddleware:
"""Ensure fallback Django errors on API paths remain machine-readable."""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if request.path.startswith('/api/v1/') and response.status_code >= 400 and not response.get('Content-Type', '').startswith('application/json'):
code = 'not_found' if response.status_code == 404 else 'server_error' if response.status_code >= 500 else 'request_error'
message = 'Resource not found.' if response.status_code == 404 else 'Request failed.'
return JsonResponse({'error': {'code': code, 'message': message}}, status=response.status_code)
return response
+85
View File
@@ -0,0 +1,85 @@
"""Small public OpenAPI document; no interactive production documentation UI."""
from django.http import JsonResponse
from django.views.decorators.http import require_GET
def operation(summary, scope, request=None, response=None, multipart=False):
result = {
'summary': summary,
'security': [{'bearerToken': []}],
'x-required-scope': scope,
'responses': {
'200': {'description': 'Success', 'content': {'application/json': {'schema': response or {'type': 'object'}}}},
'400': {'description': 'Invalid request'}, '401': {'description': 'Invalid, revoked, or expired token'},
'403': {'description': 'Missing scope'}, '404': {'description': 'Not found'},
},
}
if request:
result['requestBody'] = {'required': True, 'content': {
'multipart/form-data' if multipart else 'application/json': {'schema': request}}}
return result
ENTRY = {'type': 'object', 'properties': {
'meal': {'type': 'string', 'enum': ['breakfast', 'lunch', 'dinner', 'snacks']},
'product_id': {'type': 'string', 'format': 'uuid'},
'product_name': {'type': 'string'}, 'brand': {'type': 'string'}, 'barcode': {'type': 'string'},
'amount': {'type': 'string', 'description': 'Positive decimal'},
'unit': {'type': 'string', 'enum': ['g', 'ml']},
'date': {'type': 'string', 'format': 'date', 'description': 'Defaults to the user local date'},
'time': {'type': 'string', 'format': 'time'},
'portion_label': {'type': 'string'},
**{field: {'type': ['string', 'null'], 'description': 'Decimal nutrition amount'} for field in
('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')},
}}
INVENTORY = {'type': 'object', 'properties': {
'product_id': {'type': 'string', 'format': 'uuid'}, 'quantity': {'type': 'integer', 'minimum': 1},
'location': {'type': 'string'}, 'category': {'type': 'string'}, 'notes': {'type': 'string'},
'opened': {'type': 'boolean'}, 'best_before': {'type': ['string', 'null'], 'format': 'date'},
}}
UPLOAD = {'type': 'object', 'required': ['image'], 'properties': {
'image': {'type': 'string', 'format': 'binary'}, 'caption': {'type': 'string'},
}}
@require_GET
def schema(request):
document = {
'openapi': '3.1.0', 'info': {'title': 'TaskNest Food and Kitchen API', 'version': '1.0.0'},
'servers': [{'url': '/api/v1'}],
'components': {'securitySchemes': {'bearerToken': {'type': 'http', 'scheme': 'bearer'}}},
'paths': {
'/food/today/': {'get': operation('Current local day food log, meal groups, totals, and goals', 'food:read')},
'/food/products/': {'get': operation('Search own food products', 'food:read')},
'/food/log/': {'post': operation('Create food log entry', 'food:write', ENTRY)},
'/food/log/{id}/': {
'get': operation('Read own entry', 'food:read'),
'patch': operation('Update own entry', 'food:write', ENTRY),
'delete': operation('Delete own entry', 'food:write'),
},
'/food/log/{id}/attachments/': {'post': operation('Upload image for own entry', 'food:write', UPLOAD, multipart=True)},
'/food/attachments/{id}/file/': {'get': operation('Download own attachment', 'food:read')},
'/food/attachments/{id}/': {'delete': operation('Delete own attachment', 'food:write')},
'/kitchen/items/': {
'get': operation('Search own inventory', 'inventory:read'),
'post': operation('Create inventory item', 'inventory:write', INVENTORY),
},
'/kitchen/items/{id}/': {
'get': operation('Read own inventory item', 'inventory:read'),
'patch': operation('Update own inventory item', 'inventory:write', INVENTORY),
'delete': operation('Delete own inventory item', 'inventory:write'),
},
},
}
for path, methods in document['paths'].items():
if '{id}' in path:
methods['parameters'] = [{'name': 'id', 'in': 'path', 'required': True,
'schema': {'type': 'string', 'format': 'uuid'}}]
if 'post' in methods:
methods['post']['responses']['201'] = methods['post']['responses'].pop('200')
document['paths']['/food/attachments/{id}/file/']['get']['responses']['200'] = {
'description': 'Owned image bytes',
'content': {mime: {'schema': {'type': 'string', 'format': 'binary'}}
for mime in ('image/jpeg', 'image/png', 'image/webp')},
}
return JsonResponse(document)
+16
View File
@@ -0,0 +1,16 @@
from django.urls import path
from . import api, api_schema
urlpatterns = [
path('auth/whoami/', api.whoami),
path('schema/', api_schema.schema),
path('food/today/', api.today),
path('food/products/', api.products),
path('food/log/', api.log_create),
path('food/log/<uuid:identifier>/', api.log_item),
path('food/log/<uuid:identifier>/attachments/', api.attachment_create),
path('food/attachments/<uuid:identifier>/file/', api.attachment_file),
path('food/attachments/<uuid:identifier>/', api.attachment_delete),
path('kitchen/items/', api.inventory_collection),
path('kitchen/items/<uuid:identifier>/', api.inventory_item),
]
+4
View File
@@ -4,3 +4,7 @@ from django.apps import AppConfig
class FoodConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'food'
def ready(self):
from . import signals # noqa: F401
from . import oauth_signals # noqa: F401
@@ -0,0 +1,91 @@
# Generated by Django 6.1.1 on 2026-10-07 12:36
import django.db.models.deletion
import uuid
from django.conf import settings
from django.db import migrations, models
def backfill_api_ids(apps, schema_editor):
for model_name in ('FoodLogEntry', 'FoodProduct', 'KitchenInventoryItem'):
model = apps.get_model('food', model_name)
for pk in model.objects.filter(api_id__isnull=True).values_list('pk', flat=True).iterator():
model.objects.filter(pk=pk).update(api_id=uuid.uuid4())
class Migration(migrations.Migration):
dependencies = [
('food', '0003_inventorycategory_inventorylocation_and_more'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddField(
model_name='foodlogentry',
name='api_id',
field=models.UUIDField(null=True, editable=False),
),
migrations.AddField(
model_name='foodlogentry',
name='created_via',
field=models.CharField(default='web', max_length=16),
),
migrations.AddField(
model_name='foodproduct',
name='api_id',
field=models.UUIDField(null=True, editable=False),
),
migrations.AddField(
model_name='kitcheninventoryitem',
name='api_id',
field=models.UUIDField(null=True, editable=False),
),
migrations.RunPython(backfill_api_ids, migrations.RunPython.noop),
migrations.AlterField(model_name='foodlogentry', name='api_id', field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
migrations.AlterField(model_name='foodproduct', name='api_id', field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
migrations.AlterField(model_name='kitcheninventoryitem', name='api_id', field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
migrations.CreateModel(
name='FoodLogAttachment',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('api_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('image', models.ImageField(upload_to='food-attachments/%Y/%m/')),
('original_filename', models.CharField(max_length=255)),
('content_type', models.CharField(max_length=50)),
('file_size', models.PositiveIntegerField()),
('caption', models.CharField(blank=True, max_length=255)),
('created_at', models.DateTimeField(auto_now_add=True)),
('log_entry', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='food.foodlogentry')),
],
),
migrations.CreateModel(
name='PersonalAccessToken',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('prefix', models.CharField(max_length=20, unique=True)),
('token_hash', models.CharField(max_length=64)),
('scopes', models.JSONField(default=list)),
('created_at', models.DateTimeField(auto_now_add=True)),
('last_used_at', models.DateTimeField(blank=True, null=True)),
('expires_at', models.DateTimeField(blank=True, null=True)),
('revoked_at', models.DateTimeField(blank=True, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='personal_access_tokens', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='ApiIdempotencyRecord',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.CharField(max_length=128)),
('request_hash', models.CharField(max_length=64)),
('response', models.JSONField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('token', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='food.personalaccesstoken')),
],
options={
'constraints': [models.UniqueConstraint(fields=('token', 'key'), name='food_unique_api_idempotency_key')],
},
),
]
+40
View File
@@ -1,3 +1,5 @@
import uuid
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
@@ -22,6 +24,7 @@ class MealType(models.TextChoices):
class FoodProduct(models.Model):
api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
class Source(models.TextChoices):
OPEN_FOOD_FACTS = 'openfoodfacts', 'Open Food Facts'
MANUAL = 'manual', 'Manual'
@@ -58,6 +61,7 @@ class FoodProduct(models.Model):
class FoodLogEntry(models.Model):
api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_log_entries')
date = models.DateField(db_index=True)
time = models.TimeField(null=True, blank=True)
@@ -77,6 +81,7 @@ class FoodLogEntry(models.Model):
sugars_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
salt_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
source = models.CharField(max_length=16, choices=FoodProduct.Source.choices, default=FoodProduct.Source.MANUAL)
created_via = models.CharField(max_length=16, default='web')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@@ -156,6 +161,7 @@ class InventoryCategory(models.Model):
class KitchenInventoryItem(models.Model):
api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='kitchen_inventory')
product = models.ForeignKey(FoodProduct, on_delete=models.PROTECT, related_name='inventory_items')
quantity = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1)])
@@ -176,3 +182,37 @@ class KitchenInventoryItem(models.Model):
raise ValidationError({'location': 'Choose one of your own locations.'})
if self.user_id and self.category_id and self.category.user_id != self.user_id:
raise ValidationError({'category': 'Choose one of your own categories.'})
class PersonalAccessToken(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='personal_access_tokens')
name = models.CharField(max_length=100)
prefix = models.CharField(max_length=20, unique=True)
token_hash = models.CharField(max_length=64)
scopes = models.JSONField(default=list)
created_at = models.DateTimeField(auto_now_add=True)
last_used_at = models.DateTimeField(null=True, blank=True)
expires_at = models.DateTimeField(null=True, blank=True)
revoked_at = models.DateTimeField(null=True, blank=True)
class FoodLogAttachment(models.Model):
api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
log_entry = models.ForeignKey(FoodLogEntry, on_delete=models.CASCADE, related_name='attachments')
image = models.ImageField(upload_to='food-attachments/%Y/%m/')
original_filename = models.CharField(max_length=255)
content_type = models.CharField(max_length=50)
file_size = models.PositiveIntegerField()
caption = models.CharField(max_length=255, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
class ApiIdempotencyRecord(models.Model):
token = models.ForeignKey(PersonalAccessToken, on_delete=models.CASCADE)
key = models.CharField(max_length=128)
request_hash = models.CharField(max_length=64)
response = models.JSONField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [models.UniqueConstraint(fields=('token', 'key'), name='food_unique_api_idempotency_key')]
+21
View File
@@ -0,0 +1,21 @@
"""Issue OAuth access tokens as short-lived TaskNest PATs; keep only hashes at rest."""
from datetime import timedelta
from django.utils import timezone
from oauth2_provider.settings import oauth2_settings
from .api import SCOPES, create_token
def oauth_access_token(request):
user = getattr(request, 'user', None)
if not user or not getattr(user, 'is_authenticated', False):
raise ValueError('OAuth access token requires an authenticated user.')
scopes = list(getattr(request, 'scopes', None) or str(getattr(request, 'scope', '')).split())
if not scopes or not set(scopes).issubset(SCOPES):
raise ValueError('Invalid OAuth scopes.')
client = getattr(request, 'client', None)
name = f"MCP: {getattr(client, 'name', '') or 'connected assistant'}"[:100]
_, secret = create_token(user, name, scopes,
expires_at=timezone.now() + timedelta(seconds=oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS))
return secret
+14
View File
@@ -0,0 +1,14 @@
"""Keep OAuth-issued PATs in sync with OAuth access/refresh revocation."""
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.utils import timezone
from oauth2_provider.models import get_access_token_model
from .models import PersonalAccessToken
@receiver(post_delete, sender=get_access_token_model())
def revoke_oauth_pat(sender, instance, **kwargs):
if instance.token_checksum:
PersonalAccessToken.objects.filter(token_hash=instance.token_checksum, revoked_at__isnull=True).update(
revoked_at=timezone.now())
+25
View File
@@ -0,0 +1,25 @@
from decimal import Decimal
NUTRIENTS = (
('energy_kcal_100', 'calories_kcal'),
('carbohydrates_100', 'carbohydrates_g'),
('protein_100', 'protein_g'),
('fat_100', 'fat_g'),
('fibre_100', 'fibre_g'),
('sugars_100', 'sugars_g'),
('salt_100', 'salt_g'),
)
def apply_product_snapshot(entry, product):
"""Apply the same product snapshot and nutrition calculation for web and API logs."""
entry.product = product
entry.product_name_snapshot = product.product_name
entry.brand_snapshot = product.brand
entry.barcode_snapshot = product.barcode
entry.source = product.source
factor = entry.amount / Decimal('100')
for source, target in NUTRIENTS:
value = getattr(product, source)
setattr(entry, target, (value * factor).quantize(Decimal('0.001')) if value is not None else None)
+12
View File
@@ -0,0 +1,12 @@
from django.db import transaction
from django.db.models.signals import post_delete
from django.dispatch import receiver
from .models import FoodLogAttachment
@receiver(post_delete, sender=FoodLogAttachment)
def delete_attachment_file(sender, instance, **kwargs):
if instance.image:
storage, name = instance.image.storage, instance.image.name
transaction.on_commit(lambda: storage.delete(name))
+58
View File
@@ -0,0 +1,58 @@
{% extends 'planner/base.html' %}
{% block title %}API tokens · Tasknest{% endblock %}
{% block content %}
<section class="settings-page">
<p class="eyebrow">Personal preferences</p>
<h1>API tokens</h1>
<p>Give an app access to your food log and kitchen inventory. Keep tokens private.</p>
{% if new_token %}
<section class="settings-card" role="status">
<h2>New token</h2>
<p><strong>Copy this token now. For security reasons it cannot be shown again.</strong></p>
<div class="form-field"><label for="new-api-token">Token</label><input id="new-api-token" type="text" value="{{ new_token }}" readonly autocomplete="off" spellcheck="false"></div>
</section>
{% endif %}
<section class="settings-card">
<h2>Create token</h2>
<form method="post">{% csrf_token %}
{% for field in form %}{% if field.name == 'scopes' %}<fieldset class="token-scope-field"><legend>Permissions</legend>{{ field }}{{ field.errors }}</fieldset>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endif %}{% endfor %}
<button class="button" type="submit">Create token</button>
</form>
</section>
<section class="settings-card">
<h2>Your tokens</h2>
{% for token in tokens %}
<div>
<h3>{{ token.name }}</h3>
<p>Permissions: {{ token.scopes|join:", " }} · Created: {{ token.created_at|date:"SHORT_DATETIME_FORMAT" }} · Last used: {{ token.last_used_at|date:"SHORT_DATETIME_FORMAT"|default:"Never" }}</p>
<p>Status: {% if token.revoked_at %}Revoked{% elif token.expires_at and token.expires_at <= now %}Expired{% else %}Active{% endif %}{% if token.expires_at %} · Expires: {{ token.expires_at|date:"SHORT_DATETIME_FORMAT" }}{% endif %}</p>
{% if not token.revoked_at %}<form method="post" action="{% url 'food:token-revoke' token.pk %}">{% csrf_token %}<button class="button button--secondary" type="submit">Revoke {{ token.name }}</button></form>{% endif %}
</div>
{% empty %}<p>No API tokens yet.</p>{% endfor %}
</section>
<section class="settings-card mcp-helper" data-mcp-helper>
<h2>Connect an AI assistant</h2>
<p>Compatible assistants can use your Food and Kitchen data through MCP. Access is limited to the permissions you grant.</p>
<div class="form-field">
<label for="mcp-server-url">MCP server URL</label>
<input id="mcp-server-url" type="url" value="{{ mcp_url }}" readonly data-mcp-url>
<button class="button button--secondary" type="button" data-mcp-copy-url>Copy URL</button>
</div>
<div class="form-field">
<label for="mcp-token-input">Paste your TaskNest API token</label>
<input id="mcp-token-input" type="password" autocomplete="new-password" spellcheck="false" data-mcp-token>
<div class="mcp-helper__actions">
<button class="button button--secondary" type="button" aria-pressed="false" data-mcp-show>Show token</button>
<button class="button button--secondary" type="button" data-mcp-copy-token>Copy bearer token</button>
</div>
</div>
<p data-mcp-status role="status" aria-live="polite"></p>
<p class="mcp-helper__hint">Treat this token like a password. TaskNest does not save the token you paste here. You can revoke access from your API tokens.</p>
<div class="mcp-helper__clients">
<section><h3>ChatGPT</h3><p>Add a custom MCP app in ChatGPT and enter the MCP server URL. Select OAuth authentication, then sign in to TaskNest and approve the requested permissions. ChatGPT does not use the pasted token field.</p></section>
<section><h3>Open WebUI</h3><p>In Admin Settings → Integrations → External Tool Servers, add an MCP (Streamable HTTP) connection. Use the URL above, choose Bearer authentication, and paste your token into its Key field.</p></section>
<section><h3>Generic MCP client</h3><p>Use Streamable HTTP at the URL above and send <code>Authorization: Bearer &lt;your token&gt;</code> as a separate header. Never put the token in the URL.</p></section>
</div>
</section>
</section>
{% endblock %}
@@ -0,0 +1,25 @@
{% extends 'planner/base.html' %}
{% block title %}Connect an AI assistant · Tasknest{% endblock %}
{% block content %}
<section class="settings-page">
<p class="eyebrow">Secure connection</p>
<h1>Connect an AI assistant</h1>
{% if error %}
<section class="settings-card" role="alert"><h2>Connection could not be approved</h2><p>{{ error.description }}</p></section>
{% else %}
<section class="settings-card">
<h2>Allow {{ application.name }}?</h2>
<p>This assistant is requesting access to your TaskNest account. It can only use the permissions listed here.</p>
<ul>{% for scope in scopes_descriptions %}<li>{{ scope }}</li>{% endfor %}</ul>
<form method="post" id="authorizationForm">
{% csrf_token %}
{% for field in form %}{% if field.is_hidden %}{{ field }}{% endif %}{% endfor %}
{{ form.non_field_errors }}
<button class="button" type="submit" name="allow" value="Authorize">Allow access</button>
<button class="button button--secondary" type="submit" value="Cancel">Cancel</button>
</form>
<p>Review and revoke connected tokens anytime in <a href="{% url 'food:tokens' %}">API tokens</a>.</p>
</section>
{% endif %}
</section>
{% endblock %}
+157
View File
@@ -0,0 +1,157 @@
import hashlib
import io
import json
from datetime import datetime, timedelta, timezone as py_timezone
from decimal import Decimal
from unittest.mock import patch
from PIL import Image
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings
from django.utils import timezone
from planner.models import UserSettings
from .api import create_token
from .models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem, PersonalAccessToken
class FoodApiTests(TestCase):
def setUp(self):
self.a = get_user_model().objects.create_user('api-a', password='test')
self.b = get_user_model().objects.create_user('api-b', password='test')
self.product_a = FoodProduct.objects.create(owner=self.a, product_name='Pasta', energy_kcal_100=Decimal('350'))
self.product_b = FoodProduct.objects.create(owner=self.b, product_name='Private food')
self.entry_b = FoodLogEntry.objects.create(user=self.b, date=timezone.localdate(), meal='lunch',
product=self.product_b, product_name_snapshot='Private food', amount=Decimal('100'), unit='g')
self.location_b = InventoryLocation.objects.create(user=self.b, name='Cupboard')
self.item_b = KitchenInventoryItem.objects.create(user=self.b, product=self.product_b, location=self.location_b)
self.token, self.secret = create_token(self.a, 'Test',
['food:read', 'food:write', 'inventory:read', 'inventory:write'])
def call(self, method, path, data=None, token=None, **headers):
args = {'HTTP_AUTHORIZATION': f'Bearer {token or self.secret}', **headers}
if data is not None:
args['content_type'] = 'application/json'
data = json.dumps(data)
return getattr(self.client, method)(path, data=data, **args)
def test_authentication_scopes_and_token_storage(self):
self.assertNotIn(self.secret, self.token.token_hash)
self.assertEqual(self.token.token_hash, hashlib.sha256(self.secret.encode()).hexdigest())
self.assertEqual(self.call('get', '/api/v1/food/today/').status_code, 200)
self.token.refresh_from_db()
self.assertIsNotNone(self.token.last_used_at)
self.assertEqual(self.call('get', '/api/v1/food/today/', token='bad').status_code, 401)
read_token, read_secret = create_token(self.a, 'Read', ['food:read'])
self.assertEqual(self.call('get', '/api/v1/food/today/', token=read_secret).status_code, 200)
self.assertEqual(self.call('post', '/api/v1/food/log/', {'meal': 'lunch'}, token=read_secret).status_code, 403)
self.assertEqual(self.call('get', '/api/v1/kitchen/items/', token=read_secret).status_code, 403)
read_token.revoked_at = timezone.now()
read_token.save()
self.assertEqual(self.call('get', '/api/v1/food/today/', token=read_secret).status_code, 401)
expired, expired_secret = create_token(self.a, 'Expired', ['food:read'], timezone.now() - timedelta(seconds=1))
self.assertEqual(self.call('get', '/api/v1/food/today/', token=expired_secret).json()['error']['code'], 'expired_token')
def test_owner_isolation_and_products(self):
self.assertEqual(self.call('get', '/api/v1/food/today/').json()['meals']['lunch'], [])
result = self.call('get', '/api/v1/food/products/?search=Private')
self.assertEqual(result.json()['results'], [])
self.assertEqual(self.call('get', f'/api/v1/food/log/{self.entry_b.api_id}/').status_code, 404)
self.assertEqual(self.call('patch', f'/api/v1/food/log/{self.entry_b.api_id}/', {'meal': 'dinner'}).status_code, 404)
self.assertEqual(self.call('delete', f'/api/v1/food/log/{self.entry_b.api_id}/').status_code, 404)
self.assertEqual(self.call('post', f'/api/v1/food/log/{self.entry_b.api_id}/attachments/').status_code, 404)
self.assertEqual(self.call('get', f'/api/v1/kitchen/items/{self.item_b.api_id}/').status_code, 404)
self.assertEqual(self.call('delete', f'/api/v1/kitchen/items/{self.item_b.api_id}/').status_code, 404)
self.assertEqual(self.call('patch', f'/api/v1/kitchen/items/{self.item_b.api_id}/', {'quantity': 2}).status_code, 404)
result = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '100', 'unit': 'g',
'product_id': str(self.product_b.api_id)})
self.assertEqual(result.status_code, 404)
def test_food_crud_and_idempotency(self):
payload = {'meal': 'dinner', 'amount': '50', 'unit': 'g', 'product_id': str(self.product_a.api_id)}
first = self.call('post', '/api/v1/food/log/', payload, HTTP_IDEMPOTENCY_KEY='meal-1')
self.assertEqual(first.status_code, 201, first.content)
self.assertEqual(first.json()['calories_kcal'], '175.000')
second = self.call('post', '/api/v1/food/log/', payload, HTTP_IDEMPOTENCY_KEY='meal-1')
self.assertEqual(second.status_code, 200)
self.assertEqual(FoodLogEntry.objects.filter(user=self.a).count(), 1)
self.assertEqual(self.call('post', '/api/v1/food/log/', {**payload, 'amount': '60'},
HTTP_IDEMPOTENCY_KEY='meal-1').status_code, 409)
identifier = first.json()['id']
self.assertEqual(self.call('patch', f'/api/v1/food/log/{identifier}/', {'amount': '100'}).json()['calories_kcal'], '350.000')
self.assertEqual(self.call('get', f'/api/v1/food/log/{identifier}/').status_code, 200)
self.assertEqual(self.call('delete', f'/api/v1/food/log/{identifier}/').status_code, 200)
self.assertEqual(self.call('post', '/api/v1/food/log/', {**payload, 'amount': '0'}).status_code, 400)
def test_manual_and_inventory_crud(self):
manual = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '1', 'unit': 'g',
'product_name': 'Homemade satay', 'calories_kcal': '850'})
self.assertEqual(manual.status_code, 201, manual.content)
self.assertIsNone(manual.json()['product_id'])
self.assertEqual(manual.json()['created_via'], 'api')
self.assertEqual(self.call('get', '/api/v1/food/today/').json()['totals']['calories_kcal'], '850.000')
payload = {'product_id': str(self.product_a.api_id), 'quantity': 2, 'location': 'Cupboard'}
created = self.call('post', '/api/v1/kitchen/items/', payload, HTTP_IDEMPOTENCY_KEY='item-1')
self.assertEqual(created.status_code, 201, created.content)
self.assertEqual(self.call('post', '/api/v1/kitchen/items/', payload, HTTP_IDEMPOTENCY_KEY='item-1').status_code, 200)
identifier = created.json()['id']
self.assertEqual(self.call('get', '/api/v1/kitchen/items/?search=Pasta').json()['count'], 1)
self.assertEqual(self.call('patch', f'/api/v1/kitchen/items/{identifier}/', {'quantity': 3}).json()['quantity'], 3)
self.assertEqual(self.call('delete', f'/api/v1/kitchen/items/{identifier}/').status_code, 200)
def test_today_uses_user_timezone(self):
UserSettings.objects.create(user=self.a, time_zone='America/Los_Angeles')
with patch('planner.timezones.timezone.now', return_value=datetime(2026, 1, 1, 1, tzinfo=py_timezone.utc)):
self.assertEqual(self.call('get', '/api/v1/food/today/').json()['date'], '2025-12-31')
@override_settings(MEDIA_ROOT='/tmp/tasknest-api-test-media')
def test_attachment_validation_and_isolation(self):
entry = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '1', 'unit': 'g',
'product_name': 'Soup'}).json()
path = f"/api/v1/food/log/{entry['id']}/attachments/"
bad = SimpleUploadedFile('bad.jpg', b'<script>x</script>', content_type='image/jpeg')
response = self.client.post(path, {'image': bad}, HTTP_AUTHORIZATION=f'Bearer {self.secret}')
self.assertEqual(response.status_code, 400)
image = Image.new('RGB', (2, 2), color='red')
stream = io.BytesIO()
image.save(stream, format='PNG')
mismatch = SimpleUploadedFile('wrong.jpg', stream.getvalue(), content_type='image/jpeg')
self.assertEqual(self.client.post(path, {'image': mismatch}, HTTP_AUTHORIZATION=f'Bearer {self.secret}').status_code, 400)
good = SimpleUploadedFile('photo.png', stream.getvalue(), content_type='image/png')
response = self.client.post(path, {'image': good}, HTTP_AUTHORIZATION=f'Bearer {self.secret}')
self.assertEqual(response.status_code, 201, response.content)
for image_format, content_type, filename in [('JPEG', 'image/jpeg', 'photo.jpg'),
('WEBP', 'image/webp', 'photo.webp')]:
stream = io.BytesIO()
image.save(stream, format=image_format)
upload = SimpleUploadedFile(filename, stream.getvalue(), content_type=content_type)
self.assertEqual(self.client.post(path, {'image': upload},
HTTP_AUTHORIZATION=f'Bearer {self.secret}').status_code, 201)
huge = SimpleUploadedFile('large.png', b'X' * (5 * 1024 * 1024 + 1), content_type='image/png')
self.assertEqual(self.client.post(path, {'image': huge},
HTTP_AUTHORIZATION=f'Bearer {self.secret}').status_code, 413)
identifier = response.json()['id']
_, other_secret = create_token(self.b, 'Other', ['food:read', 'food:write'])
self.assertEqual(self.call('get', f'/api/v1/food/attachments/{identifier}/file/', token=other_secret).status_code, 404)
self.assertEqual(self.call('delete', f'/api/v1/food/attachments/{identifier}/', token=other_secret).status_code, 404)
self.assertEqual(self.call('get', f'/api/v1/food/attachments/{identifier}/file/').status_code, 200)
def test_token_management_screen_shows_secret_once(self):
self.client.force_login(self.a)
self.assertEqual(self.client.get('/food/settings/tokens/').status_code, 200)
response = self.client.post('/food/settings/tokens/', {
'name': 'Phone', 'scopes': ['food:read', 'inventory:read']})
self.assertEqual(response.status_code, 200, response.content[:300])
self.assertContains(response, 'Copy this token now')
created = PersonalAccessToken.objects.get(user=self.a, name='Phone')
self.assertNotIn(created.token_hash, response.content.decode())
self.assertNotContains(self.client.get('/food/settings/tokens/'), 'Copy this token now')
self.assertEqual(self.client.post(f'/food/settings/tokens/{created.pk}/revoke/').status_code, 302)
created.refresh_from_db()
self.assertIsNotNone(created.revoked_at)
def test_api_fallback_errors_are_json(self):
response = self.call('get', '/api/v1/does-not-exist/')
self.assertEqual(response.status_code, 404)
self.assertEqual(response['Content-Type'], 'application/json')
+59
View File
@@ -0,0 +1,59 @@
import base64
import hashlib
from urllib.parse import parse_qs, urlparse
from django.contrib.auth import get_user_model
from django.test import TestCase
from oauth2_provider.models import Application, AccessToken
from .models import PersonalAccessToken
class McpOAuthTests(TestCase):
def test_authorization_code_issues_hashed_pat_and_revoke_synchronizes(self):
user = get_user_model().objects.create_user('oauth-test', password='test')
application = Application.objects.create(user=user, name='Test MCP client', client_type=Application.CLIENT_PUBLIC,
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
redirect_uris='http://localhost:9876/callback')
self.client.force_login(user)
verifier = 'v' * 64
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
params = {'response_type': 'code', 'client_id': application.client_id,
'redirect_uri': 'http://localhost:9876/callback', 'scope': 'food:read food:write',
'state': 'test-state', 'code_challenge': challenge, 'code_challenge_method': 'S256',
'resource': 'http://localhost:8002/mcp'}
response = self.client.get('/o/authorize/', params, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200, response.content[:300])
form = response.context['form']
payload = {field.name: field.value() for field in form if field.field.widget.is_hidden and field.value() is not None}
payload['allow'] = 'Authorize'
response = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 302, response.content[:300])
code = parse_qs(urlparse(response['Location']).query)['code'][0]
response = self.client.post('/o/token/', {'grant_type': 'authorization_code', 'code': code,
'redirect_uri': 'http://localhost:9876/callback', 'client_id': application.client_id,
'code_verifier': verifier, 'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200, response.content[:300])
secret = response.json()['access_token']
self.assertTrue(secret.startswith('tn_'))
pat = PersonalAccessToken.objects.get(user=user, token_hash=hashlib.sha256(secret.encode()).hexdigest())
oauth = AccessToken.objects.get(user=user, token_checksum=pat.token_hash)
self.assertEqual(oauth.token, '')
self.assertEqual(self.client.get('/api/v1/auth/whoami/', HTTP_AUTHORIZATION=f'Bearer {secret}',
HTTP_HOST='localhost').status_code, 200)
refresh = response.json()['refresh_token']
response = self.client.post('/o/token/', {'grant_type': 'refresh_token',
'refresh_token': refresh, 'client_id': application.client_id,
'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200, response.content[:300])
renewed = response.json()['access_token']
self.assertNotEqual(secret, renewed)
self.assertEqual(self.client.get('/api/v1/auth/whoami/', HTTP_AUTHORIZATION=f'Bearer {secret}',
HTTP_HOST='localhost').status_code, 401)
secret = renewed
pat = PersonalAccessToken.objects.get(user=user, token_hash=hashlib.sha256(secret.encode()).hexdigest())
oauth = AccessToken.objects.get(user=user, token_checksum=pat.token_hash)
self.client.post(f'/food/settings/tokens/{pat.pk}/revoke/', HTTP_HOST='localhost')
self.assertFalse(AccessToken.objects.filter(pk=oauth.pk).exists())
self.assertEqual(self.client.get('/api/v1/auth/whoami/', HTTP_AUTHORIZATION=f'Bearer {secret}',
HTTP_HOST='localhost').status_code, 401)
+64
View File
@@ -0,0 +1,64 @@
from datetime import datetime, time, timedelta
from django import forms
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone
from django.views.decorators.http import require_http_methods, require_POST
from django.views.decorators.cache import never_cache
from planner.timezones import timezone_for_user
from .api import SCOPES, create_token
from .models import PersonalAccessToken
from oauth2_provider.models import get_access_token_model, revoke_access_token
class TokenForm(forms.Form):
name = forms.CharField(max_length=100, label='Name')
scopes = forms.MultipleChoiceField(choices=[(scope, scope) for scope in sorted(SCOPES)],
widget=forms.CheckboxSelectMultiple, label='Permissions')
expires_on = forms.DateField(required=False, widget=forms.DateInput(attrs={'type': 'date'}),
label='Expiry date (optional)')
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
def clean_expires_on(self):
value = self.cleaned_data['expires_on']
if value and value <= timezone.localdate(timezone=timezone_for_user(self.user)):
raise forms.ValidationError('Choose a future date.')
return value
@login_required
@never_cache
@require_http_methods(['GET', 'POST'])
def tokens(request):
form = TokenForm(request.POST or None, user=request.user)
new_token = None
if request.method == 'POST' and form.is_valid():
expiry = form.cleaned_data['expires_on']
expires_at = timezone.make_aware(datetime.combine(expiry + timedelta(days=1), time.min), timezone_for_user(request.user)) if expiry else None
_, new_token = create_token(request.user, form.cleaned_data['name'], form.cleaned_data['scopes'], expires_at)
form = TokenForm(user=request.user)
return render(request, 'food/tokens.html', {
'form': form, 'new_token': new_token,
'tokens': PersonalAccessToken.objects.filter(user=request.user).order_by('-created_at'),
'now': timezone.now(),
'mcp_url': settings.TASKNEST_MCP_PUBLIC_URL,
})
@login_required
@require_POST
def revoke_token(request, pk):
token = get_object_or_404(PersonalAccessToken, user=request.user, pk=pk)
if token.revoked_at is None:
token.revoked_at = timezone.now()
token.save(update_fields=['revoked_at'])
oauth_token = get_access_token_model().objects.filter(user=request.user, token_checksum=token.token_hash).first()
if oauth_token:
revoke_access_token(oauth_token)
return redirect('food:tokens')
+3 -1
View File
@@ -1,10 +1,12 @@
from django.urls import path
from . import views, inventory
from . import views, inventory, token_views
app_name = 'food'
urlpatterns = [
path('settings/tokens/', token_views.tokens, name='tokens'),
path('settings/tokens/<int:pk>/revoke/', token_views.revoke_token, name='token-revoke'),
path('inventory/', inventory.overview, name='inventory'),
path('inventory/add/', inventory.add, name='inventory-add'),
path('inventory/lookup/', inventory.lookup, name='inventory-lookup'),
+2 -13
View File
@@ -21,6 +21,7 @@ from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealT
from .services.diary import diary_context, selected_date
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
from .services.products import local_products
from .services.logging import apply_product_snapshot
from planner.timezones import localdate_for_user
@@ -120,19 +121,7 @@ def _save_entry(form, user, day, product):
entry = form.save(commit=False)
entry.user = user
entry.date = day
entry.product = product
entry.product_name_snapshot = product.product_name
entry.brand_snapshot = product.brand
entry.barcode_snapshot = product.barcode
entry.source = product.source
factor = entry.amount / Decimal('100')
for source, target in (
('energy_kcal_100', 'calories_kcal'), ('carbohydrates_100', 'carbohydrates_g'),
('protein_100', 'protein_g'), ('fat_100', 'fat_g'), ('fibre_100', 'fibre_g'),
('sugars_100', 'sugars_g'), ('salt_100', 'salt_g'),
):
value = getattr(product, source)
setattr(entry, target, (value * factor).quantize(Decimal('0.001')) if value is not None else None)
apply_product_snapshot(entry, product)
entry.full_clean()
entry.save()
_save_custom_portion(form, user, product, entry)
+28
View File
@@ -78,6 +78,34 @@ function initialiseMobileNavigation() {
document.addEventListener('DOMContentLoaded', initialiseMobileNavigation);
function initialiseMcpHelper() {
const helper = document.querySelector('[data-mcp-helper]');
if (!helper) return;
const token = helper.querySelector('[data-mcp-token]');
const url = helper.querySelector('[data-mcp-url]');
const status = helper.querySelector('[data-mcp-status]');
const show = helper.querySelector('[data-mcp-show]');
const clear = () => { token.value = ''; token.type = 'password'; show.textContent = 'Show token'; show.setAttribute('aria-pressed', 'false'); };
window.addEventListener('pageshow', clear);
window.addEventListener('pagehide', clear);
show.addEventListener('click', () => {
const visible = token.type === 'password';
token.type = visible ? 'text' : 'password';
show.textContent = visible ? 'Hide token' : 'Show token';
show.setAttribute('aria-pressed', String(visible));
token.focus();
});
async function copy(value, success) {
if (!value) { status.textContent = 'Paste a token first.'; token.focus(); return; }
try { await navigator.clipboard.writeText(value); status.textContent = success; }
catch { status.textContent = 'Copy was unavailable. Select and copy the field instead.'; }
}
helper.querySelector('[data-mcp-copy-url]').addEventListener('click', () => copy(url.value, 'Copied URL'));
helper.querySelector('[data-mcp-copy-token]').addEventListener('click', () => copy(token.value, 'Copied bearer token'));
}
document.addEventListener('DOMContentLoaded', initialiseMcpHelper);
let fastingTimerInterval;
+12
View File
@@ -583,3 +583,15 @@ body[data-theme="dark"] .gitea-activity__summary strong { color: #9bd5ae; }
body[data-theme="dark"] .gitea-activity__cell--0 { background: #303a33; }
body[data-theme="dark"] .gitea-activity__cell--future { background: transparent; }
@media (max-width: 560px) { .gitea-activity { padding: 22px; }.gitea-activity__header { align-items: start; }.gitea-activity__header h2 { font-size: 1.45rem; } }
.token-scope-field { border: 0; padding: 0; margin: 0 0 16px; }
.token-scope-field legend { margin-bottom: 8px; font-size: .82rem; font-weight: 700; }
.token-scope-field > div { display: grid; gap: 6px; }
.token-scope-field label { display: flex; align-items: center; gap: 10px; font-size: .88rem; font-weight: 600; cursor: pointer; }
.token-scope-field input[type='checkbox'] { width: 16px; height: 16px; margin: 0; flex: none; }
.mcp-helper__actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px; }
.mcp-helper__clients { display: grid; gap: 14px; margin: 18px 0; }
.mcp-helper__clients section { border-top: 1px solid rgba(128, 150, 135, .3); padding-top: 12px; }
.mcp-helper__clients h3 { margin: 0 0 6px; }
.mcp-helper__clients p { margin: 0; }
.mcp-helper__hint { font-size: .85rem; }
.mcp-helper [data-mcp-status] { min-height: 1.5em; font-weight: 700; }
+1
View File
@@ -0,0 +1 @@
"""TaskNest's HTTP-only MCP adapter."""
+304
View File
@@ -0,0 +1,304 @@
"""Streamable HTTP MCP adapter. All application operations cross the HTTP API."""
import base64
import binascii
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.settings import AuthSettings
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
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', 'http://127.0.0.1:8002/mcp')
OAUTH_ISSUER_URL = os.environ.get('TASKNEST_OAUTH_ISSUER_URL', 'http://127.0.0.1:1234')
MAX_IMAGE_BYTES = 5 * 1024 * 1024
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())
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())
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:
parsed = urlsplit(image_file.download_url)
host = (parsed.hostname or '').lower()
if parsed.scheme != 'https' or not host or parsed.username or parsed.password or parsed.port not in (None, 443) or not any(
host == allowed or host.endswith('.' + allowed) for allowed in FILE_HOSTS
):
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 today’s food diary for the authenticated TaskNest user, grouped by meal with totals, goals, and remaining calories/macros. Does not change data.')
async def food_get_today() -> dict[str, Any]:
data = await api_request('GET', 'food/today/')
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 = 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 = 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)
+191
View File
@@ -0,0 +1,191 @@
import asyncio
import base64
import hashlib
import io
import os
import socket
import subprocess
import sys
import time
import uuid
from datetime import timedelta
from decimal import Decimal
from urllib.parse import parse_qs, urlparse
import httpx2
from PIL import Image
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import LiveServerTestCase
from django.utils import timezone
from mcp import Client
from mcp.client.streamable_http import streamable_http_client
from oauth2_provider.models import Application
from food.api import create_token
from food.models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem
from planner.timezones import localdate_for_user
class McpHttpTests(LiveServerTestCase):
def setUp(self):
self.a = get_user_model().objects.create_user('mcp-a', password='test')
self.b = get_user_model().objects.create_user('mcp-b', password='test')
self.a_product = FoodProduct.objects.create(owner=self.a, product_name='Pasta', energy_kcal_100=Decimal('350'))
self.b_product = FoodProduct.objects.create(owner=self.b, product_name='Private rice')
self.b_entry = FoodLogEntry.objects.create(user=self.b, date=localdate_for_user(self.b), meal='lunch',
product=self.b_product, product_name_snapshot='Private rice', amount=Decimal('100'), unit='g')
location = InventoryLocation.objects.create(user=self.b, name='Private cupboard')
self.b_item = KitchenInventoryItem.objects.create(user=self.b, product=self.b_product, location=location)
_, self.secret = create_token(self.a, 'MCP test', ['food:read', 'food:write', 'inventory:read', 'inventory:write'])
_, self.b_secret = create_token(self.b, 'MCP test B', ['food:read', 'inventory:read'])
_, self.read_secret = create_token(self.a, 'MCP read', ['food:read'])
expired, self.expired_secret = create_token(self.a, 'MCP expired', ['food:read'], timezone.now() - timedelta(seconds=1))
revoked, self.revoked_secret = create_token(self.a, 'MCP revoked', ['food:read'])
revoked.revoked_at = timezone.now()
revoked.save(update_fields=['revoked_at'])
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
self.port = sock.getsockname()[1]
self.mcp_url = f'http://127.0.0.1:{self.port}/mcp'
env = {**os.environ, 'TASKNEST_API_BASE_URL': self.live_server_url + '/api/v1',
'TASKNEST_MCP_PUBLIC_URL': self.mcp_url,
'TASKNEST_OAUTH_ISSUER_URL': self.live_server_url}
self.process = subprocess.Popen([sys.executable, '-m', 'uvicorn', 'mcp_server.server:app',
'--host', '127.0.0.1', '--port', str(self.port), '--log-level', 'error'],
cwd=settings.BASE_DIR, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(50):
try:
response = httpx2.get(f'http://127.0.0.1:{self.port}/.well-known/oauth-protected-resource/mcp', timeout=1)
if response.status_code == 200:
break
except httpx2.RequestError:
pass
time.sleep(.1)
else:
self.fail('MCP server did not start.')
def tearDown(self):
self.process.terminate()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait(timeout=5)
async def _client(self, secret, operation):
async with httpx2.AsyncClient(headers={'Authorization': 'Bearer ' + secret}, timeout=30) as http:
async with Client(streamable_http_client(self.mcp_url, http_client=http)) as client:
return await operation(client)
def test_authentication_and_scope_boundaries(self):
async def check():
for secret in ('bad-token', self.expired_secret, self.revoked_secret):
async with httpx2.AsyncClient(timeout=10) as http:
response = await http.post(self.mcp_url, headers={'Authorization': 'Bearer ' + secret,
'Accept': 'application/json, text/event-stream'}, json={'jsonrpc': '2.0', 'id': 1, 'method': 'tools/list'})
self.assertEqual(response.status_code, 401)
async def read_only(client):
self.assertFalse((await client.call_tool('food_get_today')).is_error)
self.assertTrue((await client.call_tool('inventory_list')).is_error)
self.assertTrue((await client.call_tool('food_log', {'food': {
'meal': 'lunch', 'amount': '1', 'unit': 'g', 'product_name': 'No write'}})).is_error)
await self._client(self.read_secret, read_only)
asyncio.run(check())
def test_oauth_issued_pat_authenticates_mcp(self):
application = Application.objects.create(user=self.a, name='Test ChatGPT style client',
client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
redirect_uris='http://localhost:9876/callback')
self.client.force_login(self.a)
verifier = 'v' * 64
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
params = {'response_type': 'code', 'client_id': application.client_id,
'redirect_uri': 'http://localhost:9876/callback', 'scope': 'food:read',
'state': 'mcp-oauth-test', 'code_challenge': challenge, 'code_challenge_method': 'S256',
'resource': self.mcp_url}
response = self.client.get('/o/authorize/', params, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200)
form = response.context['form']
payload = {field.name: field.value() for field in form if field.field.widget.is_hidden and field.value() is not None}
payload['allow'] = 'Authorize'
redirect = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
code = parse_qs(urlparse(redirect['Location']).query)['code'][0]
response = self.client.post('/o/token/', {'grant_type': 'authorization_code', 'code': code,
'redirect_uri': 'http://localhost:9876/callback', 'client_id': application.client_id,
'code_verifier': verifier, 'resource': self.mcp_url}, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200, response.content[:200])
secret = response.json()['access_token']
async def check(client):
self.assertFalse((await client.call_tool('food_get_today')).is_error)
self.assertTrue((await client.call_tool('inventory_list')).is_error)
asyncio.run(self._client(secret, check))
def test_food_inventory_tools_and_user_isolation(self):
image = Image.new('RGB', (2, 2), 'red')
output = io.BytesIO()
image.save(output, format='PNG')
encoded = base64.b64encode(output.getvalue()).decode()
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertEqual(len(names), 12)
today = (await client.call_tool('food_get_today')).structured_content
self.assertEqual(today['meals']['lunch'], [])
products = (await client.call_tool('food_search_products', {'query': 'Pasta'})).structured_content
self.assertEqual(products['count'], 1)
self.assertEqual((await client.call_tool('food_search_products', {'query': 'Private rice'})).structured_content['count'], 0)
food = {'meal': 'dinner', 'amount': '50', 'unit': 'g', 'product_id': str(self.a_product.api_id)}
first = (await client.call_tool('food_log', {'food': food, 'idempotency_key': 'mcp-food-1'})).structured_content
self.assertEqual(first['entry']['calories_kcal'], '175.000')
again = (await client.call_tool('food_log', {'food': food, 'idempotency_key': 'mcp-food-1'})).structured_content
self.assertEqual(first['entry']['id'], again['entry']['id'])
entry_id = first['entry']['id']
updated = (await client.call_tool('food_update_entry', {'entry_id': entry_id,
'changes': {'amount': '100'}})).structured_content
self.assertEqual(updated['entry']['calories_kcal'], '350.000')
image_result = (await client.call_tool('food_attach_image', {'entry_id': entry_id,
'image_base64': encoded, 'mime_type': 'image/png', 'filename': 'meal.png',
'idempotency_key': 'mcp-image-1'})).structured_content
self.assertTrue(image_result['success'])
combined_food = {'meal': 'lunch', 'amount': '1', 'unit': 'g',
'product_name': 'Estimated meal', 'calories_kcal': '850'}
combined = (await client.call_tool('food_log_with_image', {'food': combined_food,
'image_base64': encoded, 'mime_type': 'image/png', 'idempotency_key': 'mcp-combined-1'})).structured_content
self.assertTrue(combined['attachment_added'])
partial = (await client.call_tool('food_log_with_image', {'food': combined_food,
'image_base64': 'bad!', 'mime_type': 'image/png', 'idempotency_key': 'mcp-combined-2'})).structured_content
self.assertTrue(partial['entry_created'])
self.assertFalse(partial['attachment_added'])
self.assertTrue((await client.call_tool('food_log', {'food': {'meal': 'lunch', 'amount': '0',
'unit': 'g', 'product_name': 'Invalid'}})).is_error)
self.assertTrue((await client.call_tool('food_update_entry', {'entry_id': str(self.b_entry.api_id),
'changes': {'meal': 'dinner'}})).is_error)
self.assertTrue((await client.call_tool('food_attach_image', {'entry_id': str(self.b_entry.api_id),
'image_base64': encoded, 'mime_type': 'image/png'})).is_error)
self.assertTrue((await client.call_tool('food_delete_entry', {'entry_id': str(self.b_entry.api_id)})).is_error)
self.assertTrue((await client.call_tool('food_log', {'food': {'meal': 'dinner', 'amount': '1',
'unit': 'g', 'product_id': str(self.b_product.api_id)}})).is_error)
await client.call_tool('food_delete_entry', {'entry_id': entry_id})
await client.call_tool('food_delete_entry', {'entry_id': combined['entry']['id']})
await client.call_tool('food_delete_entry', {'entry_id': partial['entry']['id']})
self.assertEqual((await client.call_tool('inventory_list')).structured_content['count'], 0)
self.assertEqual((await client.call_tool('inventory_search', {'query': 'Private'})).structured_content['count'], 0)
args = {'product_id': str(self.a_product.api_id), 'quantity': 2, 'location': 'Pantry',
'idempotency_key': 'mcp-item-1'}
item = (await client.call_tool('inventory_add', args)).structured_content['item']
again = (await client.call_tool('inventory_add', args)).structured_content['item']
self.assertEqual(item['id'], again['id'])
self.assertEqual((await client.call_tool('inventory_search', {'query': 'Pasta'})).structured_content['count'], 1)
changed = (await client.call_tool('inventory_update', {'item_id': item['id'],
'changes': {'quantity': 3}})).structured_content
self.assertEqual(changed['item']['quantity'], 3)
self.assertTrue((await client.call_tool('inventory_update', {'item_id': str(self.b_item.api_id),
'changes': {'quantity': 3}})).is_error)
self.assertTrue((await client.call_tool('inventory_remove', {'item_id': str(self.b_item.api_id)})).is_error)
await client.call_tool('inventory_remove', {'item_id': item['id']})
asyncio.run(self._client(self.secret, check))
async def other(client):
self.assertEqual((await client.call_tool('food_get_today')).structured_content['meals']['lunch'][0]['name'], 'Private rice')
self.assertEqual((await client.call_tool('inventory_list')).structured_content['count'], 1)
asyncio.run(self._client(self.b_secret, other))
@@ -9,6 +9,7 @@
<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Enable Sick Day Mode</strong><small>Give routine tasks a rest while you recover.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section>
<section class="settings-card"><h2>Hydration</h2><p>Set your daily water goal.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save water goal</button></form></section>
<section class="settings-card"><h2>Food</h2><p>Set optional daily nutrition goals. Exercise calories do not change these goals.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="food">{% for field in food_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food goals</button></form></section>
<section class="settings-card"><h2>API access</h2><p>Create scoped tokens for apps that need access to your food log or kitchen inventory.</p><a class="button" href="{% url 'food:tokens' %}">Manage API tokens</a></section>
<section class="settings-card" aria-labelledby="ntfy-title">
<h2 id="ntfy-title">Notifications / ntfy</h2>
<p>Enter your private topic URL, test it, then enable notifications.</p>
+3
View File
@@ -1,5 +1,8 @@
asarPy==1.0.1
asgiref==3.12.1
Django==6.1.1
Pillow==12.3.0
django-oauth-toolkit==3.4.1
mcp==2.3.0
h3==4.5.0
sqlparse==0.6.0
+32
View File
@@ -41,11 +41,13 @@ INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'oauth2_provider',
'planner',
'food.apps.FoodConfig',
]
MIDDLEWARE = [
'food.api_middleware.ApiErrorMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
@@ -58,6 +60,35 @@ MIDDLEWARE = [
ROOT_URLCONF = 'tasksnest.urls'
OAUTH2_PROVIDER = {
'OIDC_ISS_ENDPOINT': os.environ.get('TASKNEST_OAUTH_ISSUER_URL',
'http://127.0.0.1:1234/' if DEBUG else 'https://tasksnest.jorendegraaf.eu/'),
'SCOPES': {
'food:read': 'Read your food diary and saved foods',
'food:write': 'Create, change, and delete food diary entries and images',
'inventory:read': 'Read your kitchen inventory',
'inventory:write': 'Create, change, and remove kitchen inventory items',
},
'ACCESS_TOKEN_GENERATOR': 'food.oauth_pat.oauth_access_token',
'ACCESS_TOKEN_EXPIRE_SECONDS': 3600,
'REFRESH_TOKEN_EXPIRE_SECONDS': 604800,
'ROTATE_REFRESH_TOKEN': True,
'REFRESH_TOKEN_REUSE_PROTECTION': True,
'CIMD_ENABLED': True,
'DCR_ENABLED': False,
'OAUTH2_GRANT_TYPES_SUPPORTED': ['authorization_code', 'refresh_token'],
'OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED': ['none', 'client_secret_basic', 'client_secret_post'],
'COMPLIANT_BCP_RFC9700_TOKEN_STORAGE': True,
'COMPLIANT_BCP_RFC9700_PKCE_METHOD': True,
'COMPLIANT_BCP_RFC9700_PKCE_REQUIRED': True,
'COMPLIANT_BCP_RFC9700_ACCESS_TOKEN_TRANSPORT': True,
'COMPLIANT_BCP_RFC9700_AUTHZ_RESPONSE_ISS': True,
'COMPLIANT_BCP_RFC9700_IMPLICIT_GRANT': True,
'COMPLIANT_BCP_RFC9700_PASSWORD_GRANT': True,
}
TASKNEST_MCP_PUBLIC_URL = os.environ.get('TASKNEST_MCP_PUBLIC_URL',
'http://127.0.0.1:8002/mcp' if DEBUG else 'https://tasksnest.jorendegraaf.eu/mcp')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
@@ -123,6 +154,7 @@ USE_TZ = True
# https://docs.djangoproject.com/en/6.1/howto/static-files/
STATIC_URL = 'static/'
MEDIA_ROOT = BASE_DIR / 'private_media'
# Vite writes production assets and its manifest here. In development templates
# load modules from the Vite server configured by VITE_DEV_SERVER.
+4
View File
@@ -16,8 +16,12 @@ Including another URLconf
"""
from django.contrib import admin
from django.urls import include, path
from oauth2_provider.urls import metadata_urlpatterns
urlpatterns = [
path('', include(metadata_urlpatterns)),
path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
path('api/v1/', include('food.api_urls')),
path('admin/', admin.site.urls),
path('food/', include('food.urls', namespace='food')),
path('', include('planner.urls')),