in between state for mcp implementation
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""TaskNest's HTTP-only MCP adapter."""
|
||||
@@ -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)
|
||||
@@ -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))
|
||||
Reference in New Issue
Block a user