diff --git a/main/MCP.md b/main/MCP.md
index 9a4aea4..006ad76 100644
--- a/main/MCP.md
+++ b/main/MCP.md
@@ -1,6 +1,6 @@
# TaskNest MCP server
-The Streamable HTTP MCP endpoint exposes the Food, Kitchen, and Recipes 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.
+The Streamable HTTP MCP endpoint exposes the Food, Kitchen, Recipes, and private Stress Journal 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
@@ -47,12 +47,20 @@ Before reconnecting ChatGPT, verify the public endpoints: `/.well-known/oauth-pr
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.
+An existing ChatGPT connection may continue to request its original food and inventory scopes even after the server advertises the newer journal scopes. During a fresh OAuth consent, select **Also allow reading and changing my private dream and stress journals** if you want journal tools. The box is off by default; leaving it off preserves the requested scopes. Reconnecting without new consent or merely refreshing an old token does not add journal access. If ChatGPT skips the consent screen, revoke its old TaskNest authorization in API tokens and reconnect once. The consent screen lists the requested permissions and the optional journal upgrade separately.
+
The server exposes tools for food diary, product catalogue, inventory, and hydration 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`.
`hydration_get_daily` returns combined fluid intake, manual and Food Diary contributions, the daily goal, and remaining amount. `hydration_log`, `hydration_update`, and `hydration_delete` manage standalone manual entries. Use an `idempotency_key` with `hydration_log` when retrying. `hydration_settings_get` and `hydration_settings_update` configure automatic Food Diary counting and optional beverage rules. The Food Diary tools count eligible millilitre drinks during the food write; no additional hydration tool call is needed.
+## Private stress journal
+
+The `stress_search`, `stress_get`, `stress_create`, `stress_update`, and `stress_delete` tools use `journal:read` and `journal:write` scopes. Existing food and inventory tokens cannot read journal content. A check-in has a 0–10 score, optional note, stressor tags and physical symptoms, a timestamp, and a timing value: `anytime`, `before_sleep`, or `after_waking`. Naive timestamps use the user's saved time zone. Search supports text, local date, and timing filters. Create returns an ID; use that ID with `stress_update` for later conversational corrections rather than creating another entry. Reuse the same idempotency key and payload on creation retries. The web journal at `/stress/` provides history, a 30-day calendar, descriptive stress summaries, and nearby dream/stress entries. These comparisons describe timing only and do not establish causation.
+
+The `dream_search`, `dream_get`, `dream_create`, `dream_update`, and `dream_delete` tools use the same private journal scopes. Dreams are associated with the local date on waking, matching Health > Sleep, and can be backdated. Keep the narrative separate from the user's own interpretation; do not infer or invent either. `dream_search` supports keywords, tag, date, date range, limit, and offset. Creation returns an ID and idempotency key; use the ID for follow-up corrections. `dream_update` can replace supplied fields or append narrative/after-waking details. Appends require an idempotency key to avoid duplicate text on retries. The web journal is at `/dreams/`; the Health sleep panel links to a matching dream on the selected wake-up date.
+
## Product discovery and grocery photographs
Image interpretation belongs to the AI client. For a grocery photograph, identify the visible products and any readable barcodes, brands, package sizes, quantities, and storage locations, then send structured data to TaskNest. Unreadable details should remain unknown.
diff --git a/main/dreams/__init__.py b/main/dreams/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/main/dreams/api.py b/main/dreams/api.py
new file mode 100644
index 0000000..9c2a2c2
--- /dev/null
+++ b/main/dreams/api.py
@@ -0,0 +1,149 @@
+"""Private dream journal API for the authenticated user's MCP tools."""
+from django.core.exceptions import ValidationError
+from django.db.models import Q
+from django.http import JsonResponse
+from django.utils import timezone
+from django.utils.dateparse import parse_date, parse_datetime
+
+from food.api import api_view, error, _json, _idempotent
+from planner.timezones import timezone_for_user
+from .forms import normalize_terms
+from .models import DreamEntry
+
+FIELDS = {'wake_up_date', 'dreamed_at', 'title', 'narrative', 'interpretation',
+ 'tags', 'emotions', 'vividness', 'is_nightmare', 'after_waking_notes'}
+APPEND_FIELDS = {'append_narrative': 'narrative', 'append_after_waking_notes': 'after_waking_notes'}
+
+
+def serialize(entry):
+ return {'id': str(entry.pk), 'wake_up_date': entry.wake_up_date.isoformat(),
+ 'dreamed_at': entry.dreamed_at.isoformat() if entry.dreamed_at else None,
+ 'title': entry.title, 'narrative': entry.narrative, 'interpretation': entry.interpretation,
+ 'tags': entry.tags, 'emotions': entry.emotions, 'vividness': entry.vividness,
+ 'is_nightmare': entry.is_nightmare, 'after_waking_notes': entry.after_waking_notes,
+ 'created_at': entry.created_at.isoformat(), 'updated_at': entry.updated_at.isoformat()}
+
+
+def validate(data, user, *, updating=False):
+ if not isinstance(data, dict):
+ raise ValueError('Expected a JSON object.')
+ unknown = set(data) - FIELDS - (set(APPEND_FIELDS) if updating else set())
+ if unknown:
+ raise ValueError('Unknown fields: ' + ', '.join(sorted(unknown)))
+ if 'narrative' in data and 'append_narrative' in data:
+ raise ValueError('Choose narrative or append_narrative, not both.')
+ if 'after_waking_notes' in data and 'append_after_waking_notes' in data:
+ raise ValueError('Choose after_waking_notes or append_after_waking_notes, not both.')
+ result = {}
+ if 'wake_up_date' in data:
+ value = data['wake_up_date']
+ day = parse_date(value) if isinstance(value, str) else None
+ if day is None or day.isoformat() != value:
+ raise ValueError('Use YYYY-MM-DD for wake_up_date.')
+ result['wake_up_date'] = day
+ if 'dreamed_at' in data:
+ value = data['dreamed_at']
+ if value is None:
+ result['dreamed_at'] = None
+ else:
+ moment = parse_datetime(value) if isinstance(value, str) else None
+ if moment is None:
+ raise ValueError('Use an ISO date and time for dreamed_at.')
+ result['dreamed_at'] = timezone.make_aware(moment, timezone_for_user(user)) if timezone.is_naive(moment) else moment
+ for name, limit in [('title', 160), ('narrative', 20000), ('interpretation', 4000),
+ ('after_waking_notes', 4000)]:
+ if name in data:
+ value = data[name]
+ if not isinstance(value, str) or len(value) > limit or (name in {'title', 'narrative'} and not value.strip()):
+ raise ValueError(f'{name} must be non-empty text within {limit} characters.' if name in {'title', 'narrative'} else f'{name} must be text within {limit} characters.')
+ result[name] = value
+ for name in ('tags', 'emotions'):
+ if name in data:
+ result[name] = normalize_terms(data[name])
+ if 'vividness' in data:
+ score = data['vividness']
+ if score is not None and (isinstance(score, bool) or not isinstance(score, int) or not 0 <= score <= 10):
+ raise ValueError('Vividness must be 0–10 or null.')
+ result['vividness'] = score
+ if 'is_nightmare' in data:
+ if not isinstance(data['is_nightmare'], bool):
+ raise ValueError('is_nightmare must be true or false.')
+ result['is_nightmare'] = data['is_nightmare']
+ for append_name in APPEND_FIELDS:
+ if append_name in data:
+ value = data[append_name]
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError(f'{append_name} must be non-empty text.')
+ result[append_name] = value.strip()
+ return result
+
+
+@api_view({'GET': 'journal:read', 'POST': 'journal:write'}, ('GET', 'POST'))
+def collection(request):
+ if request.method == 'GET':
+ entries = DreamEntry.objects.filter(user=request.api_user)
+ query = request.GET.get('query', '').strip()[:100]
+ if query:
+ entries = entries.filter(Q(title__icontains=query) | Q(narrative__icontains=query) |
+ Q(tags__icontains=query) | Q(emotions__icontains=query))
+ tag = request.GET.get('tag', '').strip()[:40]
+ if tag:
+ entries = entries.filter(tags__icontains=tag)
+ for key, lookup in (('date', 'wake_up_date'), ('date_from', 'wake_up_date__gte'),
+ ('date_to', 'wake_up_date__lte')):
+ if text := request.GET.get(key):
+ day = parse_date(text)
+ if day is None or day.isoformat() != text:
+ return error('invalid_date', f'Use YYYY-MM-DD for {key}.')
+ entries = entries.filter(**{lookup: day})
+ try:
+ limit = min(max(int(request.GET.get('limit', 30)), 1), 100)
+ offset = max(int(request.GET.get('offset', 0)), 0)
+ except ValueError:
+ return error('invalid_pagination', 'Limit and offset must be integers.')
+ return JsonResponse({'items': [serialize(entry) for entry in entries[offset:offset + limit]],
+ 'total': entries.count()})
+ data = _json(request)
+ cleaned = validate(data, request.api_user)
+ if not {'wake_up_date', 'title', 'narrative'} <= cleaned.keys():
+ return error('missing_fields', 'wake_up_date, title, and narrative are required.')
+
+ def action():
+ entry = DreamEntry(user=request.api_user, **cleaned)
+ entry.full_clean()
+ entry.save()
+ return JsonResponse(serialize(entry), status=201)
+ return _idempotent(request, data, action)
+
+
+@api_view({'GET': 'journal:read', 'PATCH': 'journal:write', 'DELETE': 'journal:write'},
+ ('GET', 'PATCH', 'DELETE'))
+def item(request, identifier):
+ entry = DreamEntry.objects.filter(pk=identifier, user=request.api_user).first()
+ if entry is None:
+ return error('not_found', 'Dream entry not found.', 404)
+ if request.method == 'GET':
+ return JsonResponse(serialize(entry))
+ if request.method == 'DELETE':
+ entry.delete()
+ return JsonResponse({'deleted': True})
+ data = _json(request)
+ cleaned = validate(data, request.api_user, updating=True)
+ if any(name in cleaned for name in APPEND_FIELDS) and not request.headers.get('Idempotency-Key'):
+ return error('idempotency_required', 'Use an Idempotency-Key when appending dream details.')
+
+ def action():
+ for name, value in cleaned.items():
+ if name in APPEND_FIELDS:
+ field = APPEND_FIELDS[name]
+ current = getattr(entry, field)
+ combined = f'{current}\n\n{value}' if current else value
+ if len(combined) > (20000 if field == 'narrative' else 4000):
+ return error('too_long', f'{field} is too long.')
+ setattr(entry, field, combined)
+ else:
+ setattr(entry, name, value)
+ entry.full_clean()
+ entry.save()
+ return JsonResponse(serialize(entry))
+ return _idempotent(request, data, action) if request.headers.get('Idempotency-Key') else action()
diff --git a/main/dreams/forms.py b/main/dreams/forms.py
new file mode 100644
index 0000000..c9a574f
--- /dev/null
+++ b/main/dreams/forms.py
@@ -0,0 +1,66 @@
+from django import forms
+from django.utils import timezone
+
+from planner.timezones import localdate_for_user, timezone_for_user
+from .models import DreamEntry
+
+
+def normalize_terms(value):
+ if not isinstance(value, list) or len(value) > 12:
+ raise forms.ValidationError('Use up to 12 terms.')
+ result = []
+ for item in value:
+ if not isinstance(item, str) or not item.strip() or len(item.strip()) > 40:
+ raise forms.ValidationError('Each term must be 1–40 characters.')
+ term = item.strip()
+ if term.casefold() not in {existing.casefold() for existing in result}:
+ result.append(term)
+ return result
+
+
+class DreamEntryForm(forms.ModelForm):
+ dreamed_at = forms.DateTimeField(required=False, label='Approximate time of dream',
+ input_formats=['%Y-%m-%dT%H:%M'],
+ widget=forms.DateTimeInput(format='%Y-%m-%dT%H:%M', attrs={'type': 'datetime-local'}))
+ tags_text = forms.CharField(required=False, label='Themes or tags', max_length=500)
+ emotions_text = forms.CharField(required=False, label='Emotions', max_length=500)
+
+ class Meta:
+ model = DreamEntry
+ fields = ('wake_up_date', 'dreamed_at', 'title', 'narrative', 'vividness',
+ 'is_nightmare', 'after_waking_notes', 'interpretation')
+ widgets = {
+ 'wake_up_date': forms.DateInput(format='%Y-%m-%d', attrs={'type': 'date'}),
+ 'narrative': forms.Textarea(attrs={'rows': 6}),
+ 'after_waking_notes': forms.Textarea(attrs={'rows': 3}),
+ 'interpretation': forms.Textarea(attrs={'rows': 3}),
+ 'vividness': forms.NumberInput(attrs={'min': 0, 'max': 10}),
+ }
+
+ def __init__(self, *args, user=None, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.user = user
+ if not self.is_bound and self.instance._state.adding and user:
+ self.fields['wake_up_date'].initial = localdate_for_user(user)
+ if not self.instance._state.adding:
+ self.fields['tags_text'].initial = ', '.join(self.instance.tags)
+ self.fields['emotions_text'].initial = ', '.join(self.instance.emotions)
+ if self.instance.dreamed_at:
+ self.fields['dreamed_at'].initial = timezone.localtime(
+ self.instance.dreamed_at, timezone_for_user(user))
+
+ def clean_tags_text(self):
+ return normalize_terms([part.strip() for part in self.cleaned_data['tags_text'].split(',') if part.strip()])
+
+ def clean_emotions_text(self):
+ return normalize_terms([part.strip() for part in self.cleaned_data['emotions_text'].split(',') if part.strip()])
+
+ def save(self, commit=True):
+ entry = super().save(commit=False)
+ if entry.dreamed_at and timezone.is_naive(entry.dreamed_at):
+ entry.dreamed_at = timezone.make_aware(entry.dreamed_at, timezone_for_user(self.user))
+ entry.tags = self.cleaned_data['tags_text']
+ entry.emotions = self.cleaned_data['emotions_text']
+ if commit:
+ entry.save()
+ return entry
diff --git a/main/dreams/migrations/0001_initial.py b/main/dreams/migrations/0001_initial.py
new file mode 100644
index 0000000..4f38084
--- /dev/null
+++ b/main/dreams/migrations/0001_initial.py
@@ -0,0 +1,43 @@
+# Generated by Django 6.1.1 on 2026-10-18 15:34
+
+import django.core.validators
+import django.db.models.deletion
+import django.utils.timezone
+import uuid
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='DreamEntry',
+ fields=[
+ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
+ ('wake_up_date', models.DateField(db_index=True)),
+ ('dreamed_at', models.DateTimeField(blank=True, null=True)),
+ ('title', models.CharField(max_length=160)),
+ ('narrative', models.TextField(max_length=20000)),
+ ('interpretation', models.TextField(blank=True, max_length=4000)),
+ ('tags', models.JSONField(blank=True, default=list)),
+ ('emotions', models.JSONField(blank=True, default=list)),
+ ('vividness', models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])),
+ ('is_nightmare', models.BooleanField(default=False)),
+ ('after_waking_notes', models.TextField(blank=True, max_length=4000)),
+ ('created_at', models.DateTimeField(default=django.utils.timezone.now)),
+ ('updated_at', models.DateTimeField(auto_now=True)),
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='dream_entries', to=settings.AUTH_USER_MODEL)),
+ ],
+ options={
+ 'ordering': ('-wake_up_date', '-created_at'),
+ 'indexes': [models.Index(fields=['user', '-wake_up_date'], name='dreams_drea_user_id_f28241_idx')],
+ },
+ ),
+ ]
diff --git a/main/dreams/migrations/__init__.py b/main/dreams/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/main/dreams/models.py b/main/dreams/models.py
new file mode 100644
index 0000000..5a6a308
--- /dev/null
+++ b/main/dreams/models.py
@@ -0,0 +1,31 @@
+import uuid
+
+from django.conf import settings
+from django.core.validators import MaxValueValidator, MinValueValidator
+from django.db import models
+from django.utils import timezone
+
+
+class DreamEntry(models.Model):
+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
+ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='dream_entries')
+ wake_up_date = models.DateField(db_index=True)
+ dreamed_at = models.DateTimeField(null=True, blank=True)
+ title = models.CharField(max_length=160)
+ narrative = models.TextField(max_length=20000)
+ interpretation = models.TextField(blank=True, max_length=4000)
+ tags = models.JSONField(default=list, blank=True)
+ emotions = models.JSONField(default=list, blank=True)
+ vividness = models.PositiveSmallIntegerField(null=True, blank=True,
+ validators=[MinValueValidator(0), MaxValueValidator(10)])
+ is_nightmare = models.BooleanField(default=False)
+ after_waking_notes = models.TextField(blank=True, max_length=4000)
+ created_at = models.DateTimeField(default=timezone.now)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ ordering = ('-wake_up_date', '-created_at')
+ indexes = [models.Index(fields=('user', '-wake_up_date'))]
+
+ def __str__(self):
+ return f'{self.title} ({self.wake_up_date})'
diff --git a/main/dreams/templates/dreams/_form.html b/main/dreams/templates/dreams/_form.html
new file mode 100644
index 0000000..15f6a8b
--- /dev/null
+++ b/main/dreams/templates/dreams/_form.html
@@ -0,0 +1,14 @@
+{% csrf_token %}
+{% if form.non_field_errors %}
{{ form.non_field_errors }}
{% endif %}
+
+{% for field in form %}
+
+ {% if field.name == 'is_nightmare' %}{% else %}{{ field.label_tag }}{{ field }}{% endif %}
+ {% if field.name == 'wake_up_date' %}Use the date you woke up, matching Health > Sleep.{% endif %}
+ {% if field.name == 'tags_text' or field.name == 'emotions_text' %}Separate terms with commas.{% endif %}
+ {% if field.name == 'interpretation' %}Your own interpretation, kept separate from what happened in the dream.{% endif %}
+ {% for error in field.errors %}
Woke {{ entry.wake_up_date|date:'j F Y' }}{% if entry.dreamed_at %} · Dreamed around {% endif %}{% if entry.is_nightmare %} · Nightmare{% endif %}{% if entry.vividness is not None %} · Vividness {{ entry.vividness }}/10{% endif %}
{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}
+ {% include 'food/partials/progress_ring.html' with ring=macro %}
{{ macro.label }}
{% if macro.eaten is None %}Known amount unavailable{% elif macro.incomplete %}At least {{ macro.eaten|floatformat:1 }} g{% else %}{{ macro.eaten|floatformat:1 }} g eaten{% endif %}{% if macro.goal is not None %} · {{ macro.goal|floatformat:1 }} g goal{% endif %}
{% if macro.incomplete %}
! {% if macro.goal is not None %}Remaining unknown{% else %}Nutrition incomplete · No target{% endif %}
{% elif macro.goal is not None %}
{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}
{% else %}
No target
{% endif %}
+ {% if macro.percent > 200 %}
{{ macro.full_laps }} full laps{% if macro.current_lap < 100 %} + {{ macro.current_lap|floatformat:0 }}% of next{% endif %}
{% endif %}
{{ macro.guidance.title }}
diff --git a/main/food/templates/food/partials/progress_ring.html b/main/food/templates/food/partials/progress_ring.html
new file mode 100644
index 0000000..c9be858
--- /dev/null
+++ b/main/food/templates/food/partials/progress_ring.html
@@ -0,0 +1,10 @@
+
+
+ {% if ring.percent is not None %}{{ ring.percent }}%{% else %}—{% endif %}
+
Give an app access to your food log and kitchen inventory. Keep tokens private.
+
Give an app access to your food log, kitchen inventory, or private stress and dream journals. Keep tokens private.
{% if new_token %}
New token
@@ -32,7 +32,7 @@
Connect an AI assistant
-
Compatible assistants can use your Food and Kitchen data through MCP. Access is limited to the permissions you grant.
+
Compatible assistants can use your Food, Kitchen, Stress Journal, and Dream Journal data through MCP. Access is limited to the permissions you grant.
@@ -49,7 +49,7 @@
Treat this token like a password. TaskNest does not save the token you paste here. You can revoke access from your API tokens.
-
ChatGPT
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.
+
ChatGPT
Add a custom MCP app in ChatGPT and enter the MCP server URL. Select OAuth authentication, then sign in to TaskNest and review the requested permissions. For dream and stress tools, select the optional private journal permission on the TaskNest consent page. If reconnecting skips consent, revoke the old ChatGPT authorization above and reconnect once. ChatGPT does not use the pasted token field.
Open WebUI
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.
Generic MCP client
Use Streamable HTTP at the URL above and send Authorization: Bearer <your token> as a separate header. Never put the token in the URL.
diff --git a/main/food/templates/oauth2_provider/authorize.html b/main/food/templates/oauth2_provider/authorize_tasknest.html
similarity index 64%
rename from main/food/templates/oauth2_provider/authorize.html
rename to main/food/templates/oauth2_provider/authorize_tasknest.html
index af7a153..7077f52 100644
--- a/main/food/templates/oauth2_provider/authorize.html
+++ b/main/food/templates/oauth2_provider/authorize_tasknest.html
@@ -9,11 +9,13 @@
{% else %}
Allow {{ application.name }}?
-
This assistant is requesting access to your TaskNest account. It can only use the permissions listed here.
+
Allow access grants the permissions listed here{% if offer_journal_scopes %} and any optional permissions you select below{% endif %}.
{% for scope in scopes_descriptions %}
{{ scope }}
{% endfor %}
+ {% if offer_journal_scopes %}
This connection did not request the newer private journal permissions. You can explicitly add them here for dream and stress tools.