Files
Django_TasksApp/main/MCP.md
T
2026-10-11 20:46:55 +02:00

10 KiB

TaskNest MCP server

The Streamable HTTP MCP endpoint exposes the Food and Kitchen API to an AI assistant. The server in mcp_server.server is an HTTP adapter: every user operation goes through /api/v1/ with the connected user's bearer token. It does not read Django models directly.

Local development

Install main/requirements.txt in the project virtual environment and run Django migrations. Start Django using the project's normal development command on port 1234, then start MCP from main/:

python -m uvicorn mcp_server.server:app --host 127.0.0.1 --port 8002

The endpoint is http://127.0.0.1:8002/mcp. Its protected resource metadata is at /.well-known/oauth-protected-resource/mcp. Django serves OAuth authorization server metadata at /.well-known/oauth-authorization-server and OAuth endpoints under /o/.

Set these variables in the MCP process for deployment:

Variable Purpose
TASKNEST_API_BASE_URL Internal Django API URL ending in /api/v1
TASKNEST_MCP_PUBLIC_URL Public HTTPS MCP URL ending in /mcp
TASKNEST_OAUTH_ISSUER_URL Public HTTPS Django origin used in OAuth metadata
TASKNEST_MCP_FILE_HOSTS Comma-separated HTTPS host allowlist for client-supplied file downloads

Set TASKNEST_MCP_PUBLIC_URL and TASKNEST_OAUTH_ISSUER_URL in Django as well. Keep the issuer URL consistent between both processes. The checked-in defaults use https://tasksnest.jorendegraaf.eu/; override both variables with local URLs when testing local OAuth. Do not place personal access tokens in URLs or environment variables. Bind MCP to loopback only when Caddy runs on the same host. When Caddy runs on another host and proxies to the app host's Tailnet address, bind MCP to that Tailnet address instead. The MCP process should have the same restart and logging policy as the Django service.

The public /mcp path must reach the MCP process, not Django. For the site's Caddy proxy, route the exact MCP path and protected-resource metadata to the MCP listener, and let the existing Django route handle OAuth metadata and /o/:

tasksnest.jorendegraaf.eu {
    handle /mcp {
        reverse_proxy 100.91.62.59:8002
    }
    handle /.well-known/oauth-protected-resource/mcp {
        reverse_proxy 100.91.62.59:8002
    }
    handle {
        reverse_proxy 100.91.62.59:1234
    }
}

Integrate these handle routes into the existing site block rather than replacing unrelated proxy settings. Preserve HTTPS and the Authorization header. The provided deploy/systemd/tasknest-mcp.service starts MCP on the app host's Tailnet address; adjust its address and virtualenv path if they differ, install it on the app host, and start it before reloading Caddy. If Caddy and Django are on the same host, replace the Caddy upstreams with 127.0.0.1 and bind MCP to 127.0.0.1.

Before reconnecting ChatGPT, verify the public endpoints: /.well-known/oauth-protected-resource/mcp must advertise https://tasksnest.jorendegraaf.eu/ as its authorization server; /.well-known/oauth-authorization-server must advertise public HTTPS authorization and token endpoints; and an unauthenticated POST to /mcp should return an MCP authentication response, not a Django 404. Restart the Django and MCP processes after changing their environment variables.

Connect a client

Open Settings → API tokens → Connect an AI assistant. For ChatGPT, use the public MCP URL and OAuth sign-in. ChatGPT must be able to reach the HTTPS URL and its OAuth metadata. For Open WebUI or another bearer-token client, create a personal token with only the scopes needed, choose Streamable HTTP, and enter the same MCP URL and token as a bearer credential. The helper's password field is local to the browser and clears when the page is left; it does not submit the token to the helper. Revoke a token from Settings when it is no longer needed.

The server exposes tools for food diary, product catalogue, inventory, and hydration reads and changes. food_attach_image and food_log_with_image accept a ChatGPT file object via image_file or base64 data via image_base64. Images must be JPEG, PNG, or WebP and at most 5 MiB. A client-supplied file URL must use HTTPS and an allowed host. The API performs image validation and ownership checks. Creation tools accept an idempotency_key; reuse the same key and arguments when retrying a request. food_log_with_image reports whether the entry was created even if its later attachment upload fails.

food_get_today accepts an optional date in YYYY-MM-DD format. Omit it for the user's local today; pass a calendar date to read another day, such as yesterday. The HTTP API supports the same parameter on GET /api/v1/food/today/?date=YYYY-MM-DD.

