Fix OAuth page

This commit is contained in:
Joren de Graaf
2026-10-19 16:51:53 +02:00
parent a8418cdba7
commit 743785c2e0
54 changed files with 1794 additions and 27 deletions
+112 -2
View File
@@ -23,7 +23,7 @@ API_BASE = os.environ.get('TASKNEST_API_BASE_URL', 'http://127.0.0.1:1234/api/v1
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']
SUPPORTED_SCOPES = ['food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal: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'
@@ -196,6 +196,52 @@ class RecipeAnalysisInput(BaseModel):
substitutions: dict[str, str] = Field(default_factory=dict)
class StressInput(BaseModel):
score: int = Field(ge=0, le=10)
recorded_at: str | None = None
timing: Literal['anytime', 'before_sleep', 'after_waking'] = 'anytime'
note: str = ''
tags: list[str] = Field(default_factory=list)
symptoms: list[Literal['tension', 'headache', 'fatigue', 'restlessness']] = Field(default_factory=list)
class StressChanges(BaseModel):
score: int | None = Field(default=None, ge=0, le=10)
recorded_at: str | None = None
timing: Literal['anytime', 'before_sleep', 'after_waking'] | None = None
note: str | None = None
tags: list[str] | None = None
symptoms: list[Literal['tension', 'headache', 'fatigue', 'restlessness']] | None = None
class DreamInput(BaseModel):
wake_up_date: str
title: str
narrative: str
dreamed_at: str | None = None
interpretation: str = ''
tags: list[str] = Field(default_factory=list)
emotions: list[str] = Field(default_factory=list)
vividness: int | None = Field(default=None, ge=0, le=10)
is_nightmare: bool = False
after_waking_notes: str = ''
class DreamChanges(BaseModel):
wake_up_date: str | None = None
title: str | None = None
narrative: str | None = None
dreamed_at: str | None = None
interpretation: str | None = None
tags: list[str] | None = None
emotions: list[str] | None = None
vividness: int | None = Field(default=None, ge=0, le=10)
is_nightmare: bool | None = None
after_waking_notes: str | None = None
append_narrative: str | None = None
append_after_waking_notes: str | None = None
def _token() -> str:
access = get_access_token()
if access is None:
@@ -330,7 +376,7 @@ async def _attach(entry_id, image_base64, image_file, mime_type, filename, capti
def create_server() -> MCPServer:
server = MCPServer('TaskNest', description='Food diary and kitchen inventory for the authenticated TaskNest user.',
server = MCPServer('TaskNest', description='Food, kitchen, and private stress and dream journals 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))
@@ -665,6 +711,70 @@ def create_server() -> MCPServer:
payload=payload, idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Search or list your private stress check-ins. Optional date is a local YYYY-MM-DD day; timing distinguishes before sleep from after waking. Read only.')
async def stress_search(query: str = '', date: str | None = None,
timing: Literal['anytime', 'before_sleep', 'after_waking'] | None = None,
limit: int = 30, offset: int = 0) -> dict[str, Any]:
params = {'query': query, 'limit': min(max(limit, 1), 100), 'offset': max(offset, 0)}
if date is not None:
params['date'] = date
if timing is not None:
params['timing'] = timing
return await api_request('GET', 'stress/', params=params)
@server.tool(structured_output=True, description='Read one stress check-in owned by the authenticated user using its ID. Read only.')
async def stress_get(entry_id: str) -> dict[str, Any]:
return await api_request('GET', f'stress/{entry_id}/')
@server.tool(structured_output=True, description='Create a private 0–10 stress check-in. Use before_sleep for stress before sleeping and after_waking for stress noticed after waking; do not conflate the two. Reuse idempotency_key on retries and update the returned ID for follow-up details.')
async def stress_create(entry: StressInput, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
data = await api_request('POST', 'stress/', payload=entry.model_dump(mode='json', exclude_none=True),
idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Update only supplied fields of one owned stress check-in. Use for conversational corrections or adding details to the existing ID instead of creating a duplicate.')
async def stress_update(entry_id: str, changes: StressChanges) -> dict[str, Any]:
return await api_request('PATCH', f'stress/{entry_id}/',
payload=changes.model_dump(mode='json', exclude_unset=True))
@server.tool(structured_output=True, description='Permanently delete one owned stress check-in. Require the user’s clear intent.')
async def stress_delete(entry_id: str) -> dict[str, Any]:
return await api_request('DELETE', f'stress/{entry_id}/')
@server.tool(structured_output=True, description='List or search your private dreams by keywords, tag, wake-up date or date range. Dates are local YYYY-MM-DD wake-up dates matching Health > Sleep. Read only.')
async def dream_search(query: str = '', tag: str = '', date: str | None = None,
date_from: str | None = None, date_to: str | None = None,
limit: int = 30, offset: int = 0) -> dict[str, Any]:
params = {'query': query, 'tag': tag, 'limit': min(max(limit, 1), 100), 'offset': max(offset, 0)}
for key, value in [('date', date), ('date_from', date_from), ('date_to', date_to)]:
if value is not None:
params[key] = value
return await api_request('GET', 'dreams/', params=params)
@server.tool(structured_output=True, description='Read one private dream entry by ID, including its original narrative and separately stored interpretation. Read only.')
async def dream_get(entry_id: str) -> dict[str, Any]:
return await api_request('GET', f'dreams/{entry_id}/')
@server.tool(structured_output=True, description='Create a private dream for its wake-up date. Record only details supplied by the user; do not invent or interpret. Use the returned ID for follow-ups and reuse idempotency_key on retries.')
async def dream_create(entry: DreamInput, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
data = await api_request('POST', 'dreams/', payload=entry.model_dump(mode='json', exclude_none=True),
idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Update or append user-supplied corrections to an existing owned dream ID. For append fields, reuse idempotency_key on retries; follow-ups must not create duplicate dreams.')
async def dream_update(entry_id: str, changes: DreamChanges,
idempotency_key: str | None = None) -> dict[str, Any]:
payload = changes.model_dump(mode='json', exclude_unset=True)
key = _key(idempotency_key) if any(name.startswith('append_') for name in payload) else idempotency_key
data = await api_request('PATCH', f'dreams/{entry_id}/', payload=payload, idempotency_key=key)
return {**data, **({'idempotency_key': key} if key else {})}
@server.tool(structured_output=True, description='Permanently delete an owned dream entry by ID. Require the user’s clear intent.')
async def dream_delete(entry_id: str) -> dict[str, Any]:
return await api_request('DELETE', f'dreams/{entry_id}/')
return server
+72 -7
View File
@@ -16,7 +16,7 @@ import httpx2
from PIL import Image
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import LiveServerTestCase, SimpleTestCase
from django.test import LiveServerTestCase, SimpleTestCase, override_settings
from django.utils import timezone
from mcp import Client
from mcp.client.streamable_http import streamable_http_client
@@ -78,7 +78,7 @@ class McpHttpTests(LiveServerTestCase):
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'])
['food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write'])
break
except httpx2.RequestError:
pass
@@ -142,6 +142,51 @@ class McpHttpTests(LiveServerTestCase):
asyncio.run(self._client(self.secret, check))
def test_stress_tools_support_incremental_updates(self):
_, journal_secret = create_token(self.a, 'Journal MCP test', ['journal:read', 'journal:write'])
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertTrue({'stress_create', 'stress_search', 'stress_get', 'stress_update', 'stress_delete'} <= names)
payload = {'entry': {'score': 7, 'timing': 'before_sleep', 'note': 'Work', 'tags': ['work']},
'idempotency_key': 'mcp-stress-test-1'}
created = (await client.call_tool('stress_create', payload)).structured_content
entry_id = created['id']
self.assertEqual((await client.call_tool('stress_create', payload)).structured_content['id'], entry_id)
updated = (await client.call_tool('stress_update', {'entry_id': entry_id,
'changes': {'note': 'Work and noise'}})).structured_content
self.assertEqual(updated['score'], 7)
self.assertEqual(updated['note'], 'Work and noise')
self.assertEqual((await client.call_tool('stress_get', {'entry_id': entry_id})).structured_content['note'], 'Work and noise')
self.assertEqual((await client.call_tool('stress_search', {'query': 'noise'})).structured_content['total'], 1)
self.assertFalse((await client.call_tool('stress_delete', {'entry_id': entry_id})).is_error)
self.assertEqual((await client.call_tool('stress_search')).structured_content['total'], 0)
asyncio.run(self._client(journal_secret, check))
def test_dream_tools_create_and_append_without_duplicates(self):
_, journal_secret = create_token(self.a, 'Dream MCP test', ['journal:read', 'journal:write'])
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertTrue({'dream_create', 'dream_search', 'dream_get', 'dream_update', 'dream_delete'} <= names)
payload = {'entry': {'wake_up_date': '2026-10-18', 'title': 'A house',
'narrative': 'First memory.', 'tags': ['house']},
'idempotency_key': 'mcp-dream-create-1'}
created = (await client.call_tool('dream_create', payload)).structured_content
entry_id = created['id']
self.assertEqual((await client.call_tool('dream_create', payload)).structured_content['id'], entry_id)
append = {'entry_id': entry_id, 'changes': {'append_narrative': 'Second memory.'},
'idempotency_key': 'mcp-dream-append-1'}
self.assertFalse((await client.call_tool('dream_update', append)).is_error)
self.assertFalse((await client.call_tool('dream_update', append)).is_error)
entry = (await client.call_tool('dream_get', {'entry_id': entry_id})).structured_content
self.assertEqual(entry['narrative'], 'First memory.\n\nSecond memory.')
self.assertEqual((await client.call_tool('dream_search', {'tag': 'house'})).structured_content['total'], 1)
self.assertFalse((await client.call_tool('dream_delete', {'entry_id': entry_id})).is_error)
asyncio.run(self._client(journal_secret, check))
def test_inventory_update_partial_quantity_and_structured_validation(self):
product = FoodProduct.objects.create(owner=self.a, product_name='Meatballs',
package_amount=Decimal('400'), package_unit='g')
@@ -200,7 +245,7 @@ class McpHttpTests(LiveServerTestCase):
asyncio.run(self._client(self.secret, check))
self.assertEqual(KitchenInventoryItem.objects.filter(pk__in=[item.pk for item in items], archived_at__isnull=False).count(), 2)
def test_oauth_issued_pat_authenticates_mcp(self):
def test_oauth_issued_pat_authenticates_mcp_with_journal_upgrade(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')
@@ -208,24 +253,44 @@ class McpHttpTests(LiveServerTestCase):
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',
'redirect_uri': 'http://localhost:9876/callback',
'scope': 'food:read food:write inventory:read inventory:write',
'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')
with override_settings(TASKNEST_MCP_PUBLIC_URL=self.mcp_url):
response = self.client.get('/o/authorize/', params, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'grant_journal_scopes')
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')
payload['grant_journal_scopes'] = 'on'
payload['journal_scope_offer'] = response.context['journal_scope_offer']
with override_settings(TASKNEST_MCP_PUBLIC_URL=self.mcp_url):
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']
self.assertEqual(set(response.json()['scope'].split()),
{'food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write'})
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)
self.assertFalse((await client.call_tool('inventory_list')).is_error)
dream = await client.call_tool('dream_create', {'entry': {'wake_up_date': '2026-10-18',
'title': 'User supplied', 'narrative': 'A room.'}, 'idempotency_key': 'oauth-dream-1'})
self.assertFalse(dream.is_error, dream)
dream_id = dream.structured_content['id']
self.assertEqual((await client.call_tool('dream_search', {'query': 'room'})).structured_content['total'], 1)
changed = await client.call_tool('dream_update', {'entry_id': dream_id,
'changes': {'append_narrative': 'A door.'}, 'idempotency_key': 'oauth-dream-append-1'})
self.assertFalse(changed.is_error, changed)
stress = await client.call_tool('stress_create', {'entry': {'score': 5},
'idempotency_key': 'oauth-stress-1'})
self.assertFalse(stress.is_error, stress)
self.assertEqual((await client.call_tool('stress_search')).structured_content['total'], 1)
asyncio.run(self._client(secret, check))
def test_food_inventory_tools_and_user_isolation(self):