This commit is contained in:
Joren de Graaf
2026-10-09 14:43:46 +02:00
parent c825cd474e
commit 559c51e9bb
20 changed files with 322 additions and 27 deletions
+58
View File
@@ -0,0 +1,58 @@
# TaskNest MCP server
The Streamable HTTP MCP endpoint exposes the Food and Kitchen API to an AI assistant. The server in `mcp_server.server` is an HTTP adapter: every user operation goes through `/api/v1/` with the connected user's bearer token. It does not read Django models directly.
## Local development
Install `main/requirements.txt` in the project virtual environment and run Django migrations. Start Django using the project's normal development command on port 1234, then start MCP from `main/`:
```sh
python -m uvicorn mcp_server.server:app --host 127.0.0.1 --port 8002
```
The endpoint is `http://127.0.0.1:8002/mcp`. Its protected resource metadata is at `/.well-known/oauth-protected-resource/mcp`. Django serves OAuth authorization server metadata at `/.well-known/oauth-authorization-server` and OAuth endpoints under `/o/`.
Set these variables in the MCP process for deployment:
| Variable | Purpose |
| --- | --- |
| `TASKNEST_API_BASE_URL` | Internal Django API URL ending in `/api/v1` |
| `TASKNEST_MCP_PUBLIC_URL` | Public HTTPS MCP URL ending in `/mcp` |
| `TASKNEST_OAUTH_ISSUER_URL` | Public HTTPS Django origin used in OAuth metadata |
| `TASKNEST_MCP_FILE_HOSTS` | Comma-separated HTTPS host allowlist for client-supplied file downloads |
Set `TASKNEST_MCP_PUBLIC_URL` and `TASKNEST_OAUTH_ISSUER_URL` in Django as well. Keep the issuer URL consistent between both processes. The checked-in defaults use `https://tasksnest.jorendegraaf.eu/`; override both variables with local URLs when testing local OAuth. Do not place personal access tokens in URLs or environment variables. Bind MCP to loopback only when Caddy runs on the **same host**. When Caddy runs on another host and proxies to the app host's Tailnet address, bind MCP to that Tailnet address instead. The MCP process should have the same restart and logging policy as the Django service.
The public `/mcp` path **must** reach the MCP process, not Django. For the site's Caddy proxy, route the exact MCP path and protected-resource metadata to the MCP listener, and let the existing Django route handle OAuth metadata and `/o/`:
```caddyfile
tasksnest.jorendegraaf.eu {
handle /mcp {
reverse_proxy 100.91.62.59:8002
}
handle /.well-known/oauth-protected-resource/mcp {
reverse_proxy 100.91.62.59:8002
}
handle {
reverse_proxy 100.91.62.59:1234
}
}
```
Integrate these `handle` routes into the existing site block rather than replacing unrelated proxy settings. Preserve HTTPS and the `Authorization` header. The provided `deploy/systemd/tasknest-mcp.service` starts MCP on the app host's Tailnet address; adjust its address and virtualenv path if they differ, install it on the **app host**, and start it before reloading Caddy. If Caddy and Django are on the same host, replace the Caddy upstreams with `127.0.0.1` and bind MCP to `127.0.0.1`.
Before reconnecting ChatGPT, verify the public endpoints: `/.well-known/oauth-protected-resource/mcp` must advertise `https://tasksnest.jorendegraaf.eu/` as its authorization server; `/.well-known/oauth-authorization-server` must advertise public HTTPS authorization and token endpoints; and an unauthenticated POST to `/mcp` should return an MCP authentication response, not a Django 404. Restart the Django and MCP processes after changing their environment variables.
## Connect a client
Open **Settings → API tokens → Connect an AI assistant**. For ChatGPT, use the public MCP URL and OAuth sign-in. ChatGPT must be able to reach the HTTPS URL and its OAuth metadata. For Open WebUI or another bearer-token client, create a personal token with only the scopes needed, choose Streamable HTTP, and enter the same MCP URL and token as a bearer credential. The helper's password field is local to the browser and clears when the page is left; it does not submit the token to the helper. Revoke a token from Settings when it is no longer needed.
The server exposes 12 tools for food diary and inventory reads and changes. `food_attach_image` and `food_log_with_image` accept a ChatGPT file object via `image_file` or base64 data via `image_base64`. Images must be JPEG, PNG, or WebP and at most 5 MiB. A client-supplied file URL must use HTTPS and an allowed host. The API performs image validation and ownership checks. Creation tools accept an `idempotency_key`; reuse the same key and arguments when retrying a request. `food_log_with_image` reports whether the entry was created even if its later attachment upload fails.
`food_get_today` accepts an optional `date` in `YYYY-MM-DD` format. Omit it for the user's local today; pass a calendar date to read another day, such as yesterday. The HTTP API supports the same parameter on `GET /api/v1/food/today/?date=YYYY-MM-DD`.
The OAuth consent page displays the requested scopes. OAuth access tokens are user-specific API tokens, and token revocation also revokes the matching OAuth grant. For production, use HTTPS and set the issuer and MCP URLs to the actual public hosts before connecting a client. Dynamic client registration is disabled; clients use OAuth Client ID Metadata Documents (CIMD). ChatGPT's document offers both `none` and `private_key_jwt`; this server selects `none` with PKCE because the installed Django OAuth Toolkit supports public CIMD clients only. Clients that do not explicitly offer `none` are rejected.
## Verify
Run `python manage.py test food.test_oauth_mcp mcp_server.tests` from `main/`. These tests exercise OAuth issuance and revocation, the live HTTP MCP protocol, scopes, user isolation, image upload, idempotency, and tool results. A real external ChatGPT connection still requires a public HTTPS deployment and a client sign-in test.
+4
View File
@@ -1,5 +1,9 @@
# Tasknest development notes
## AI assistant connection
The Food and Kitchen API has a Streamable HTTP MCP adapter with per-user token and OAuth authentication. See [MCP.md](MCP.md) for local startup, deployment routing, client setup, and verification.
## Weather scheduling
The server gets a finite 16-day daily forecast from Open-Meteo and caches each user's normalized forecast for twelve hours. No browser code, template, or model calls Open-Meteo directly.
+18
View File
@@ -0,0 +1,18 @@
[Unit]
Description=Tasknest MCP Streamable HTTP server
Wants=network-online.target
After=network-online.target tailscaled.service
[Service]
Type=simple
User=jorenmartijn
WorkingDirectory=/home/jorenmartijn/django/main
Environment=TASKNEST_API_BASE_URL=http://127.0.0.1:1234/api/v1
Environment=TASKNEST_MCP_PUBLIC_URL=https://tasksnest.jorendegraaf.eu/mcp
Environment=TASKNEST_OAUTH_ISSUER_URL=https://tasksnest.jorendegraaf.eu/
ExecStart=/home/jorenmartijn/django/tasksnest-host/bin/python -m uvicorn mcp_server.server:app --host 100.91.62.59 --port 8002
Restart=on-failure
RestartSec=3
[Install]
WantedBy=multi-user.target
+7 -1
View File
@@ -222,7 +222,13 @@ def _idempotent(request, payload, action, digest_override=None):
@api_view('food:read', ('GET',))
def today(request):
day = localdate_for_user(request.api_user)
requested_date = request.GET.get('date')
if requested_date is None:
day = localdate_for_user(request.api_user)
else:
day = parse_date(requested_date)
if day is None or day.isoformat() != requested_date:
return error('invalid_date', 'Use a date in YYYY-MM-DD format.')
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}
+6 -1
View File
@@ -49,7 +49,7 @@ def schema(request):
'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/today/': {'get': operation('Food log for an optional local calendar date, defaulting to today', '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}/': {
@@ -77,6 +77,11 @@ def schema(request):
'schema': {'type': 'string', 'format': 'uuid'}}]
if 'post' in methods:
methods['post']['responses']['201'] = methods['post']['responses'].pop('200')
document['paths']['/food/today/']['get']['parameters'] = [{
'name': 'date', 'in': 'query', 'required': False,
'description': 'Local calendar date; defaults to today in the user time zone.',
'schema': {'type': 'string', 'format': 'date'},
}]
document['paths']['/food/attachments/{id}/file/']['get']['responses']['200'] = {
'description': 'Owned image bytes',
'content': {mime: {'schema': {'type': 'string', 'format': 'binary'}}
+21
View File
@@ -0,0 +1,21 @@
"""Adapt CIMD method negotiation for DOT's public-client-only implementation."""
from oauth2_provider.cimd import SafeMetadataFetcher
from oauth2_provider.settings import oauth2_settings
class CompatibleCIMDFetcher(SafeMetadataFetcher):
def fetch(self, client_id):
metadata, max_age = super().fetch(client_id)
methods = metadata.get('token_endpoint_auth_methods_supported')
if (
metadata.get('token_endpoint_auth_method') != 'none'
and isinstance(methods, list)
and 'none' in methods
and 'none' in oauth2_settings.OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED
):
# DOT 3.4 accepts only public CIMD clients. The plural metadata
# field explicitly allows this method even when the legacy singular
# field prefers private_key_jwt, which this server does not offer.
metadata = {**metadata, 'token_endpoint_auth_method': 'none'}
return metadata, max_age
+2 -1
View File
@@ -24,7 +24,8 @@ def selected_date(request):
def diary_context(user, day):
goals, _ = UserSettings.objects.get_or_create(user=user)
entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product').defer('product__raw_data'))
entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product')
.prefetch_related('attachments').defer('product__raw_data'))
totals = {name: sum((getattr(entry, name) or ZERO for entry in entries), ZERO) for name in
('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g')}
meals = []
+3
View File
@@ -15,6 +15,9 @@ body[data-theme="dark"]{--food-surface:#202923;--food-border:#3b473f;--food-ink:
.food-progress span{background:var(--food-green)}
.food-entry-main span,.food-entry-main small,.food-card>p:not(.food-remaining),.food-attribution{color:var(--food-muted);opacity:1}
.food-entry-main strong,.food-card h2,.food-card h3,.food-remaining{color:var(--food-ink)}
.food-entry-images{display:flex;gap:.35rem;flex:none;max-width:min(40vw,220px);overflow-x:auto;padding:.15rem}
.food-entry-images a{display:block;flex:none;border-radius:.6rem}
.food-entry-images a:focus-visible{outline:2px solid currentColor;outline-offset:2px}
.inventory-page .inventory-group{margin:1.5rem 0 .5rem}.inventory-filters{display:flex;flex-wrap:wrap;gap:.75rem;align-items:end}.inventory-filters label{display:grid;gap:.25rem;min-width:130px;flex:1}.inventory-filters .inventory-check{display:flex;align-items:center;min-width:auto}.inventory-row{display:flex;align-items:center;gap:1rem}.inventory-row>img,.inventory-product>img{width:68px;height:68px;object-fit:contain;background:#fff;border-radius:.6rem}.inventory-row-main{flex:1;min-width:0}.inventory-row-main p{margin:.2rem 0}.inventory-row-actions{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap}.inventory-row-actions form{display:flex;gap:.4rem}.inventory-row-actions button,.inventory-row-actions a{min-height:44px;padding:.5rem .75rem}.inventory-tag{display:inline-block;padding:.2rem .45rem;margin:.2rem .2rem 0 0;border-radius:.5rem;background:#eef1ed;color:#263828}.inventory-soon{background:#fff0c2;color:#533c00}.inventory-expired{background:#f9d9d9;color:#6b1717}.inventory-product{display:flex;gap:1rem;align-items:center}.inventory-existing{display:flex;justify-content:space-between;align-items:center;gap:.7rem;margin:.7rem 0}.inventory-form{display:grid;gap:.8rem}.inventory-form .form-field{display:grid;gap:.25rem}.inventory-form input:not([type=checkbox]),.inventory-form textarea{width:100%}@media(max-width:650px){.inventory-row{align-items:flex-start;flex-wrap:wrap}.inventory-row-actions{width:100%}.inventory-existing{align-items:flex-start;flex-direction:column}}
.inventory-quantity{display:flex;align-items:center;gap:.5rem}.inventory-quantity input{text-align:center;max-width:6rem}.inventory-quantity button{min-width:44px;min-height:44px;border:1px solid currentColor;border-radius:.5rem;background:transparent;color:inherit;font-size:1.3rem}
.food-tabs a[aria-current=page]{background:var(--food-green);border-color:var(--food-green);color:#fff}
@@ -5,7 +5,18 @@
{% for meal in meals %}
<section class="food-meal" id="meal-{{ meal.key }}" aria-labelledby="meal-title-{{ meal.key }}">
<div class="food-meal-heading"><div><h2 id="meal-title-{{ meal.key }}">{{ meal.label }}</h2><p>{{ meal.calories|floatformat:0 }} kcal</p></div><a class="food-add-meal" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal.key }}" aria-label="Add food to {{ meal.label }}">+</a></div>
{% if meal.entries %}<ul class="food-entry-list">{% for entry in meal.entries %}<li class="food-entry"><div class="food-entry-main">{% if entry.product and entry.product.image_url %}<img src="{{ entry.product.image_url }}" alt="" loading="lazy">{% endif %}<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }})</small></div></div><a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a></li>{% endfor %}</ul>{% else %}<p class="food-empty">Nothing logged yet.</p>{% endif %}
{% if meal.entries %}<ul class="food-entry-list">{% for entry in meal.entries %}
<li class="food-entry">
<div class="food-entry-main">
{% with images=entry.attachments.all %}
{% if images %}<div class="food-entry-images">{% for attachment in images %}<a href="{% url 'food:attachment-file' attachment.api_id %}" target="_blank" rel="noopener" aria-label="View attached image{% if attachment.caption %}: {{ attachment.caption }}{% else %} for {{ entry.product_name_snapshot }}{% endif %}"><img src="{% url 'food:attachment-file' attachment.api_id %}" alt="" loading="lazy"></a>{% endfor %}</div>
{% elif entry.product and entry.product.image_url %}<img src="{{ entry.product.image_url }}" alt="" loading="lazy">{% endif %}
{% endwith %}
<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }})</small></div>
</div>
<a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>
</li>
{% endfor %}</ul>{% else %}<p class="food-empty">Nothing logged yet.</p>{% endif %}
</section>
{% endfor %}
<a class="button" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}">Add food</a>
+1 -1
View File
@@ -35,7 +35,7 @@
<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>
<input id="mcp-server-url" type="url" readonly data-mcp-url>
<button class="button button--secondary" type="button" data-mcp-copy-url>Copy URL</button>
</div>
<div class="form-field">
+12
View File
@@ -105,6 +105,18 @@ class FoodApiTests(TestCase):
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')
def test_food_diary_accepts_specific_date(self):
entry = FoodLogEntry.objects.create(user=self.a, date=datetime(2026, 1, 2).date(), meal='breakfast',
product_name_snapshot='Oats', amount=Decimal('100'), unit='g', calories_kcal=Decimal('120'))
response = self.call('get', '/api/v1/food/today/?date=2026-01-02')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()['date'], '2026-01-02')
self.assertEqual(response.json()['meals']['breakfast'][0]['id'], str(entry.api_id))
self.assertEqual(response.json()['totals']['calories_kcal'], '120')
self.assertEqual(self.call('get', '/api/v1/food/today/?date=2026-01-03').json()['meals']['breakfast'], [])
for invalid in ('', 'yesterday', '2026-02-30', '2026-1-2'):
self.assertEqual(self.call('get', f'/api/v1/food/today/?date={invalid}').status_code, 400)
@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',
+35
View File
@@ -1,15 +1,50 @@
import base64
import hashlib
from unittest.mock import patch
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 .cimd import CompatibleCIMDFetcher
from .models import PersonalAccessToken
class McpOAuthTests(TestCase):
def test_cimd_requires_explicit_public_client_support(self):
metadata = {'token_endpoint_auth_method': 'private_key_jwt',
'token_endpoint_auth_methods_supported': ['private_key_jwt']}
with patch('oauth2_provider.cimd.SafeMetadataFetcher.fetch', return_value=(metadata, 300)):
selected, _ = CompatibleCIMDFetcher().fetch('https://example.com/client.json')
self.assertEqual(selected['token_endpoint_auth_method'], 'private_key_jwt')
def test_chatgpt_cimd_can_select_public_client_method(self):
client_id = 'https://chatgpt.com/oauth/client.json'
redirect_uri = 'https://chatgpt.com/connector_platform_oauth_redirect'
metadata = {
'client_id': client_id,
'redirect_uris': [redirect_uri],
'grant_types': ['authorization_code', 'refresh_token'],
'token_endpoint_auth_method': 'private_key_jwt',
'token_endpoint_auth_methods_supported': ['none', 'private_key_jwt'],
'client_name': 'ChatGPT',
}
user = get_user_model().objects.create_user('chatgpt-cimd-test', password='test')
self.client.force_login(user)
verifier = 'v' * 64
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
with patch('oauth2_provider.cimd.SafeMetadataFetcher.fetch', return_value=(metadata, 300)):
response = self.client.get('/o/authorize/', {
'response_type': 'code', 'client_id': client_id, 'redirect_uri': redirect_uri,
'scope': 'food:read', 'state': 'cimd-test', 'code_challenge': challenge,
'code_challenge_method': 'S256', 'resource': 'https://tasksnest.jorendegraaf.eu',
}, HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
self.assertEqual(response.status_code, 200, response.content[:300])
self.assertContains(response, 'Authorize')
application = Application.objects.get(client_id=client_id)
self.assertEqual(application.client_type, Application.CLIENT_PUBLIC)
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,
+25 -1
View File
@@ -1,8 +1,10 @@
from datetime import date
from decimal import Decimal
from tempfile import TemporaryDirectory
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import IntegrityError, transaction
from django.test import TestCase
from django.urls import reverse
@@ -10,7 +12,7 @@ from planner.models import UserSettings
from .services.diary import diary_context
from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
class FoodFoundationTests(TestCase):
@@ -61,6 +63,28 @@ class FoodFoundationTests(TestCase):
self.client.force_login(self.user)
self.assertEqual(self.client.get(reverse('food:diary')).status_code, 200)
def test_diary_shows_private_attachment_to_owner(self):
entry = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.DINNER,
product_name_snapshot='Dinner', amount=Decimal('250'), unit=Unit.GRAM)
image_bytes = b'example-image-bytes'
with TemporaryDirectory() as media_root, self.settings(MEDIA_ROOT=media_root):
attachment = FoodLogAttachment.objects.create(log_entry=entry,
image=SimpleUploadedFile('dinner.png', image_bytes, content_type='image/png'),
original_filename='dinner.png', content_type='image/png', file_size=len(image_bytes))
image_url = reverse('food:attachment-file', args=[attachment.api_id])
self.client.force_login(self.user)
diary = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
self.assertContains(diary, image_url, count=2)
image = self.client.get(image_url)
self.assertEqual(image.status_code, 200)
self.assertEqual(image['Content-Type'], 'image/png')
self.assertEqual(b''.join(image.streaming_content), image_bytes)
image.close()
self.client.force_login(self.other)
self.assertEqual(self.client.get(image_url).status_code, 404)
self.client.logout()
self.assertEqual(self.client.get(image_url).status_code, 302)
def test_food_goals_reject_negative_values(self):
from planner.forms import FoodGoalForm
-2
View File
@@ -1,7 +1,6 @@
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
@@ -47,7 +46,6 @@ def tokens(request):
'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,
})
+1
View File
@@ -24,6 +24,7 @@ urlpatterns = [
path('manual/', views.manual_food, name='manual'),
path('log/<int:pk>/', views.edit_entry, name='edit'),
path('log/<int:pk>/delete/', views.delete_entry, name='delete'),
path('attachments/<uuid:identifier>/file/', views.attachment_file, name='attachment-file'),
path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'),
path('export/<str:period>/', views.export_csv, name='export'),
]
+15 -3
View File
@@ -7,17 +7,18 @@ import re
from urllib.parse import urlencode
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse
from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse
from django.contrib import messages
from django.db.models import Q
from django.db.models import Max
from django.db import transaction
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.decorators.http import require_http_methods, require_POST
from django.views.decorators.http import require_GET, require_http_methods, require_POST
from django.views.decorators.cache import never_cache
from .forms import FoodLogForm, ManualFoodForm
from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType
from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType
from .services.diary import diary_context, selected_date
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
from .services.products import local_products
@@ -144,6 +145,17 @@ def diary(request):
return render(request, 'food/diary.html', diary_context(request.user, day))
@login_required
@never_cache
@require_GET
def attachment_file(request, identifier):
attachment = get_object_or_404(FoodLogAttachment, api_id=identifier, log_entry__user=request.user)
response = FileResponse(attachment.image.open('rb'), content_type=attachment.content_type)
response['Content-Disposition'] = 'inline'
response['X-Content-Type-Options'] = 'nosniff'
return response
@login_required
@require_http_methods(['GET', 'POST'])
def add_food(request):
+1
View File
@@ -83,6 +83,7 @@ function initialiseMcpHelper() {
if (!helper) return;
const token = helper.querySelector('[data-mcp-token]');
const url = helper.querySelector('[data-mcp-url]');
url.value = `${window.location.origin}/mcp`;
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'); };
+55 -13
View File
@@ -1,6 +1,7 @@
"""Streamable HTTP MCP adapter. All application operations cross the HTTP API."""
import base64
import binascii
import logging
import os
import uuid
from datetime import datetime
@@ -11,17 +12,22 @@ from urllib.parse import urlsplit
import httpx2
from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.auth.provider import AccessToken, TokenVerifier
from mcp.server.auth.routes import create_protected_resource_routes
from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.transport_security import TransportSecuritySettings
from pydantic import AnyHttpUrl, BaseModel, ConfigDict, Field
API_BASE = os.environ.get('TASKNEST_API_BASE_URL', 'http://127.0.0.1:1234/api/v1').rstrip('/')
MCP_PUBLIC_URL = os.environ.get('TASKNEST_MCP_PUBLIC_URL', 'http://127.0.0.1:8002/mcp')
OAUTH_ISSUER_URL = os.environ.get('TASKNEST_OAUTH_ISSUER_URL', 'http://127.0.0.1:1234')
MCP_PUBLIC_URL = os.environ.get('TASKNEST_MCP_PUBLIC_URL', 'https://tasksnest.jorendegraaf.eu/mcp')
OAUTH_ISSUER_URL = os.environ.get('TASKNEST_OAUTH_ISSUER_URL', 'https://tasksnest.jorendegraaf.eu/')
MAX_IMAGE_BYTES = 5 * 1024 * 1024
SUPPORTED_SCOPES = ['food:read', 'food:write', 'inventory:read', 'inventory:write']
FILE_HOSTS = tuple(host.strip().lower().lstrip('.') for host in
os.environ.get('TASKNEST_MCP_FILE_HOSTS', 'openai.com,oaiusercontent.com,chatgpt.com').split(',') if host.strip())
CHATGPT_BLOB_HOST = 'oaisdmntprukwest.blob.core.windows.net'
logger = logging.getLogger(__name__)
class ClientImageFile(BaseModel):
@@ -149,15 +155,29 @@ def _key(value):
return value or str(uuid.uuid4())
def _allowed_file_host(host):
return host == CHATGPT_BLOB_HOST or any(
host == allowed or host.endswith('.' + allowed) for allowed in FILE_HOSTS
)
async def _resolve_image(image_base64, image_file, mime_type, filename):
if bool(image_base64) == bool(image_file):
raise ToolError('Provide exactly one image: image_base64 or image_file.')
if image_file:
parsed = urlsplit(image_file.download_url)
try:
parsed = urlsplit(image_file.download_url)
port = parsed.port
except ValueError:
raise ToolError('Image download URL is invalid.') from None
host = (parsed.hostname or '').lower()
if parsed.scheme != 'https' or not host 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
):
if parsed.scheme != 'https' or not host:
raise ToolError('Image download URL must be HTTPS with a hostname.')
if parsed.username or parsed.password or port not in (None, 443):
raise ToolError('Image download URL contains unsupported credentials or port.')
if not _allowed_file_host(host):
# Never log or return the path/query: they may contain a signed URL.
logger.warning('Rejected image download host %r', host)
raise ToolError('Image download URL is not an allowed HTTPS file host.')
try:
async with httpx2.AsyncClient(timeout=20, follow_redirects=False) as client:
@@ -206,9 +226,9 @@ def create_server() -> MCPServer:
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/')
@server.tool(structured_output=True, description='Read the authenticated user’s food diary for a specific local calendar day, grouped by meal with totals, goals, and remaining calories/macros. Optional date must be YYYY-MM-DD; omit it for today in the user’s time zone. For “yesterday”, pass yesterday’s calendar date. Does not change data.')
async def food_get_today(date: str | None = None) -> dict[str, Any]:
data = await api_request('GET', 'food/today/', params={'date': date} if date is not None else None)
entries = {meal: [_entry(item) for item in items] for meal, items in data['meals'].items()}
goals = data.get('goals', {})
mapping = {'calories_kcal': 'daily_calorie_goal', 'carbohydrates_g': 'carbohydrate_goal_g',
@@ -242,7 +262,7 @@ def create_server() -> MCPServer:
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,
async def food_attach_image(entry_id: str, image_base64: str | None = None, image_file: ClientImageFile = None,
mime_type: str | None = None, filename: str = 'image', caption: str = '',
idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
@@ -251,7 +271,7 @@ def create_server() -> MCPServer:
@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,
image_file: ClientImageFile = None, mime_type: str | None = None,
filename: str = 'image', caption: str = '',
idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
@@ -300,5 +320,27 @@ def create_server() -> MCPServer:
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)
app = create_server().streamable_http_app(
streamable_http_path='/mcp', stateless_http=True, json_response=True,
max_request_body_size=8 * 1024 * 1024,
transport_security=TransportSecuritySettings(
allowed_hosts=[urlsplit(MCP_PUBLIC_URL).netloc, '127.0.0.1:*', 'localhost:*'],
allowed_origins=[f'{urlsplit(MCP_PUBLIC_URL).scheme}://{urlsplit(MCP_PUBLIC_URL).netloc}',
'https://chatgpt.com', 'http://127.0.0.1:*', 'http://localhost:*'],
),
)
# The SDK uses required_scopes for both metadata and transport authorization.
# TaskNest authorizes each API operation separately, so leave transport scopes
# empty and advertise the supported scopes only in the resource metadata route.
metadata_route = create_protected_resource_routes(
resource_url=AnyHttpUrl(MCP_PUBLIC_URL),
authorization_servers=[AnyHttpUrl(OAUTH_ISSUER_URL)],
scopes_supported=SUPPORTED_SCOPES,
)[0]
for index, route in enumerate(app.router.routes):
if getattr(route, 'path', None) == metadata_route.path:
app.router.routes[index] = metadata_route
break
else:
raise RuntimeError('MCP protected-resource metadata route is missing.')
+43 -1
View File
@@ -16,15 +16,33 @@ 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.test import LiveServerTestCase, SimpleTestCase
from django.utils import timezone
from mcp import Client
from mcp.client.streamable_http import streamable_http_client
from mcp.server.mcpserver.exceptions import ToolError
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
from .server import ClientImageFile, _allowed_file_host, _resolve_image
class ImageHostLoggingTests(SimpleTestCase):
def test_chatgpt_blob_account_is_allowed_without_allowing_other_blob_accounts(self):
self.assertTrue(_allowed_file_host('oaisdmntprukwest.blob.core.windows.net'))
self.assertFalse(_allowed_file_host('other.blob.core.windows.net'))
self.assertFalse(_allowed_file_host('not-oaisdmntprukwest.blob.core.windows.net'))
def test_rejected_file_logs_only_hostname(self):
image = ClientImageFile(download_url='https://files.example.invalid/private?signature=secret', file_id='test')
with self.assertLogs('mcp_server.server', level='WARNING') as captured:
with self.assertRaisesRegex(ToolError, 'not an allowed HTTPS file host'):
asyncio.run(_resolve_image(None, image, None, 'image'))
self.assertIn('files.example.invalid', captured.output[0])
self.assertNotIn('/private', captured.output[0])
self.assertNotIn('signature=secret', captured.output[0])
class McpHttpTests(LiveServerTestCase):
@@ -58,6 +76,8 @@ class McpHttpTests(LiveServerTestCase):
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:
self.assertEqual(response.json()['scopes_supported'],
['food:read', 'food:write', 'inventory:read', 'inventory:write'])
break
except httpx2.RequestError:
pass
@@ -80,6 +100,11 @@ class McpHttpTests(LiveServerTestCase):
def test_authentication_and_scope_boundaries(self):
async def check():
async with httpx2.AsyncClient(timeout=10) as http:
response = await http.post(self.mcp_url, headers={'Authorization': 'Bearer ' + self.secret,
'Host': 'untrusted.example', 'Accept': 'application/json, text/event-stream'},
json={'jsonrpc': '2.0', 'id': 1, 'method': 'tools/list'})
self.assertEqual(response.status_code, 421)
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,
@@ -122,6 +147,9 @@ class McpHttpTests(LiveServerTestCase):
asyncio.run(self._client(secret, check))
def test_food_inventory_tools_and_user_isolation(self):
previous_day = localdate_for_user(self.a) - timedelta(days=1)
FoodLogEntry.objects.create(user=self.a, date=previous_day, meal='breakfast',
product_name_snapshot='Yesterday oats', amount=Decimal('100'), unit='g', calories_kcal=Decimal('120'))
image = Image.new('RGB', (2, 2), 'red')
output = io.BytesIO()
image.save(output, format='PNG')
@@ -132,6 +160,11 @@ class McpHttpTests(LiveServerTestCase):
self.assertEqual(len(names), 12)
today = (await client.call_tool('food_get_today')).structured_content
self.assertEqual(today['meals']['lunch'], [])
yesterday = (await client.call_tool('food_get_today', {'date': previous_day.isoformat()})).structured_content
self.assertEqual(yesterday['date'], previous_day.isoformat())
self.assertEqual(yesterday['meals']['breakfast'][0]['name'], 'Yesterday oats')
self.assertEqual(yesterday['totals']['calories_kcal'], '120')
self.assertTrue((await client.call_tool('food_get_today', {'date': 'yesterday'})).is_error)
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)
@@ -148,6 +181,15 @@ class McpHttpTests(LiveServerTestCase):
'image_base64': encoded, 'mime_type': 'image/png', 'filename': 'meal.png',
'idempotency_key': 'mcp-image-1'})).structured_content
self.assertTrue(image_result['success'])
unsafe_file = await client.call_tool('food_attach_image', {'entry_id': entry_id,
'image_file': {'download_url': 'http://127.0.0.1/private', 'file_id': 'test'}})
self.assertTrue(unsafe_file.is_error)
unknown_host = await client.call_tool('food_attach_image', {'entry_id': entry_id,
'image_file': {'download_url': 'https://files.example.invalid/private?signature=secret',
'file_id': 'test'}})
self.assertTrue(unknown_host.is_error)
self.assertNotIn('files.example.invalid', str(unknown_host.content))
self.assertNotIn('signature=secret', str(unknown_host.content))
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,
+3 -2
View File
@@ -62,7 +62,7 @@ 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/'),
'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',
@@ -75,6 +75,7 @@ OAUTH2_PROVIDER = {
'ROTATE_REFRESH_TOKEN': True,
'REFRESH_TOKEN_REUSE_PROTECTION': True,
'CIMD_ENABLED': True,
'CIMD_METADATA_FETCHER': 'food.cimd.CompatibleCIMDFetcher',
'DCR_ENABLED': False,
'OAUTH2_GRANT_TYPES_SUPPORTED': ['authorization_code', 'refresh_token'],
'OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED': ['none', 'client_secret_basic', 'client_secret_post'],
@@ -87,7 +88,7 @@ OAUTH2_PROVIDER = {
'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')
'https://tasksnest.jorendegraaf.eu/mcp')
TEMPLATES = [
{