add mcp
This commit is contained in:
+55
-13
@@ -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.')
|
||||
|
||||
Reference in New Issue
Block a user