hydration_get_daily returns combined fluid intake, manual and Food Diary contributions, the daily goal, and remaining amount. hydration_log, hydration_update, and hydration_delete manage standalone manual entries. Use an idempotency_key with hydration_log when retrying. hydration_settings_get and hydration_settings_update configure automatic Food Diary counting and optional beverage rules. The Food Diary tools count eligible millilitre drinks during the food write; no additional hydration tool call is needed.

Product discovery and grocery photographs

Image interpretation belongs to the AI client. For a grocery photograph, identify the visible products and any readable barcodes, brands, package sizes, quantities, and storage locations, then send structured data to TaskNest. Unreadable details should remain unknown.

  1. Call food_lookup_product with a name or barcode. It searches the authenticated user's products and, by default, Open Food Facts. It never saves search results. Exact barcodes take precedence. include_open_food_facts: false limits the lookup to local products. A result has source, confidence, and either a local product_id or an external external_id/barcode.
  2. When the user selects an external candidate, call food_import_product with its barcode. It uses the existing Open Food Facts cache and returns a local product_id. An unknown barcode returns a structured failure; the caller can offer manual creation. If data is incomplete, missing nutrition stays unknown.
  3. For a product absent from both catalogues, call food_create_product with only observed facts. It accepts products without barcodes or nutrition. If a likely duplicate exists, it returns needs_review and candidates instead of making a duplicate.
  4. Call inventory_add with a local product_id for one item, or inventory_import_groceries for up to 20 groceries. The batch resolves local matches, can import confident Open Food Facts matches, and can create manual products when create_missing_products is true. It adds a separate inventory row for each successful item; existing stock is not incremented. A batch idempotency key is required; reuse the same key and payload on retry.

For ambiguous candidates, ask the user to select one or supply more identifying details. Report batch item statuses individually: added, needs_review, or skipped. A batch can return partial_success; successful items remain added while failed items do not leave partial product or inventory writes. A changed payload with the same idempotency key returns a conflict.

Partial inventory use

inventory_get_stock returns owned products, remaining totals, and individual packages. Use a product ID for a definite match; a text query returns candidates. inventory_preview_consumption is read only and shows package deductions and any shortage. inventory_consume requires a product ID, positive decimal amount, compatible unit, and idempotency key. It uses opened packages first, then best-before date and age. Set allow_partial only after the user explicitly accepts a shortage. inventory_undo_consumption records a reversal when the affected package quantities have not changed. All four tools enforce the existing inventory read or write scopes through the HTTP API.

inventory_update accepts an absolute remaining_amount for one owned package. Reductions use the same consumption service as inventory_consume; zero archives the package. It can update opened and notes in the same request. A rejected quantity returns success: false with error.details.field and error.details.reason.

Example tool arguments:

{"query":"Milbona Volle Chocolademelk","brand":"Milbona","limit":10,"include_open_food_facts":true}
{"product":{"name":"Volle Chocolademelk","brand":"Milbona","package_quantity":"1000","package_unit":"ml"},"idempotency_key":"product-chocolate-milk-1"}
{"items":[{"name":"Volle Chocolademelk","brand":"Milbona","quantity":2,"package_quantity":"1000","package_unit":"ml","location":"Koelkast"},{"name":"Crème fraîche","quantity":1,"location":"Koelkast"}],"create_missing_products":true,"idempotency_key":"grocery-import-2026-10-09"}

Product package size is stored as a numeric amount and unit alongside the existing display text. Inventory quantity counts packages. A single opened package can store remaining_amount; mixed packages with different remaining contents should be separate inventory rows. The batch import does not infer consumption from a photograph.

The OAuth consent page displays the requested scopes. OAuth access tokens are user-specific API tokens, and token revocation also revokes the matching OAuth grant. For production, use HTTPS and set the issuer and MCP URLs to the actual public hosts before connecting a client. Dynamic client registration is disabled; clients use OAuth Client ID Metadata Documents (CIMD). ChatGPT's document offers both none and private_key_jwt; this server selects none with PKCE because the installed Django OAuth Toolkit supports public CIMD clients only. Clients that do not explicitly offer none are rejected.

Verify

Run python manage.py test food.test_oauth_mcp mcp_server.tests from main/. These tests exercise OAuth issuance and revocation, the live HTTP MCP protocol, scopes, user isolation, image upload, idempotency, and tool results. A real external ChatGPT connection still requires a public HTTPS deployment and a client sign-in test.