This commit is contained in:
Joren de Graaf
2026-10-09 14:43:46 +02:00
parent c825cd474e
commit 559c51e9bb
20 changed files with 322 additions and 27 deletions
+55 -13
View File
@@ -1,6 +1,7 @@
"""Streamable HTTP MCP adapter. All application operations cross the HTTP API."""
import base64
import binascii
import logging
import os
import uuid
from datetime import datetime
@@ -11,17 +12,22 @@ from urllib.parse import urlsplit
import httpx2
from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.auth.provider import AccessToken, TokenVerifier
from mcp.server.auth.routes import create_protected_resource_routes
from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.transport_security import TransportSecuritySettings
from pydantic import AnyHttpUrl, BaseModel, ConfigDict, Field
API_BASE = os.environ.get('TASKNEST_API_BASE_URL', 'http://127.0.0.1:1234/api/v1').rstrip('/')
MCP_PUBLIC_URL = os.environ.get('TASKNEST_MCP_PUBLIC_URL', 'http://127.0.0.1:8002/mcp')
OAUTH_ISSUER_URL = os.environ.get('TASKNEST_OAUTH_ISSUER_URL', 'http://127.0.0.1:1234')
MCP_PUBLIC_URL = os.environ.get('TASKNEST_MCP_PUBLIC_URL', 'https://tasksnest.jorendegraaf.eu/mcp')
OAUTH_ISSUER_URL = os.environ.get('TASKNEST_OAUTH_ISSUER_URL', 'https://tasksnest.jorendegraaf.eu/')
MAX_IMAGE_BYTES = 5 * 1024 * 1024
SUPPORTED_SCOPES = ['food:read', 'food:write', 'inventory:read', 'inventory:write']
FILE_HOSTS = tuple(host.strip().lower().lstrip('.') for host in
os.environ.get('TASKNEST_MCP_FILE_HOSTS', 'openai.com,oaiusercontent.com,chatgpt.com').split(',') if host.strip())
CHATGPT_BLOB_HOST = 'oaisdmntprukwest.blob.core.windows.net'
logger = logging.getLogger(__name__)
class ClientImageFile(BaseModel):
@@ -149,15 +155,29 @@ def _key(value):
return value or str(uuid.uuid4())
def _allowed_file_host(host):
return host == CHATGPT_BLOB_HOST or any(
host == allowed or host.endswith('.' + allowed) for allowed in FILE_HOSTS
)
async def _resolve_image(image_base64, image_file, mime_type, filename):
if bool(image_base64) == bool(image_file):
raise ToolError('Provide exactly one image: image_base64 or image_file.')
if image_file:
parsed = urlsplit(image_file.download_url)
try:
parsed = urlsplit(image_file.download_url)
port = parsed.port
except ValueError:
raise ToolError('Image download URL is invalid.') from None
host = (parsed.hostname or '').lower()
if parsed.scheme != 'https' or not host or parsed.username or parsed.password or parsed.port not in (None, 443) or not any(
host == allowed or host.endswith('.' + allowed) for allowed in FILE_HOSTS
):
if parsed.scheme != 'https' or not host:
raise ToolError('Image download URL must be HTTPS with a hostname.')
if parsed.username or parsed.password or port not in (None, 443):
raise ToolError('Image download URL contains unsupported credentials or port.')
if not _allowed_file_host(host):
# Never log or return the path/query: they may contain a signed URL.
logger.warning('Rejected image download host %r', host)
raise ToolError('Image download URL is not an allowed HTTPS file host.')
try:
async with httpx2.AsyncClient(timeout=20, follow_redirects=False) as client:
@@ -206,9 +226,9 @@ def create_server() -> MCPServer:
issuer_url=AnyHttpUrl(OAUTH_ISSUER_URL), resource_server_url=AnyHttpUrl(MCP_PUBLIC_URL),
required_scopes=[], validate_token_resource=False))
@server.tool(structured_output=True, description='Read today’s food diary for the authenticated TaskNest user, grouped by meal with totals, goals, and remaining calories/macros. Does not change data.')
async def food_get_today() -> dict[str, Any]:
data = await api_request('GET', 'food/today/')
@server.tool(structured_output=True, description='Read the authenticated user’s food diary for a specific local calendar day, grouped by meal with totals, goals, and remaining calories/macros. Optional date must be YYYY-MM-DD; omit it for today in the user’s time zone. For “yesterday”, pass yesterday’s calendar date. Does not change data.')
async def food_get_today(date: str | None = None) -> dict[str, Any]:
data = await api_request('GET', 'food/today/', params={'date': date} if date is not None else None)
entries = {meal: [_entry(item) for item in items] for meal, items in data['meals'].items()}
goals = data.get('goals', {})
mapping = {'calories_kcal': 'daily_calorie_goal', 'carbohydrates_g': 'carbohydrate_goal_g',
@@ -242,7 +262,7 @@ def create_server() -> MCPServer:
return {'success': True, 'deleted_entry_id': entry_id}
@server.tool(structured_output=True, meta={'openai/fileParams': ['image_file']}, description='Attach a client-supplied JPEG, PNG, or WebP image to one owned food entry. Supply either image_file from ChatGPT or image_base64 from a generic client; maximum 5 MiB and 25 megapixels. This adds a private attachment. Reuse idempotency_key on retries.')
async def food_attach_image(entry_id: str, image_base64: str | None = None, image_file: ClientImageFile | None = None,
async def food_attach_image(entry_id: str, image_base64: str | None = None, image_file: ClientImageFile = None,
mime_type: str | None = None, filename: str = 'image', caption: str = '',
idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
@@ -251,7 +271,7 @@ def create_server() -> MCPServer:
@server.tool(structured_output=True, meta={'openai/fileParams': ['image_file']}, description='Create one food entry and attach the user-supplied image in one operation. Use for “log this photo as dinner.” Supply image_file from ChatGPT or image_base64 from a generic client. Search saved products first when appropriate; knowingly estimated nutrition is allowed. If image upload fails after entry creation, the result explicitly says the entry was created and gives its ID. Reuse idempotency_key on retries.')
async def food_log_with_image(food: FoodInput, image_base64: str | None = None,
image_file: ClientImageFile | None = None, mime_type: str | None = None,
image_file: ClientImageFile = None, mime_type: str | None = None,
filename: str = 'image', caption: str = '',
idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
@@ -300,5 +320,27 @@ def create_server() -> MCPServer:
return server
app = create_server().streamable_http_app(streamable_http_path='/mcp', stateless_http=True,
json_response=True, max_request_body_size=8 * 1024 * 1024)
app = create_server().streamable_http_app(
streamable_http_path='/mcp', stateless_http=True, json_response=True,
max_request_body_size=8 * 1024 * 1024,
transport_security=TransportSecuritySettings(
allowed_hosts=[urlsplit(MCP_PUBLIC_URL).netloc, '127.0.0.1:*', 'localhost:*'],
allowed_origins=[f'{urlsplit(MCP_PUBLIC_URL).scheme}://{urlsplit(MCP_PUBLIC_URL).netloc}',
'https://chatgpt.com', 'http://127.0.0.1:*', 'http://localhost:*'],
),
)
# The SDK uses required_scopes for both metadata and transport authorization.
# TaskNest authorizes each API operation separately, so leave transport scopes
# empty and advertise the supported scopes only in the resource metadata route.
metadata_route = create_protected_resource_routes(
resource_url=AnyHttpUrl(MCP_PUBLIC_URL),
authorization_servers=[AnyHttpUrl(OAUTH_ISSUER_URL)],
scopes_supported=SUPPORTED_SCOPES,
)[0]
for index, route in enumerate(app.router.routes):
if getattr(route, 'path', None) == metadata_route.path:
app.router.routes[index] = metadata_route
break
else:
raise RuntimeError('MCP protected-resource metadata route is missing.')
+43 -1
View File
@@ -16,15 +16,33 @@ import httpx2
from PIL import Image
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import LiveServerTestCase
from django.test import LiveServerTestCase, SimpleTestCase
from django.utils import timezone
from mcp import Client
from mcp.client.streamable_http import streamable_http_client
from mcp.server.mcpserver.exceptions import ToolError
from oauth2_provider.models import Application
from food.api import create_token
from food.models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem
from planner.timezones import localdate_for_user
from .server import ClientImageFile, _allowed_file_host, _resolve_image
class ImageHostLoggingTests(SimpleTestCase):
def test_chatgpt_blob_account_is_allowed_without_allowing_other_blob_accounts(self):
self.assertTrue(_allowed_file_host('oaisdmntprukwest.blob.core.windows.net'))
self.assertFalse(_allowed_file_host('other.blob.core.windows.net'))
self.assertFalse(_allowed_file_host('not-oaisdmntprukwest.blob.core.windows.net'))
def test_rejected_file_logs_only_hostname(self):
image = ClientImageFile(download_url='https://files.example.invalid/private?signature=secret', file_id='test')
with self.assertLogs('mcp_server.server', level='WARNING') as captured:
with self.assertRaisesRegex(ToolError, 'not an allowed HTTPS file host'):
asyncio.run(_resolve_image(None, image, None, 'image'))
self.assertIn('files.example.invalid', captured.output[0])
self.assertNotIn('/private', captured.output[0])
self.assertNotIn('signature=secret', captured.output[0])
class McpHttpTests(LiveServerTestCase):
@@ -58,6 +76,8 @@ class McpHttpTests(LiveServerTestCase):
try:
response = httpx2.get(f'http://127.0.0.1:{self.port}/.well-known/oauth-protected-resource/mcp', timeout=1)
if response.status_code == 200:
self.assertEqual(response.json()['scopes_supported'],
['food:read', 'food:write', 'inventory:read', 'inventory:write'])
break
except httpx2.RequestError:
pass
@@ -80,6 +100,11 @@ class McpHttpTests(LiveServerTestCase):
def test_authentication_and_scope_boundaries(self):
async def check():
async with httpx2.AsyncClient(timeout=10) as http:
response = await http.post(self.mcp_url, headers={'Authorization': 'Bearer ' + self.secret,
'Host': 'untrusted.example', 'Accept': 'application/json, text/event-stream'},
json={'jsonrpc': '2.0', 'id': 1, 'method': 'tools/list'})
self.assertEqual(response.status_code, 421)
for secret in ('bad-token', self.expired_secret, self.revoked_secret):
async with httpx2.AsyncClient(timeout=10) as http:
response = await http.post(self.mcp_url, headers={'Authorization': 'Bearer ' + secret,
@@ -122,6 +147,9 @@ class McpHttpTests(LiveServerTestCase):
asyncio.run(self._client(secret, check))
def test_food_inventory_tools_and_user_isolation(self):
previous_day = localdate_for_user(self.a) - timedelta(days=1)
FoodLogEntry.objects.create(user=self.a, date=previous_day, meal='breakfast',
product_name_snapshot='Yesterday oats', amount=Decimal('100'), unit='g', calories_kcal=Decimal('120'))
image = Image.new('RGB', (2, 2), 'red')
output = io.BytesIO()
image.save(output, format='PNG')
@@ -132,6 +160,11 @@ class McpHttpTests(LiveServerTestCase):
self.assertEqual(len(names), 12)
today = (await client.call_tool('food_get_today')).structured_content
self.assertEqual(today['meals']['lunch'], [])
yesterday = (await client.call_tool('food_get_today', {'date': previous_day.isoformat()})).structured_content
self.assertEqual(yesterday['date'], previous_day.isoformat())
self.assertEqual(yesterday['meals']['breakfast'][0]['name'], 'Yesterday oats')
self.assertEqual(yesterday['totals']['calories_kcal'], '120')
self.assertTrue((await client.call_tool('food_get_today', {'date': 'yesterday'})).is_error)
products = (await client.call_tool('food_search_products', {'query': 'Pasta'})).structured_content
self.assertEqual(products['count'], 1)
self.assertEqual((await client.call_tool('food_search_products', {'query': 'Private rice'})).structured_content['count'], 0)
@@ -148,6 +181,15 @@ class McpHttpTests(LiveServerTestCase):
'image_base64': encoded, 'mime_type': 'image/png', 'filename': 'meal.png',
'idempotency_key': 'mcp-image-1'})).structured_content
self.assertTrue(image_result['success'])
unsafe_file = await client.call_tool('food_attach_image', {'entry_id': entry_id,
'image_file': {'download_url': 'http://127.0.0.1/private', 'file_id': 'test'}})
self.assertTrue(unsafe_file.is_error)
unknown_host = await client.call_tool('food_attach_image', {'entry_id': entry_id,
'image_file': {'download_url': 'https://files.example.invalid/private?signature=secret',
'file_id': 'test'}})
self.assertTrue(unknown_host.is_error)
self.assertNotIn('files.example.invalid', str(unknown_host.content))
self.assertNotIn('signature=secret', str(unknown_host.content))
combined_food = {'meal': 'lunch', 'amount': '1', 'unit': 'g',
'product_name': 'Estimated meal', 'calories_kcal': '850'}
combined = (await client.call_tool('food_log_with_image', {'food': combined_food,