142 lines
18 KiB
Markdown
142 lines
18 KiB
Markdown
# TaskNest MCP server
|
||
|
||
The Streamable HTTP MCP endpoint exposes the Food, Kitchen, Recipes, and private Stress Journal 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.
|
||
|
||
When `TASKNEST_API_BASE_URL` uses loopback HTTP, the MCP adapter marks that trusted local hop as HTTPS for Django's proxy security check. This keeps `SECURE_SSL_REDIRECT` enabled without redirecting API calls to a TLS listener on port 1234. Restart the MCP process after deploying adapter changes. A direct unauthenticated call to the loopback API without that header may return a 301 redirect; a public HTTPS API call should return a structured 401 instead.
|
||
|
||
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.
|
||
|
||
An existing ChatGPT connection may continue to request its original food and inventory scopes even after the server advertises the newer journal scopes. During a fresh OAuth consent, select **Also allow reading and changing my private dream and stress journals** if you want journal tools. The box is off by default; leaving it off preserves the requested scopes. Reconnecting without new consent or merely refreshing an old token does not add journal access. If ChatGPT skips the consent screen, revoke its old TaskNest authorization in API tokens and reconnect once. The consent screen lists the requested permissions and the optional journal upgrade separately.
|
||
|
||
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.
|
||
|
||
## Private stress journal
|
||
|
||
The `stress_search`, `stress_get`, `stress_create`, `stress_update`, and `stress_delete` tools use `journal:read` and `journal:write` scopes. Existing food and inventory tokens cannot read journal content. A check-in has a 0–10 score, optional note, stressor tags and physical symptoms, a timestamp, and a timing value: `anytime`, `before_sleep`, or `after_waking`. Naive timestamps use the user's saved time zone. Search supports text, local date, and timing filters. Create returns an ID; use that ID with `stress_update` for later conversational corrections rather than creating another entry. Reuse the same idempotency key and payload on creation retries. The web journal at `/stress/` provides history, a 30-day calendar, descriptive stress summaries, and nearby dream/stress entries. These comparisons describe timing only and do not establish causation.
|
||
|
||
The `dream_search`, `dream_get`, `dream_create`, `dream_update`, and `dream_delete` tools use the same private journal scopes. Dreams are associated with the local date on waking, matching Health > Sleep, and can be backdated. Keep the narrative separate from the user's own interpretation; do not infer or invent either. `dream_search` supports keywords, tag, date, date range, limit, and offset. Creation returns an ID and idempotency key; use the ID for follow-up corrections. `dream_update` can replace supplied fields or append narrative/after-waking details. Appends require an idempotency key to avoid duplicate text on retries. The web journal is at `/dreams/`; the Health sleep panel links to a matching dream on the selected wake-up date.
|
||
|
||
## 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":"<recipe UUID>","ingredient":{"name":"Oats","quantity":"150","unit":"g","inventory_product_id":"<owned product UUID>","nutrition_product_id":"<owned product UUID>"},"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":"<recipe UUID>","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`.
|
||
|
||
Inventory `quantity` is outer-package count. Flat packages use `pieces_per_package`, `remaining_pieces`, and optional explicit `piece_amount`. Nested packages add `inner_packs_per_package`, `pieces_per_inner_pack`, labels, and (for measured stock) `inner_pack_amount`. The outer amount and total piece count are derived from that metadata; per-piece weight is estimated from the measured inner-pack amount. `inventory_get_stock` exposes both piece and measured totals plus the nested breakdown. Preview and consume accept `pieces`, `inner_packs`, or matching g/ml amounts where the metadata supports conversion; measured deductions must map to whole pieces, with the final piece taking the exact remaining residual. `inventory_update` can reduce absolute `remaining_pieces` through the same atomic ledger. Converting a count-only legacy row requires explicitly setting package count so an old mistaken count is not multiplied into stock.
|
||
|
||
### Bulk inventory housekeeping
|
||
|
||
`inventory_bulk_update` accepts 1–50 `{item_id, changes}` entries. `changes` uses the same fields and stock rules as `inventory_update`; omitted fields stay unchanged. Optional `expected_updated_at` rejects an item that changed since it was read. `dry_run` defaults to true and returns per-item before/after snapshots without saving. Set `dry_run: false` and provide an `idempotency_key` to apply. The default allows valid entries to succeed when others fail; `atomic: true` rolls back the whole batch on any failure. Duplicate IDs and oversized batches are rejected before writes.
|
||
|
||
For example, preview two location changes with `items: [{"item_id": "…", "changes": {"location": "Metalen stellingkast"}}, {"item_id": "…", "changes": {"location": "Zwarte stellingkast"}}]`. Use the returned IDs and current item timestamps for execution. To correct expiry dates, set `best_before` to `YYYY-MM-DD` (or `null` to clear it).
|
||
|
||
`inventory_bulk_delete` accepts 1–20 explicit `item_ids` and defaults to a read-only preview showing names, quantities and locations. To archive those exact rows, use `dry_run: false`, `confirm: true` and a new `idempotency_key`. It never deletes food products or consumption history. Reuse the same key and payload for retries; a changed payload with the same key is rejected. Both tools report `validated`, `changed`, `unchanged`, `failed` or `rolled_back` per item and aggregate counts. Re-read inventory before cleanup after an interrupted request.
|
||
|
||
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.
|