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')