in between state for mcp implementation

This commit is contained in:
Joren de Graaf
2026-10-07 15:49:38 +02:00
parent 4f8c3272aa
commit c825cd474e
17 changed files with 735 additions and 5 deletions
+18 -5
View File
@@ -3,6 +3,7 @@ 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
@@ -80,7 +81,7 @@ def api_view(scope, methods):
if failure:
return failure
required_scope = scope.get(request.method) if isinstance(scope, dict) else scope
if required_scope not in token.scopes:
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
@@ -197,13 +198,13 @@ def _inventory_data(item):
'added_at': item.added_at.isoformat(), 'updated_at': item.updated_at.isoformat()}
def _idempotent(request, payload, action):
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 = hashlib.sha256(request.path.encode() + b'\0' + request.body).hexdigest()
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)
@@ -233,6 +234,13 @@ def today(request):
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]
@@ -439,8 +447,13 @@ def attachment_create(request, identifier):
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}'
attachment.save()
return JsonResponse(_attachment_data(attachment), status=201)
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',))
+1
View File
@@ -2,6 +2,7 @@ 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),
+1
View File
@@ -7,3 +7,4 @@ class FoodConfig(AppConfig):
def ready(self):
from . import signals # noqa: F401
from . import oauth_signals # noqa: F401
+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())
+24
View File
@@ -30,5 +30,29 @@
</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 %}
+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)
+6
View File
@@ -1,6 +1,7 @@
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
@@ -10,6 +11,7 @@ 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):
@@ -45,6 +47,7 @@ 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,
})
@@ -55,4 +58,7 @@ def revoke_token(request, 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')
+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;
+7
View File
@@ -588,3 +588,10 @@ body[data-theme="dark"] .gitea-activity__cell--future { background: transparent;
.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))
+2
View File
@@ -2,5 +2,7 @@ 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
+30
View File
@@ -41,6 +41,7 @@ INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'oauth2_provider',
'planner',
'food.apps.FoodConfig',
]
@@ -59,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',
+3
View File
@@ -16,8 +16,11 @@ 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')),