# TaskNest MCP server The Streamable HTTP MCP endpoint exposes the Food, Kitchen, and Recipes 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/`: ```sh 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/`: ```caddyfile 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. ## Recipes Recipe tools use the connected user's recipes and products. `recipe_search` and `recipe_get` require `food:read`. Creation, updates, deletion, variation, ingredient, and subrecipe tools require `food:write`. Ingredient product IDs must belong to the user. Variations copy ingredients, substitutions, and component links; later edits are independent. Component recipes cannot form cycles. `recipe_cook_later_add`, `recipe_cook_later_remove`, and `recipe_cook_later_list` manage the authenticated user's Cook Later bookmarks. Add and remove require `food:write`; list requires `food:read`. The list includes owned recipes and currently published demo recipes visible in discovery. These actions do not log a meal or deduct inventory. Existing `recipe_search` and `recipe_get` responses include `is_cook_later`. Create a recipe, then add ingredients: ```json {"recipe":{"title":"Oat bowl","default_servings":"2","instructions_markdown":"Mix oats and milk."},"idempotency_key":"recipe-oat-bowl-1"} ``` ```json {"recipe_id":"","ingredient":{"name":"Oats","quantity":"150","unit":"g","inventory_product_id":"","nutrition_product_id":""},"idempotency_key":"oat-ingredient-1"} ``` `recipe_create_variation` accepts `recipe_id`, an optional `title`, and an optional `idempotency_key`. `recipe_subrecipe_add` accepts the parent `recipe_id`, owned `component_id`, positive decimal `quantity` (default 1), `unit` (default `servings`), and an optional `idempotency_key`. `recipe_subrecipe_remove` takes the parent `recipe_id` and returned `subrecipe_id`. Inventory deduction is an explicit two-step action. Call `recipe_check_inventory` with the recipe ID and an optional `options` object containing `servings`, `include_optional`, or `substitutions`. It returns shortages, the package deduction plan, and a signed `confirmation` only when stock is ready. After the user confirms that plan, pass its exact `confirmation` and `recipe_id` to `recipe_deduct_inventory`. A repeated confirmation returns the existing operation without deducting twice. `recipe_undo_inventory` takes the returned `stock_use_id` and reverses the deduction when affected packages have not changed. Preview requires `inventory:read`; deduction and undo require `inventory:write`. `recipe_log_meal` is a separate `food:write` action. It logs a nutrition snapshot for consumed servings and never deducts inventory. Supply `recipe_id`, `consumed_servings`, `meal`, and an `idempotency_key`; `servings`, `date`, and `time` are optional. Repeat the same key and arguments on retry to avoid duplicate diary entries. A recipe meal can be logged even when inventory is short. ```json {"recipe_id":"","consumed_servings":"1","meal":"dinner","date":"2026-10-12","idempotency_key":"recipe-dinner-2026-10-12-1"} ``` The corresponding HTTP routes are listed in `GET /api/v1/schema/`. Recipe meal dates use the user's local calendar date by default. Inventory deduction never creates a food diary entry as a side effect. ## 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: ```json {"query":"Milbona Volle Chocolademelk","brand":"Milbona","limit":10,"include_open_food_facts":true} ``` ```json {"product":{"name":"Volle Chocolademelk","brand":"Milbona","package_quantity":"1000","package_unit":"ml"},"idempotency_key":"product-chocolate-milk-1"} ``` ```json {"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.