diff --git a/main/mcp_server/TOOL_AUDIT.md b/main/mcp_server/TOOL_AUDIT.md new file mode 100644 index 0000000..0f0d1a5 --- /dev/null +++ b/main/mcp_server/TOOL_AUDIT.md @@ -0,0 +1,112 @@ +# MCP tool catalog audit + +Card: [Audit all TasksNest MCP tools](https://projects.jorendegraaf.eu/projects/cards/358cce5d-056c-43b6-ae24-9ebf79fad64a/) + +## Baseline, 3 November 2026 + +`python3 main/mcp_server/tool_catalog_audit.py` extracts the current registrations in +`server.py` into `tool_catalog_baseline.json`. The baseline contains **93 tools**, +with no duplicate names or empty descriptions. It records the declared parameter +names and direct API calls. `food_attach_image` uses the `_attach` helper; 42 tools +have at least one dynamic API path, so their recorded expressions require manual +review. + +This is a source inventory, not a verified live MCP discovery snapshot. The existing +descriptions and inferred API methods must not be treated as verified scopes, +side effects, response schemas, or client behavior. + +## Review tracker + +| Batch | Scope | Status | Required evidence | +| --- | --- | --- | --- | +| 1 | Food diary, products, hydration | Scope mapping complete; first discovery changes tested; contract review pending | Input/output schemas, read/write/error responses | +| 2 | Inventory, grocery, housekeeping | Source scope mapping complete; first discovery changes tested | Response contracts, destructive confirmation, retries | +| 3 | Recipes and nutrition import | Source scope mapping complete; discovery preview scopes tested | Ownership, dietary warnings, provenance, response contracts | +| 4 | Journals and dietary preferences | Source scope mapping complete | Sensitive response contracts, time zones, archive/delete semantics | +| 5 | Cross-client discovery | Pending | Live list-tools snapshot, ChatGPT and Codex checks | + +For each tool, verify the actual handler and response before changing metadata. +Record purpose, use and avoid cases, a natural-language example, required scope, +side effects, retry behavior, error response, and schema gaps. Preserve existing +client contracts unless a separately reviewed migration is necessary. + +## Batch 1: verified endpoint scope and impact + +The scope column comes from the Django `@api_view` decorator on the routed +endpoint, including the method-specific scope for shared endpoints. All results +are owner-scoped through the bearer token. `food_log_with_image` makes two +requests, so an attachment failure can follow a successful log creation. + +| Tools | Scope | Impact / retry note | +| --- | --- | --- | +| `food_get_today`, `food_search_products`, `food_lookup_product` | `food:read` | Read only; lookup may call Open Food Facts | +| `food_create_product`, `food_import_product` | `food:write` | Create/reuse product; pass the same idempotency key on retry | +| `food_log` | `food:write` | Creates diary entry; exact package consumption only when explicitly requested | +| `food_update_entry`, `food_delete_entry` | `food:write` | Changes or deletes owned entry; deletion also removes attachments | +| `food_attach_image` | `food:write` | Adds private attachment to an owned entry; same key on retry | +| `food_log_with_image` | `food:write` | Creates entry then attaches image; inspect partial result before retry | +| `hydration_get_daily`, `hydration_settings_get` | `food:read` | Read only | +| `hydration_log`, `hydration_update`, `hydration_delete`, `hydration_settings_update` | `food:write` | Change manual entries or settings; creation supports idempotency key | + +Source references: `main/food/api_urls.py`, `main/food/api.py`, and +`main/mcp_server/server.py`. The API returns structured `{error: {code, message}}` +for authentication, scope, validation and domain errors. The MCP adapter converts +most HTTP errors into `ToolError`; `food_import_product` is an exception that +returns a `{status: failed, reason}` result. Response schemas remain broadly +typed as `dict[str, Any]` in the adapter and need response-specific review. + +### First implementation pass + +Expanded the server description to identify its domains, OAuth scope rule and +confirmation/retry safeguards. Updated product search, lookup and import +descriptions to distinguish their use cases and scopes, and made the manual +hydration delete tool state the required user intent. `test_tool_catalog.py` +checks that the static inventory matches registered tools and that these +discovery cues appear in the registered metadata. This pass changes metadata +only; it does not alter tool arguments, response envelopes or API behavior. + +## Batch 2: verified endpoint scope and impact + +Inventory and grocery operations use `inventory:read` for reads and +`inventory:write` for mutations. Two read-only previews (`inventory_preview_consumption` +and `housekeeping_preview`) use POST but are governed by different scopes: +`inventory:read` and `inventory:write` respectively. The latter can prepare a +short-lived confirmation but does not apply changes. These distinctions come +from the routed Django `@api_view` decorators. + +| Tools | Scope | Impact / use | +| --- | --- | --- | +| `inventory_list`, `inventory_search`, `inventory_get_stock`, `inventory_preview_consumption` | `inventory:read` | Read stock or preview a deduction | +| `inventory_add`, `inventory_import_groceries`, `inventory_update`, `inventory_bulk_update`, `inventory_bulk_delete`, `inventory_remove`, `inventory_consume`, `inventory_undo_consumption` | `inventory:write` | Change owned stock; bulk tools default to preview | +| `grocery_list`, `grocery_search`, `grocery_add_recipe` with `confirm=false` | `inventory:read` | Read shopping list or preview recipe needs | +| `grocery_add`, `grocery_edit`, `grocery_delete`, `grocery_add_recipe` with `confirm=true` | `inventory:write` | Change shopping list, never stock | +| `housekeeping_search`, `housekeeping_scan`, `housekeeping_history` | `inventory:read` | Discover candidates or read audit history | +| `housekeeping_preview`, `housekeeping_apply` | `inventory:write` | Preview or apply reviewed rename, merge, classification or link change | + +Discovery text now calls out the inventory preview scope, separates stock from +shopping list operations, and directs stock consumption through a preview. +Response shapes and domain error contracts still require individual review. + +## Batches 3 and 4: source permission audit + +The recipe API uses `food:read` for search, get, link listing, cook-later +listing and component composition preview. Recipe creation, update, deletion, +variation, ingredients, links, cook-later changes, subrecipes and meal logging +use `food:write`. Recipe stock preview uses `inventory:read`; stock confirm +and undo use `inventory:write`. Grocery recipe preview/confirmation is covered +in batch 2. Composition preview uses POST but is read scoped. + +Nutrition source ingredient/search/review reads use `food:read`. +Import preview and commit, ingredient correction, exclusion changes and recipe +feedback use `food:write`. Import preview uses POST and write scope but creates +no records. Its description now exposes that prerequisite. + +Stress and dream collection/item reads use `journal:read`; create, update and +delete use `journal:write`. Dietary preference, exception, audit and recipe +evaluation reads use `dietary_preferences:read`; create, update and archive +use `dietary_preferences:write`. A token without dietary read scope cannot +implicitly evaluate a recipe against private preferences. + +These are endpoint-source observations, not yet evidence that every client +receives accurate machine-readable output schemas. The adapter still advertises +generic object outputs for most tools. diff --git a/main/mcp_server/server.py b/main/mcp_server/server.py index e9b295a..1768263 100644 --- a/main/mcp_server/server.py +++ b/main/mcp_server/server.py @@ -451,7 +451,7 @@ async def _attach(entry_id, image_base64, image_file, mime_type, filename, capti def create_server() -> MCPServer: - server = MCPServer('TaskNest', description='Food, kitchen, and private stress and dream journals for the authenticated TaskNest user.', + server = MCPServer('TaskNest', description='Private TasksNest tools for Food Diary, saved products, hydration, kitchen inventory, groceries, recipes, nutrition sources, dietary preferences, and stress and dream journals. Read tools inspect the authenticated user’s data; write tools change it and require the corresponding OAuth scope. Search or preview before ambiguous or consequential writes, and reuse idempotency keys on retries. Never infer permission to delete, consume stock, log a meal, or accept a dietary warning from tool availability alone.', token_verifier=ApiTokenVerifier(), auth=AuthSettings( issuer_url=AnyHttpUrl(OAUTH_ISSUER_URL), resource_server_url=AnyHttpUrl(MCP_PUBLIC_URL), required_scopes=[], validate_token_resource=False)) @@ -478,7 +478,7 @@ def create_server() -> MCPServer: '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='Find food product candidates in your saved products and optionally Open Food Facts. Read only: never saves a search result. Exact barcodes rank first; ambiguous matches are candidates for user selection. External lookup may be unavailable.') + @server.tool(structured_output=True, description='Find food product candidates in saved products and optionally Open Food Facts. Requires food:read. Use for “identify this barcode”; use food_search_products for saved-only search. Read only: never saves a result. Exact barcodes rank first; ask the user to choose an ambiguous match. External lookup may be unavailable.') async def food_lookup_product(query: str = '', barcode: str | None = None, brand: str = '', package_quantity: Decimal | None = None, package_unit: Literal['g', 'ml'] | None = None, @@ -498,7 +498,7 @@ def create_server() -> MCPServer: payload=product.model_dump(mode='json', exclude_none=True), idempotency_key=key) return {**data, 'idempotency_key': key} - @server.tool(structured_output=True, description='Save a selected Open Food Facts product by numeric barcode into your product catalogue. Changes data; uses the configured cached external import. Does not invent missing nutrition. Returns a local product_id, or a structured not-found/error response. Reuse idempotency_key on retries.') + @server.tool(structured_output=True, description='Save a selected Open Food Facts product by numeric barcode into your product catalogue. Requires food:write. Use after the user selects a lookup candidate; do not use for manual facts or an ambiguous barcode. Changes data, does not invent missing nutrition, and returns a local product_id or a failed-status result. Reuse idempotency_key on retries.') async def food_import_product(barcode: str, idempotency_key: str | None = None) -> dict[str, Any]: key = _key(idempotency_key) try: @@ -652,13 +652,13 @@ def create_server() -> MCPServer: params = {'product_id': product_id, 'query': query, 'location_id': location_id} return await api_request('GET', 'kitchen/stock/', params={k: v for k, v in params.items() if v is not None}) - @server.tool(structured_output=True, description='Preview package deductions for one owned product without changing stock. Supports pieces and inner_packs when packaging is configured, plus matching g/ml amounts. Nested per-piece weights are estimates derived from measured inner-pack amounts; unsupported conversions return a clear error.') + @server.tool(structured_output=True, description='Preview package deductions for one owned product without changing stock. Requires inventory:read even though the underlying API uses POST. Use before inventory_consume, especially when stock may be short. Supports configured pieces, inner_packs and matching g/ml; derived per-piece weights are estimates. Unsupported conversions return an error.') async def inventory_preview_consumption(product_id: str, amount: Decimal, unit: str, package_id: str | None = None) -> dict[str, Any]: return await api_request('POST', 'kitchen/consumption/preview/', payload={ 'product_id': product_id, 'amount': str(amount), 'unit': unit, 'package_id': package_id}) - @server.tool(structured_output=True, description='Consume an exact quantity from owned inventory packages atomically. Requires a unique idempotency key. If stock is short, preview first and use allow_partial only with explicit user choice.') + @server.tool(structured_output=True, description='Consume an exact quantity from owned inventory packages atomically. Requires inventory:write, the user’s clear intent and a unique idempotency key. Preview with inventory_preview_consumption first; use allow_partial only if the user accepts the specific shortage. This changes stock but does not log a Food Diary meal.') async def inventory_consume(product_id: str, amount: Decimal, unit: str, idempotency_key: str, package_id: str | None = None, source_reference: str = '', description: str = '', allow_partial: bool = False) -> dict[str, Any]: @@ -694,7 +694,7 @@ def create_server() -> MCPServer: return await api_request('PATCH', f'hydration/manual/{entry_id}/', payload={k: v for k, v in changes.items() if v is not None}) - @server.tool(structured_output=True, description='Delete an owned standalone manual hydration entry. Does not affect Food Diary entries.') + @server.tool(structured_output=True, description='Delete an owned standalone manual hydration entry by ID. Requires food:write and the user’s clear intent. Does not affect Food Diary entries. Use hydration_update to correct an entry instead of deleting it.') async def hydration_delete(entry_id: str) -> dict[str, Any]: return await api_request('DELETE', f'hydration/manual/{entry_id}/') @@ -737,7 +737,7 @@ def create_server() -> MCPServer: async def recipe_link_remove(recipe_id: str, link_id: str) -> dict[str, Any]: return await api_request('DELETE', f'recipes/{recipe_id}/links/{link_id}/') - @server.tool(structured_output=True, description='Preview an explicitly selected set of owned component recipes. Returns ingredient details, nutrition completeness, duplicate ingredient warnings, and issues. Suggestion links are excluded; this does not create a recipe, log a meal, or deduct inventory.') + @server.tool(structured_output=True, description='Preview an explicitly selected set of owned component recipes. Requires food:read, although the API uses POST. Returns ingredient details, nutrition completeness, duplicate ingredient warnings, and issues. Suggestion links are excluded; this does not create a recipe, log a meal, or deduct inventory.') async def recipe_composition_preview(components: list[RecipeComponentInput]) -> dict[str, Any]: return await api_request('POST', 'recipes/compositions/preview/', payload={'components': [item.model_dump(mode='json') for item in components]}) @@ -763,7 +763,7 @@ def create_server() -> MCPServer: return await api_request('GET', 'recipes/cook-later/', params={'search': search, 'limit': limit, 'offset': offset}) - @server.tool(structured_output=True, description='List your grocery items by needed, purchased, or all status. Read only.') + @server.tool(structured_output=True, description='List your grocery items by needed, purchased, or all status. Requires inventory:read and changes nothing. This is a shopping list, not current kitchen stock; use inventory_search for stock.') async def grocery_list(status: Literal['needed', 'purchased', 'all'] = 'needed', limit: int = 30, offset: int = 0) -> dict[str, Any]: return await api_request('GET', 'groceries/', params={'status': status, 'limit': limit, 'offset': offset}) @@ -775,7 +775,7 @@ def create_server() -> MCPServer: return await api_request('GET', 'groceries/', params={'query': query, 'category': category, 'product_id': product_id or '', 'status': status, 'limit': limit, 'offset': offset}) - @server.tool(structured_output=True, description='Add one item to your grocery list. Does not change Kitchen Inventory. Reuse the idempotency key on retries.') + @server.tool(structured_output=True, description='Add one item to your grocery list. Requires inventory:write. Use for “put milk on my shopping list”; use inventory_add only for food already owned. Does not change Kitchen Inventory. Reuse the same idempotency key and payload on retries.') async def grocery_add(item: GroceryItemInput, idempotency_key: str | None = None) -> dict[str, Any]: key = _key(idempotency_key) data = await api_request('POST', 'groceries/', payload=item.model_dump(mode='json', exclude_none=True), @@ -791,7 +791,7 @@ def create_server() -> MCPServer: async def grocery_delete(item_id: str) -> dict[str, Any]: return await api_request('DELETE', f'groceries/{item_id}/') - @server.tool(structured_output=True, description='Preview or confirm missing ingredients for an owned recipe, scaled to servings and selected substitutions. Omit confirm to preview. Set confirm true to add; uncertain matches additionally require confirm_uncertain true after review. Does not change Kitchen Inventory.') + @server.tool(structured_output=True, description='Preview or confirm missing ingredients for an owned recipe, scaled to servings and selected substitutions. Preview requires inventory:read; confirm=true requires inventory:write and the user’s approval of the reviewed list. Uncertain matches additionally require confirm_uncertain=true. This changes groceries only, never Kitchen Inventory.') async def grocery_add_recipe(recipe_id: str, options: RecipeAnalysisInput | None = None, confirm: bool = False, confirm_uncertain: bool = False, idempotency_key: str | None = None) -> dict[str, Any]: diff --git a/main/mcp_server/test_tool_catalog.py b/main/mcp_server/test_tool_catalog.py new file mode 100644 index 0000000..5c481f7 --- /dev/null +++ b/main/mcp_server/test_tool_catalog.py @@ -0,0 +1,40 @@ +"""Discovery contract checks for the MCP catalog audit.""" + +from django.test import SimpleTestCase + +from .server import create_server +from .tool_catalog_audit import catalog + + +class ToolCatalogDiscoveryTests(SimpleTestCase): + def test_source_inventory_matches_registered_tools(self): + source_names = {item['name'] for item in catalog()} + registered = create_server()._tool_manager.list_tools() + self.assertEqual(source_names, {tool.name for tool in registered}) + self.assertEqual(len(registered), len(source_names)) + for tool in registered: + with self.subTest(tool=tool.name): + self.assertTrue(tool.description) + self.assertEqual(tool.parameters['type'], 'object') + self.assertEqual(tool.output_schema['type'], 'object') + + def test_first_batch_discovery_guides_product_and_destructive_choices(self): + tools = {tool.name: tool for tool in create_server()._tool_manager.list_tools()} + self.assertIn('food:read', tools['food_lookup_product'].description) + self.assertIn('food_search_products', tools['food_lookup_product'].description) + self.assertIn('food:write', tools['food_import_product'].description) + self.assertIn('user’s clear intent', tools['hydration_delete'].description) + + def test_inventory_discovery_distinguishes_preview_stock_and_shopping(self): + tools = {tool.name: tool for tool in create_server()._tool_manager.list_tools()} + self.assertIn('inventory:read', tools['inventory_preview_consumption'].description) + self.assertIn('inventory_consume', tools['inventory_preview_consumption'].description) + self.assertIn('inventory:write', tools['inventory_consume'].description) + self.assertIn('does not log a Food Diary meal', tools['inventory_consume'].description) + self.assertIn('not current kitchen stock', tools['grocery_list'].description) + + def test_cross_domain_previews_advertise_their_actual_scopes(self): + tools = {tool.name: tool for tool in create_server()._tool_manager.list_tools()} + self.assertIn('food:read', tools['recipe_composition_preview'].description) + self.assertIn('inventory:read', tools['grocery_add_recipe'].description) + self.assertIn('inventory:write', tools['grocery_add_recipe'].description) diff --git a/main/mcp_server/tool_catalog_audit.py b/main/mcp_server/tool_catalog_audit.py new file mode 100644 index 0000000..c3971ae --- /dev/null +++ b/main/mcp_server/tool_catalog_audit.py @@ -0,0 +1,51 @@ +"""Generate a reviewable inventory of the MCP tools declared in server.py. + +Run from the repository root: python main/mcp_server/tool_catalog_audit.py +This is static analysis: endpoint scopes and response contracts still need review. +""" + +import ast +import json +from pathlib import Path + + +SOURCE = Path(__file__).with_name('server.py') +OUTPUT = Path(__file__).with_name('tool_catalog_baseline.json') + + +def catalog(): + tree = ast.parse(SOURCE.read_text()) + tools = [] + for node in ast.walk(tree): + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + decorators = [d for d in node.decorator_list if isinstance(d, ast.Call) + and isinstance(d.func, ast.Attribute) and d.func.attr == 'tool'] + if not decorators: + continue + decorator = decorators[0] + description = next((ast.literal_eval(k.value) for k in decorator.keywords + if k.arg == 'description' and isinstance(k.value, ast.Constant)), '') + calls = [c for c in ast.walk(node) if isinstance(c, ast.Call) + and isinstance(c.func, ast.Name) and c.func.id == 'api_request'] + endpoints = [] + for call in calls: + if len(call.args) >= 2: + endpoints.append({'method': ast.unparse(call.args[0]), + 'path': ast.unparse(call.args[1])}) + tools.append({ + 'name': node.name, + 'line': node.lineno, + 'description': description, + 'parameters': [arg.arg for arg in node.args.args], + 'endpoints': endpoints, + 'needs_scope_review': True, + 'needs_output_schema_review': True, + }) + return sorted(tools, key=lambda item: item['name']) + + +if __name__ == '__main__': + items = catalog() + OUTPUT.write_text(json.dumps({'tool_count': len(items), 'tools': items}, indent=2) + '\n') + print(f'Wrote {len(items)} tools to {OUTPUT}')