diff --git a/docs/integrations/mcp.md b/docs/integrations/mcp.md index b655940..6b71b29 100644 --- a/docs/integrations/mcp.md +++ b/docs/integrations/mcp.md @@ -2,7 +2,7 @@ CatalogIT includes an **MCP server** for AI clients that support local stdio or hosted Streamable HTTP. The MCP process calls CatalogIT's REST API using an API token; it does not connect directly to PostgreSQL. Every API request is authorized as the CatalogIT user who owns the token. -The first release provides tools to search/list services, fetch a service by ID, search vendors and hardware, read service cost records, read the change history of a record, and (for admins) read the global audit log. Hardware and financial tools require the corresponding CatalogIT visibility permissions. A small set of write tools can create and update vendors, tags, and services; the MCP server cannot delete or archive records. +The MCP server provides tools to search/list services, fetch a service by ID, search vendors, hardware, and payment methods, read service and hardware cost records, read the change history of a record, and (for admins) read the global audit log. Hardware and financial tools require the corresponding CatalogIT visibility permissions. A small set of write tools can create and update vendors, tags, and services, and create, update, and delete cost records. The MCP server cannot delete or archive services, hardware, vendors, or tags. ## Requirements @@ -16,7 +16,7 @@ The first release provides tools to search/list services, fetch a service by ID, Create a dedicated CatalogIT user for the assistant, then create an API token while signed in as that user. Tokens inherit the user's role and feature permissions. Start with a viewer account and grant financial or hardware visibility only if the workflow needs it. Store the token as a secret in your AI client's MCP configuration; treat it like a password and revoke it in **Settings → API Tokens** if exposed. -What the assistant can change depends on the token owner's role: with a viewer account every write tool fails with `403`, so the connection is effectively read-only. Editors can create tags and create or update services; vendor writes and tag updates need an admin. Do not reuse an admin token when a lower-privilege account is sufficient. +What the assistant can change depends on the token owner's role: with a viewer account every write tool fails with `403`, so the connection is effectively read-only. Editors can create tags, create or update services, and change cost records if they also have financial visibility; vendor writes and tag updates need an admin. Do not reuse an admin token when a lower-privilege account is sufficient. ## Configure a local MCP client @@ -55,7 +55,9 @@ Restart or reload the AI client, then confirm that the CatalogIT tools appear in | `list_vendors` | List or search vendors by name | Catalog access | | `list_hardware_assets` | Search assets by model, serial, status, or location; optionally filter by hardware type or archive state | Hardware visibility | | `get_service_cost_records` | Read costs for a service | Financial visibility | -| `get_record_history` | Read the change history of a service, hardware asset, vendor, or tag by UUID, newest first; service and hardware history include attachment changes | Catalog access; hardware history requires hardware visibility | +| `get_hardware_cost` | Read the purchase cost of a hardware asset | Financial and hardware visibility | +| `list_payment_methods` | List or search payment methods by name | Catalog access | +| `get_record_history` | Read the change history of a service, hardware asset, vendor, tag, or cost record by UUID, newest first; service and hardware history include attachment changes | Catalog access; hardware history requires hardware visibility; cost record history requires financial visibility (and hardware visibility for hardware costs) | | `list_audit_events` | Read the global audit log, newest first; optionally filter by category (`data_change`, `security`, `notification`, `error`) | Admin | List tools default to 50 results and accept `limit` from 1 to 100. `get_record_history` and `list_audit_events` are paginated instead: they accept `page` (from 1) and `per_page` (from 1 to 100) and return `total_pages`. Searching filters the API's current list response, so large catalogs may still require the API to return the complete list before the MCP server narrows the result. @@ -81,16 +83,23 @@ Write tools change CatalogIT data. They call the same API endpoints as the web U | `update_tag` | Rename a tag or change its color | Admin | | `create_service` | Create a service with name, description, status, vendor, category, classification, environment, criticality, renewal date, seats, SSO/SCIM flags, and tags | Editor or admin | | `update_service` | Change any of those fields on one service by UUID; add or remove individual tags | Editor or admin | +| `create_service_cost_record` | Add a cost record to a service: fiscal year, amount, record type (`actual`, `estimated`, `budget`), and optional purchase year and payment method | Editor or admin with financial visibility | +| `update_service_cost_record` | Change any of those fields on one service cost record | Editor or admin with financial visibility | +| `delete_service_cost_record` | Permanently delete one service cost record | Editor or admin with financial visibility | +| `set_hardware_cost` | Set the purchase cost of a hardware asset; each asset has one cost record of type `actual` | Editor or admin with financial and hardware visibility | +| `delete_hardware_cost` | Permanently remove the purchase cost of a hardware asset | Editor or admin with financial and hardware visibility | -Update tools change only the fields passed and cannot clear a field. Write tools do not set notes, points of contact, owners, assignees, notification recipients, cost centers, payment methods, contracts, or renewal schedules; use the web UI for those. Archived services accept only description and status changes. +Update tools change only the fields passed and cannot clear a field; `set_hardware_cost` keeps the current purchase and fiscal year when they are omitted. Write tools do not set notes (including cost-record notes), points of contact, owners, assignees, notification recipients, a service's cost center, payment method, or contract, or renewal schedules; use the web UI for those. Archived services accept only description and status changes. Cost records of archived services and archived hardware are read-only. Delete tools are annotated as destructive; the MCP server instructs assistants to confirm with the user before running them. Examples: - “Create a vendor called Acme with website acme.example.” - “Tag [service name] as SaaS and remove the Legacy tag.” - “Set the criticality of [service name] to High.” +- “Add a 2027 budget of 12,000 for [service name].” (Requires financial visibility.) +- “Set the purchase cost of laptop [serial] to 1,850.” (Requires financial and hardware visibility.) -The MCP server excludes service notes, personal contact details, hardware notes and cellular identifiers, vendor notes, and cost-record notes from its results. History values also omit hardware assignees, cost centers, payment methods, and attachment storage keys. History and audit results name the person who made a change but not their email address. `list_audit_events` returns each event's summary and, for data changes, only the names of changed fields; use `get_record_history` to see values. It does not offer arbitrary SQL, bulk changes, archiving, or record deletion. +The MCP server excludes service notes, personal contact details, hardware notes and cellular identifiers, vendor notes, and cost-record notes from its results. History values also omit hardware assignees, cost centers, payment methods, and attachment storage keys. History and audit results name the person who made a change but not their email address. `list_audit_events` returns each event's summary and, for data changes, only the names of changed fields; use `get_record_history` to see values. It does not offer arbitrary SQL, bulk changes, archiving, or deletion of records other than cost records. ## Troubleshooting diff --git a/docs/releases/next.md b/docs/releases/next.md index 0ff633f..3247bc6 100644 --- a/docs/releases/next.md +++ b/docs/releases/next.md @@ -1,3 +1,7 @@ # Next release -No unreleased changes yet. Released notes: [v1.6.x](v1.6.md), [v1.5.2](v1.5.2.md). +Released notes: [v1.6.x](v1.6.md), [v1.5.2](v1.5.2.md). + +## MCP cost record tools + +The MCP server can now change cost records. `create_service_cost_record`, `update_service_cost_record`, and `delete_service_cost_record` manage a service's costs; `set_hardware_cost` and `delete_hardware_cost` set or remove a hardware asset's purchase cost. New read tools `get_hardware_cost` and `list_payment_methods` support them, and `get_record_history` accepts `record_type="cost_record"`. Each tool calls the existing API, so writes need an editor or admin with financial visibility (plus hardware visibility for hardware costs), cost records of archived services and hardware stay read-only, and every change is recorded in history under the token owner. Delete tools are annotated as destructive, and cost-record notes are neither returned nor set. The MCP server still cannot delete or archive services, hardware, vendors, or tags. See [MCP and AI assistants](../integrations/mcp.md). diff --git a/docs/superpowers/specs/2026-11-02-bulk-actions-design.md b/docs/superpowers/specs/2026-11-02-bulk-actions-design.md new file mode 100644 index 0000000..e2b583e --- /dev/null +++ b/docs/superpowers/specs/2026-11-02-bulk-actions-design.md @@ -0,0 +1,284 @@ +# Bulk Edit and Bulk Actions Design + +## Goal + +Let users select many Services, Hardware assets, or Users in a list and change them in one operation: + +- **Bulk edit**: set shared fields such as status, category, location, tags, or role. +- **Bulk actions**: archive (deactivate for users), unarchive (activate for users), and delete. + +Every bulk operation applies the same rules as the single-record endpoints. A bulk operation is all-or-nothing: if one record fails a rule, the operation stops, no record changes, and the UI shows which record failed and why. + +## Current rules to preserve + +### Services (`backend/app/routers/services.py`) + +- Update, archive, unarchive: editor or admin. +- Delete: admin only. The service must be archived first (`409 Service must be archived before it can be deleted`). Delete also removes attachments (database rows and S3 objects). +- Archived services accept only `description`, `point_of_contact`, `notes`, and `status` changes (`400`). +- At most `MAX_TAGS_PER_SERVICE` (5) tags per service. Unknown tag, status, vendor, category, or classification ids return `400`. +- Assignee count cannot exceed `total_seats`. +- Financial fields are scrubbed from responses without financial visibility. + +### Hardware (`backend/app/routers/hardware_assets.py`) + +- Every endpoint requires hardware visibility. +- Update, archive, unarchive: editor or admin. Delete: admin only, archived first. +- Archived hardware accepts only `notes`, `status`, `hardware_status_id`, `hardware_location_id`, and `mdm_connected`. +- The merged record is validated with `HardwareAssetCreate`. For example, `operating_system` must be valid for the `hardware_type`. + +### Users (`backend/app/routers/users.py`) + +- Every endpoint: admin only. Users have no archive; `is_active` is the equivalent. +- An admin cannot demote, deactivate, or delete their own account. +- The last admin cannot be deleted. +- Identity fields (`email`, `first_name`, `last_name`, `display_name`, `department`) can change only for `provisioning_source = local`. +- Delete fails when the user owns services, is assigned to services, or holds hardware. +- Role `admin` removes explicit permission rows. Other roles keep `permissions` (`financial_view`, `hardware_view`). +- SCIM can set `is_active` again on its next sync. + +### Transactions and audit + +- `get_audited_db` opens one session per request and commits after the handler. One request is one transaction. +- The `after_flush` audit listener writes a history row for each changed record, attributed to the current user. Bulk operations get per-record history with no extra work. + +## Design + +### Principle: one rule set, two entry points + +Move the body of each single-record handler into a plain async function. The single endpoint and the bulk endpoint both call it. This keeps bulk logic identical to single-record logic. + +| Entity | New functions | Location | +| --- | --- | --- | +| Service | `apply_service_update(db, service, update_data)`, `archive_service_record(service)`, `unarchive_service_record(service)`, `prepare_service_delete(db, service) -> list[str]` | `backend/app/routers/services.py` (or `backend/app/domain/services.py` if the file gets too long) | +| Hardware | `apply_hardware_update(db, hardware, update_data)`, `archive_hardware_record(hardware)`, `unarchive_hardware_record(hardware)`, `prepare_hardware_delete(db, hardware) -> list[str]` | `backend/app/routers/hardware_assets.py` | +| User | `apply_user_update(db, user, data, current_user)`, `check_user_deletable(db, user, current_user)`, `delete_user_record(db, user, current_user)` | `backend/app/routers/users.py` | + +The functions raise the same `HTTPException`s as today. The single-record endpoints must keep their current responses. Run the existing tests before and after the extraction. + +`prepare_*_delete` returns the S3 storage keys and deletes only the database rows. See "Attachments on bulk delete". + +### API + +One endpoint per entity. The body uses an `action` discriminator: + +``` +POST /api/services/bulk +POST /api/hardware/bulk +POST /api/users/bulk +``` + +These paths do not collide with existing routes: `POST /api/services/` and `POST /api/services/{id}/archive` are the only other `POST` routes. Register the bulk route before the `/{id}` routes anyway, to keep matching order obvious. + +Request: + +```json +{ + "action": "update", + "ids": ["", ""], + "changes": { "service_status_id": "", "add_tag_ids": [""] } +} +``` + +`action` values: + +| Entity | `update` | `archive` | `unarchive` | `delete` | +| --- | --- | --- | --- | --- | +| Services | editor, admin | editor, admin | editor, admin | admin | +| Hardware | editor, admin + hardware visibility | same | same | admin + hardware visibility | +| Users | admin (`archive` = deactivate, `unarchive` = activate) | admin | admin | admin | + +`unarchive` is included so a bulk archive can be undone in one step. + +Batch rules, checked before any record changes: + +- `ids`: 1 to 500 unique UUIDs. Remove duplicates. More than 500 returns `422`. +- `changes`: required for `update`, forbidden for other actions. An empty `changes` returns `422`. +- Every id must exist. Otherwise return `404` and list the missing ids. +- Role and permission dependencies apply per action, as in the table. + +Processing: + +1. Load all records with `SELECT ... WHERE id IN (...) ORDER BY id FOR UPDATE`. The fixed order prevents deadlocks between two concurrent bulk requests. +2. Process records in the order of `ids` in the request, so the failing record is the same on every retry. +3. Call the shared function for each record. On the first `HTTPException`, stop, roll back the transaction, and return the error in the shape below. +4. Flush once after the loop to surface constraint errors such as `IntegrityError`, then commit. + +Success response, `200`: + +```json +{ "action": "update", "count": 12, "ids": ["..."] } +``` + +The UI reloads the list after success, so the response does not include the records. + +Failure response. Keep the HTTP status of the underlying rule (`400`, `403`, `404`, `409`, `422`): + +```json +{ + "detail": { + "message": "Archived services only allow updates to description, point of contact, notes, and status", + "record_id": "", + "record_label": "Slack", + "position": 4, + "applied": 0 + } +} +``` + +- `record_label`: service name, hardware serial number or model name, or user email. +- `applied` is always 0 and tells API clients that the operation rolled back. +- Batch-level errors (size, missing ids, role) have no `record_id`. + +### `changes` schemas + +Each schema is a new Pydantic model with `extra="forbid"`. Every field is optional. A field that is not sent stays unchanged. A field sent as `null` clears the value, but only where the single-record endpoint allows `null`. Bulk edit excludes free-text and unique fields (name, serial number, email, notes). + +`ServiceBulkChanges`: + +| Field | Notes | +| --- | --- | +| `service_status_id` | Sets `status` too, as the single update does. Allowed on archived services. | +| `category_id` | Nullable | +| `classification_id` | Nullable | +| `vendor_id` | Nullable | +| `environment` | Nullable | +| `criticality` | `Critical`, `High`, `Medium`, `Low`, or `null` | +| `add_tag_ids`, `remove_tag_ids` | Computed per service: current tags minus removes, plus adds. Then passed as `tag_ids`, so the 5-tag limit applies. The same id in both lists returns `422`. | +| `renewal_reminders_enabled` | Boolean | +| `sso_integrated`, `scim_enabled` | Boolean | + +`HardwareBulkChanges`: + +| Field | Notes | +| --- | --- | +| `hardware_status_id` | Allowed on archived hardware | +| `hardware_location_id` | Nullable. Allowed on archived hardware. | +| `mdm_connected` | Boolean. Allowed on archived hardware. | +| `operating_system` | Nullable. The merged record is validated per `hardware_type`, so a mixed selection can fail. | + +Hardware has no tags or category. `hardware_type` is excluded because a type change affects quantity, serial number, and cellular identifiers per record. + +`UserBulkChanges`: + +| Field | Notes | +| --- | --- | +| `role` | `admin`, `editor`, `viewer`. Self-demotion fails. | +| `department` | Nullable. Fails for SCIM or OIDC users. | +| `receive_renewal_notifications` | Boolean | +| `add_permissions`, `remove_permissions` | Slugs from `ALLOWED_USER_PERMISSION_SLUGS`. Merged per user, then passed as `permissions`. Ignored for admins, as today. | + +User activation uses the `archive` and `unarchive` actions, not `changes.is_active`. Activation then follows the same rules as archive in the UI and in permissions. + +### Attachments on bulk delete + +`delete_entity_attachments` deletes S3 objects before the transaction commits. In a bulk delete, a failure on record 30 would roll back the database but leave records 1 to 29 without their files. Bulk delete must avoid this: + +1. Collect storage keys and delete the database rows for every record. +2. Commit. Bulk routes use `Depends(get_audited_db, scope="function")` and commit explicitly before step 3. +3. Delete the S3 objects. A failure here only logs a warning with the orphan keys; the records are already deleted. + +Change the single-record delete to use the same order. It has the same problem on a smaller scale. + +### Frontend + +#### `DataTable` selection + +`frontend/src/components/DataTable.tsx` gets opt-in selection props: + +```ts +selectable?: boolean; +getRowId?: (row: T) => string; +selectedIds?: ReadonlySet; +onSelectionChange?: (ids: Set) => void; +``` + +- A checkbox column at the start. The header checkbox selects or clears all rows that match the current filters, and shows the indeterminate state for a partial selection. +- Shift-click selects a range. +- A checkbox click does not trigger row navigation. The existing interactive-element guard already covers `input`. +- When filters change, remove ids that are no longer visible. A hidden record must never be in a bulk operation. +- Clear the selection when the Active/Archived view changes and after a successful bulk operation. +- Do not show the selection column to users with no bulk action: viewers on Services and Hardware, and non-admins on Users. + +#### Bulk action bar + +New `frontend/src/components/BulkActionBar.tsx`. It is a sticky bar above the table, visible when one or more rows are selected: + +`12 selected · Edit fields · Archive · Delete · Clear selection` + +| Page | Active view | Archived view | +| --- | --- | --- | +| Services (`Services.tsx`) | Edit fields, Archive | Edit status, Unarchive, Delete (admin) | +| Hardware (`Hardware.tsx`) | Edit fields, Archive | Edit status/location/MDM, Unarchive, Delete (admin) | +| Users (`Users.tsx`) | Edit fields, Deactivate, Activate, Delete | n/a (single list) | + +Delete appears in the active view only when the API would accept it: never for services or hardware, which must be archived first. + +#### Bulk edit dialog + +New `frontend/src/components/BulkEditDialog.tsx`, driven by a per-entity field config: + +- One row per field, with three modes: **Leave unchanged** (default), **Set to** (a select from reference data), and **Clear** (only for nullable fields). +- Tags: "Add tags" and "Remove tags" pickers that reuse `TagPicker`. +- Permissions: "Grant" and "Revoke" checkboxes. +- The submit button is disabled while every field is "Leave unchanged". +- The summary line reads: "Change 2 fields on 12 services". + +#### Confirmation and results + +- Archive, deactivate: a confirmation dialog with the count and the first 10 record labels. +- Delete: a confirmation dialog with the count, the record labels, and an "This cannot be undone" warning. The user must type the count to enable the button. +- Success: a toast ("12 services archived"), a list reload, and a cleared selection. +- Failure: an inline error in the dialog, for example: "Nothing was changed. 'Slack' (4 of 12): A service can have at most 5 tags." The selection is kept so the user can fix it and retry. A "Select only this record" link helps the user inspect the failing record. + +## Out of scope + +- Bulk changes to owners, assignees, notification recipients, cost centers, payment methods, contracts, renewal settings, and hardware assignment. +- Bulk operations through MCP. The MCP documentation keeps the "no bulk changes" statement. +- Best-effort mode (apply valid records, skip invalid ones) and a dry-run preview. A future `dry_run: true` flag fits this API: run every check, roll back, and return all failures. +- Undo beyond unarchive and activate. +- Bulk operations on vendors, tags, and other reference data. + +## Tests + +Backend (`uv run --with pytest pytest -q`, as in CI), new `backend/tests/test_bulk_services.py`, `test_bulk_hardware.py`, `test_bulk_users.py`: + +- The single-record endpoints return the same results after the extraction. The existing `test_service_patch.py`, `test_archive_policies.py`, `test_user_deletion.py`, and `test_validation_guardrails.py` pass unchanged. +- Success: N records updated, and N history entries attributed to the actor. +- All-or-nothing: a batch of three where record 2 breaks a rule (archived service with a category change, a sixth tag, an OS that does not match the hardware type, self-demotion, a user who owns services). Verify the response `record_id` and `position`, and that records 1 and 3 did not change. +- Delete of an active service or hardware asset in the batch fails with `409`, and nothing is deleted. +- Role checks: an editor cannot bulk delete; an editor without hardware visibility gets `403` on hardware bulk; a non-admin gets `403` on user bulk. +- Batch validation: empty ids, more than 500 ids, duplicate ids (removed), unknown ids (`404`), `changes` with `archive` (`422`), unknown `changes` keys (`422`). +- Attachments: S3 deletion runs only after commit. A failure in the batch deletes no S3 objects. + +Frontend (Vitest): + +- `DataTable` selection: header checkbox, shift-range, pruning after a filter change, no navigation on checkbox click. +- `BulkEditDialog` builds the expected `changes` payload from each field mode. +- The error state renders the API `detail.message`, `record_label`, and `position`. + +## Delivery + +Ship in three pull requests, in this order: + +1. Backend extraction of shared functions, with no behavior change. +2. Bulk endpoints and tests. +3. Frontend selection, action bar, dialogs, and documentation (`README.md` feature list, `docs/releases/next.md`). + +After PR 3 merges, and before the release is tagged, run a whole-project authorization and data-exposure review as a multi-agent workflow. Use one reviewer per dimension across all routers, and an independent verification pass for each finding: + +- Role and permission checks on every endpoint, including the new bulk endpoints. +- Financial fields that leak outside `_scrub_financial`: dashboard, admin export, history values, user directory. +- Hardware data visible without hardware visibility: user profile, history. +- Archived-record locks bypassed through side routes: attachments, assignee and owner removal, cost endpoints. +- MCP results that contain fields the documentation says are excluded. +- Audit coverage: tables missing from `AUDITED_TABLES`, and writes that do not use `get_audited_db`. +- OIDC, SCIM, and API token authentication paths. + +## Acceptance criteria + +1. An editor selects 20 active services, sets status and category, and adds a tag in one operation. History shows 20 entries under the editor's name. +2. If any of the 20 already has 5 tags, nothing changes, and the UI names that service. +3. An admin selects archived services and hardware and deletes them in one operation. A selection that contains an active record is rejected with no change. +4. An admin deactivates 10 users in one operation. A selection that contains the admin's own account is rejected with no change. +5. Viewers see no selection checkboxes. API calls from a viewer token return `403`. diff --git a/docs/superpowers/specs/2026-11-02-mcp-cost-records-design.md b/docs/superpowers/specs/2026-11-02-mcp-cost-records-design.md new file mode 100644 index 0000000..b9cf953 --- /dev/null +++ b/docs/superpowers/specs/2026-11-02-mcp-cost-records-design.md @@ -0,0 +1,143 @@ +# MCP Cost Record Tools Design + +## Goal + +Let MCP clients read, create, update, and delete cost records for services and hardware assets, with the same rules as the web UI and REST API. + +## Current state + +- `mcp/src/catalogit_mcp/server.py` has one read tool for costs: `get_service_cost_records`. It has no hardware cost read and no cost writes. +- The server instructions and `docs/integrations/mcp.md` say: "The server cannot delete or archive records." +- Service costs live at `/api/services/{service_id}/cost-records/` (`backend/app/routers/cost_records.py`): + - `GET /`, `GET /{record_id}`: financial visibility. + - `POST /`, `PUT /{record_id}`, `DELETE /{record_id}`: editor or admin, plus financial visibility. + - Writes on an archived service return `409 Archived services are read-only for cost records`. + - `CostRecordCreate`: `fiscal_year` 1900-2100 (required), `amount` >= 0 (required), `record_type` in `actual | estimated | budget` (required), optional `purchase_year` 1900-2100, optional `payment_method_id`, optional `notes`. + - `CostRecordUpdate` uses `exclude_unset`, so unsent fields stay unchanged. `fiscal_year`, `amount`, and `record_type` cannot be null. +- Hardware costs allow one record per asset (partial unique index `uq_cost_records_hardware_id`). The UI uses `GET/PUT /api/hardware/{hardware_id}/hardware-cost` (`backend/app/routers/hardware_assets.py`): + - Requires financial visibility and hardware visibility. `PUT` also requires editor or admin. + - `PUT` with `amount: 0` deletes the record. + - `PUT` replaces `purchase_year` (an omitted value becomes `null`) and forces `record_type` to `actual`. + - Archived hardware returns `409 Archived hardware is read-only for cost`. +- `GET /api/payment-methods/` is open to every signed-in user. +- Cost record history exists (`cost_records` is audited). `/api/history/cost_records/{id}` requires financial visibility, and hardware visibility for hardware cost records. + +## Scope + +### New and changed tools + +| Tool | Kind | API call | Permission | +| --- | --- | --- | --- | +| `get_service_cost_records` | read (existing) | unchanged | Financial visibility | +| `get_hardware_cost` | read | `GET /api/hardware/{id}/hardware-cost` | Financial + hardware visibility | +| `list_payment_methods` | read | `GET /api/payment-methods/` | Catalog access | +| `create_service_cost_record` | create | `POST /api/services/{id}/cost-records/` | Editor or admin + financial visibility | +| `update_service_cost_record` | update | `PUT /api/services/{id}/cost-records/{record_id}` | Editor or admin + financial visibility | +| `delete_service_cost_record` | delete | `DELETE /api/services/{id}/cost-records/{record_id}` | Editor or admin + financial visibility | +| `set_hardware_cost` | update | `PUT /api/hardware/{id}/hardware-cost` | Editor or admin + financial + hardware visibility | +| `delete_hardware_cost` | delete | `PUT /api/hardware/{id}/hardware-cost` with `amount: 0` | Editor or admin + financial + hardware visibility | +| `get_record_history` | read (existing) | add `record_type="cost_record"` mapped to `cost_records` | Financial visibility (+ hardware visibility for hardware costs) | + +No backend change is required. Every tool calls an existing endpoint, so validation, role checks, archive locks, and audit attribution stay identical to the UI. + +### Tool contracts + +`create_service_cost_record(service_id, fiscal_year, amount, record_type, purchase_year=None, payment_method_id=None)` + +- Validate UUIDs with `_uuid_arg`. +- Validate locally before the call, to give clear messages: `fiscal_year` and `purchase_year` in 1900-2100, `amount` >= 0, `record_type` in `actual | estimated | budget` (case-insensitive, sent lowercase). +- Return the cost record summary (see "Result shape"). + +`update_service_cost_record(service_id, record_id, fiscal_year=None, amount=None, record_type=None, purchase_year=None, payment_method_id=None)` + +- Send only the arguments the caller set, with `_changes()`. Same rule as other update tools: fields cannot be cleared. +- Raise `ValueError("Pass at least one field to change")` when the body is empty. +- `notes` is never sent, so `exclude_unset` keeps existing notes. + +`delete_service_cost_record(service_id, record_id)` + +- Return `{"deleted": true, "id": record_id, "service_id": service_id}` on `204`. +- The API returns `204` with no body. `_api_request` currently parses JSON on every success. Change it to return `None` for `204` responses. + +`get_hardware_cost(hardware_id)` + +- Return the summary or `{"cost_record": null}` when the asset has no cost. + +`set_hardware_cost(hardware_id, amount, purchase_year=None, fiscal_year=None)` + +- Reject `amount == 0` with a message that points to `delete_hardware_cost`. The API treats 0 as delete; the tool name must not hide a delete. +- Keep the "only passed fields change" rule. `PUT` replaces `purchase_year`, so the tool first calls `GET .../hardware-cost` and fills unset `purchase_year` and `fiscal_year` from the current record. +- Docstring states that hardware cost is always `record_type = actual` and one record per asset. + +`delete_hardware_cost(hardware_id)` + +- Read the current cost first. If there is none, return `{"deleted": false}` and do not write. +- Otherwise send `PUT` with `{"amount": 0}` and return `{"deleted": true, "hardware_id": ...}`. + +`list_payment_methods(query=None, limit=50)` + +- Same filter and limit pattern as `list_vendors`. Return `id` and `name` only. + +### Result shape + +Reuse one `_cost_record_summary(row)` for every cost tool, and switch `get_service_cost_records` to it: + +`id, service_id, hardware_id, fiscal_year, purchase_year, amount, record_type, payment_method_id, payment_method_name, recorded_at` + +`notes` and `recorded_by_*` stay out, as today. + +### Annotations + +- Reads: `_READ_ONLY`. +- Create: `_CREATES`. +- Update and set: `_UPDATES`. +- Deletes: new `_DELETES = ToolAnnotations(readOnlyHint=False, destructiveHint=True, idempotentHint=False, openWorldHint=False)`. + +### Server instructions and documentation + +- Change the `FastMCP(instructions=...)` text: the server cannot delete or archive catalog records; it can delete cost records, and only after the user confirms. +- `docs/integrations/mcp.md`: + - Add the read tools to "Available read tools". + - Add the write tools to "Available write tools", with roles. + - Replace "the MCP server cannot delete or archive records" with the precise rule. + - Add an example: "Add a 2027 budget of 12,000 for [service name]." + - State that cost-record notes cannot be read or set through MCP. +- `docs/releases/next.md`: add an entry. + +## Rules preserved from the API + +- Viewers get `403` on every write. +- A user without financial visibility gets `403` on every cost tool. +- Archived services and archived hardware get `409` on cost writes. The tool error passes the API detail through unchanged. +- An unknown payment method returns `400 Payment method not found`. +- A cost record from another service returns `404 Cost record not found`. +- Each change appears in record history under the token owner's name. + +## Out of scope + +- Setting or reading cost-record notes. +- Clearing `payment_method_id` or `purchase_year` on an update. +- Bulk cost changes, cost import, and changes to cost centers or payment methods. +- Service financial fields outside cost records (`cost_center_id`, `payment_method_id` on the service). + +## Tests + +`mcp/tests/test_cost_tools.py`, same mocking pattern as `test_write_tools.py`: + +- Create sends only set fields and normalizes `record_type`. +- Create rejects an invalid `record_type`, an out-of-range year, a negative amount, and a malformed UUID before any API call. +- Update sends a partial body; an empty update raises `ValueError`. +- Delete handles a `204` response with no body. +- `set_hardware_cost` merges the current `purchase_year` and `fiscal_year` when the caller omits them, and rejects `amount=0`. +- `delete_hardware_cost` does not write when no cost exists. +- `get_record_history(record_type="cost_record")` calls `/api/history/cost_records/{id}`. +- A `403` and a `409` from the API surface as `RuntimeError` with the API detail. +- `test_auth_header.py` still passes after the `_api_request` `204` change. + +## Acceptance criteria + +1. An editor with financial visibility can add, change, and delete a service cost record through MCP. The change appears in the service's Costs tab and its history. +2. The same editor can set and remove a hardware cost. The hardware detail page shows the change. +3. An editor without financial visibility, and every viewer, get a `403` message on cost writes. +4. Cost writes on archived records fail with the API's `409` message, and nothing changes. +5. `uv run --with pytest pytest -q` passes in `mcp/`, as in CI. diff --git a/mcp/src/catalogit_mcp/server.py b/mcp/src/catalogit_mcp/server.py index e698a0d..1b77547 100644 --- a/mcp/src/catalogit_mcp/server.py +++ b/mcp/src/catalogit_mcp/server.py @@ -34,7 +34,8 @@ "hardware, service cost records, record change history, and the audit log. The create_* " "and update_* tools change CatalogIT data: confirm the intended change with the user " "first, and look up record ids with the read tools instead of guessing them. The server " - "cannot delete or archive records. " + "cannot delete or archive catalog records; the delete_*_cost tools permanently remove " + "cost records, so run them only after the user confirms. " "Hardware and financial tools require the connected CatalogIT user's existing permissions." ), host=_MCP_HOST, @@ -145,6 +146,8 @@ async def _api_request( message += f". The token owner's role or feature permissions do not allow this {action}." raise RuntimeError(message) + if response.status_code == 204: + return None try: return response.json() except ValueError as exc: @@ -166,6 +169,9 @@ async def _api_write(method: str, path: str, body: dict[str, Any], *, ctx: Conte _UPDATES = ToolAnnotations( readOnlyHint=False, destructiveHint=True, idempotentHint=True, openWorldHint=False ) +_DELETES = ToolAnnotations( + readOnlyHint=False, destructiveHint=True, idempotentHint=False, openWorldHint=False +) _CRITICALITY_VALUES = {"Critical", "High", "Medium", "Low"} @@ -368,6 +374,57 @@ async def list_hardware_assets( return {"count": min(len(rows), limit), "truncated": len(rows) > limit, "hardware_assets": [_hardware_summary(row) for row in rows[:limit]]} +_COST_RECORD_TYPES = {"actual", "estimated", "budget"} + + +def _cost_record_summary(row: dict[str, Any]) -> dict[str, Any]: + """Cost record fields shared by every cost tool; notes and recorder stay out.""" + return { + "id": row.get("id"), + "service_id": row.get("service_id"), + "hardware_id": row.get("hardware_id"), + "fiscal_year": row.get("fiscal_year"), + "purchase_year": row.get("purchase_year"), + "amount": row.get("amount"), + "record_type": row.get("record_type"), + "payment_method_id": row.get("payment_method_id"), + "payment_method_name": row.get("payment_method_name"), + "recorded_at": row.get("recorded_at"), + } + + +def _year_arg(name: str, value: int | None) -> int | None: + if value is not None and not 1900 <= value <= 2100: + raise ValueError(f"{name} must be between 1900 and 2100") + return value + + +def _amount_arg(value: float | None) -> float | None: + if value is not None and value < 0: + raise ValueError("amount cannot be negative") + return value + + +def _record_type_arg(value: str | None) -> str | None: + if value is None: + return None + cleaned = value.strip().lower() + if cleaned not in _COST_RECORD_TYPES: + raise ValueError(f"record_type must be one of: {', '.join(sorted(_COST_RECORD_TYPES))}") + return cleaned + + +def _service_cost_path(service_id: str, record_id: str | None = None) -> str: + path = f"/api/services/{_uuid_arg('service_id', service_id)}/cost-records/" + if record_id is not None: + path += _uuid_arg("record_id", record_id) + return path + + +def _hardware_cost_path(hardware_id: str) -> str: + return f"/api/hardware/{_uuid_arg('hardware_id', hardware_id)}/hardware-cost" + + @mcp.tool(annotations=_READ_ONLY) async def get_service_cost_records( ctx: Context, @@ -377,27 +434,168 @@ async def get_service_cost_records( """List a service's financial cost records. Requires financial visibility.""" limit = _bounded_limit(limit) rows = await _api_get(f"/api/services/{quote(service_id, safe='')}/cost-records/", ctx=ctx) - summaries = [ - { - "id": row.get("id"), - "service_id": row.get("service_id"), - "fiscal_year": row.get("fiscal_year"), - "purchase_year": row.get("purchase_year"), - "amount": row.get("amount"), - "record_type": row.get("record_type"), - "payment_method_name": row.get("payment_method_name"), - "recorded_at": row.get("recorded_at"), - } - for row in rows[:limit] - ] + summaries = [_cost_record_summary(row) for row in rows[:limit]] return {"count": min(len(rows), limit), "truncated": len(rows) > limit, "cost_records": summaries} +@mcp.tool(annotations=_READ_ONLY) +async def get_hardware_cost(ctx: Context, hardware_id: str) -> dict[str, Any]: + """Get a hardware asset's purchase cost. Requires financial and hardware visibility. + + Each hardware asset has at most one cost record. Returns cost_record as null when none is set. + """ + row = await _api_get(_hardware_cost_path(hardware_id), ctx=ctx) + return {"cost_record": _cost_record_summary(row) if row else None} + + +@mcp.tool(annotations=_READ_ONLY) +async def list_payment_methods(ctx: Context, query: str | None = None, limit: int = 50) -> dict[str, Any]: + """List or search payment methods by name, for use with the cost record tools.""" + limit = _bounded_limit(limit) + rows = await _api_get("/api/payment-methods/", ctx=ctx) + needle = query.casefold().strip() if query else "" + if needle: + rows = [row for row in rows if needle in str(row.get("name") or "").casefold()] + return { + "count": min(len(rows), limit), + "truncated": len(rows) > limit, + "payment_methods": [{"id": row.get("id"), "name": row.get("name")} for row in rows[:limit]], + } + + +@mcp.tool(annotations=_CREATES) +async def create_service_cost_record( + ctx: Context, + service_id: str, + fiscal_year: int, + amount: float, + record_type: str, + purchase_year: int | None = None, + payment_method_id: str | None = None, +) -> dict[str, Any]: + """Add a cost record to a service. This changes CatalogIT data. + + Requires an editor or admin account with financial visibility. record_type is actual, + estimated, or budget. Years are between 1900 and 2100; amount cannot be negative. Pass a + payment_method_id from list_payment_methods. Archived services are read-only for costs. + Cost-record notes can only be set in the CatalogIT UI. Returns the new cost record. + """ + body = { + "fiscal_year": _year_arg("fiscal_year", fiscal_year), + "amount": _amount_arg(amount), + "record_type": _record_type_arg(record_type), + } | _changes( + purchase_year=_year_arg("purchase_year", purchase_year), + payment_method_id=( + _uuid_arg("payment_method_id", payment_method_id) if payment_method_id else None + ), + ) + row = await _api_write("POST", _service_cost_path(service_id), body, ctx=ctx) + return _cost_record_summary(row) + + +@mcp.tool(annotations=_UPDATES) +async def update_service_cost_record( + ctx: Context, + service_id: str, + record_id: str, + fiscal_year: int | None = None, + amount: float | None = None, + record_type: str | None = None, + purchase_year: int | None = None, + payment_method_id: str | None = None, +) -> dict[str, Any]: + """Change fields on one service cost record. This changes CatalogIT data. + + Requires an editor or admin account with financial visibility. Only the fields you pass + are changed; fields cannot be cleared through this tool, and notes are kept. Archived + services are read-only for costs. Returns the updated cost record. + """ + path = _service_cost_path(service_id, record_id) + body = _changes( + fiscal_year=_year_arg("fiscal_year", fiscal_year), + amount=_amount_arg(amount), + record_type=_record_type_arg(record_type), + purchase_year=_year_arg("purchase_year", purchase_year), + payment_method_id=( + _uuid_arg("payment_method_id", payment_method_id) if payment_method_id else None + ), + ) + if not body: + raise ValueError("Pass at least one field to change") + row = await _api_write("PUT", path, body, ctx=ctx) + return _cost_record_summary(row) + + +@mcp.tool(annotations=_DELETES) +async def delete_service_cost_record(ctx: Context, service_id: str, record_id: str) -> dict[str, Any]: + """Permanently delete one service cost record. This cannot be undone. + + Confirm with the user before running it. Requires an editor or admin account with + financial visibility. Archived services are read-only for costs. + """ + path = _service_cost_path(service_id, record_id) + await _api_request("DELETE", path, ctx=ctx) + return { + "deleted": True, + "id": _uuid_arg("record_id", record_id), + "service_id": _uuid_arg("service_id", service_id), + } + + +@mcp.tool(annotations=_UPDATES) +async def set_hardware_cost( + ctx: Context, + hardware_id: str, + amount: float, + purchase_year: int | None = None, + fiscal_year: int | None = None, +) -> dict[str, Any]: + """Set the purchase cost of a hardware asset. This changes CatalogIT data. + + Requires an editor or admin account with financial and hardware visibility. Each asset has + one cost record of type actual; this creates it or replaces its amount. purchase_year and + fiscal_year keep their current values when omitted; a new record's fiscal year defaults to + the purchase year, then to the current year. amount must be greater than 0; use + delete_hardware_cost to remove a cost. Archived hardware is read-only for costs. + """ + if amount <= 0: + raise ValueError("amount must be greater than 0; use delete_hardware_cost to remove a cost") + path = _hardware_cost_path(hardware_id) + _year_arg("purchase_year", purchase_year) + _year_arg("fiscal_year", fiscal_year) + if purchase_year is None or fiscal_year is None: + current = await _api_get(path, ctx=ctx) or {} + if purchase_year is None: + purchase_year = current.get("purchase_year") + if fiscal_year is None: + fiscal_year = current.get("fiscal_year") + body = {"amount": amount} | _changes(purchase_year=purchase_year, fiscal_year=fiscal_year) + row = await _api_write("PUT", path, body, ctx=ctx) + return _cost_record_summary(row) + + +@mcp.tool(annotations=_DELETES) +async def delete_hardware_cost(ctx: Context, hardware_id: str) -> dict[str, Any]: + """Permanently remove a hardware asset's purchase cost. This cannot be undone. + + Confirm with the user before running it. Requires an editor or admin account with + financial and hardware visibility. Archived hardware is read-only for costs. + """ + path = _hardware_cost_path(hardware_id) + hardware_id = _uuid_arg("hardware_id", hardware_id) + if not await _api_get(path, ctx=ctx): + return {"deleted": False, "hardware_id": hardware_id} + await _api_write("PUT", path, {"amount": 0}, ctx=ctx) + return {"deleted": True, "hardware_id": hardware_id} + + _HISTORY_TABLES = { "service": "services", "hardware": "hardware_assets", "vendor": "vendors", "tag": "tags", + "cost_record": "cost_records", } # History values mirror whole database rows, so drop the same private fields the # summaries above leave out, plus financial references and storage locations. @@ -448,10 +646,12 @@ async def get_record_history( page: int = 1, per_page: int = 50, ) -> dict[str, Any]: - """Get the change history of one service, hardware asset, vendor, or tag, newest first. + """Get the change history of one service, hardware asset, vendor, tag, or cost record, newest first. - record_type is one of: service, hardware, vendor, tag. Service and hardware history include - their attachment changes. Hardware history requires hardware visibility. Notes, contact + record_type is one of: service, hardware, vendor, tag, cost_record. Service and hardware + history include their attachment changes. Hardware history requires hardware visibility; + cost record history requires financial visibility (and hardware visibility for hardware + costs). Notes, contact details, assignees, cellular identifiers, and financial references are removed from values. """ table = _HISTORY_TABLES.get(record_type) diff --git a/mcp/tests/test_cost_tools.py b/mcp/tests/test_cost_tools.py new file mode 100644 index 0000000..45189aa --- /dev/null +++ b/mcp/tests/test_cost_tools.py @@ -0,0 +1,224 @@ +"""Tests for the service and hardware cost record tools.""" + +from __future__ import annotations + +import asyncio +import unittest +from unittest.mock import AsyncMock, MagicMock, patch + +import httpx + +from catalogit_mcp import server + +_SERVICE_ID = "6f1c2a7e-3b4d-4e5f-8a9b-0c1d2e3f4a5b" +_RECORD_ID = "0b8f8e7a-1c2d-4e3f-9a8b-7c6d5e4f3a2b" +_HARDWARE_ID = "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d" +_PAYMENT_ID = "11111111-2222-4333-8444-555555555555" + +_RECORD = { + "id": _RECORD_ID, + "service_id": _SERVICE_ID, + "hardware_id": None, + "payment_method_id": None, + "payment_method_name": None, + "fiscal_year": 2027, + "purchase_year": None, + "amount": 1200.0, + "record_type": "budget", + "notes": "private", + "recorded_at": "2026-11-02T10:00:00Z", + "recorded_by_id": "u1", + "recorded_by_name": "Ada Lovelace", +} + + +class ServiceCostToolsTest(unittest.IsolatedAsyncioTestCase): + async def test_create_sends_typed_fields_and_hides_notes(self) -> None: + api_write = AsyncMock(return_value=_RECORD) + with patch.object(server, "_api_write", api_write): + result = await server.create_service_cost_record( + None, _SERVICE_ID, 2027, 1200, " Budget ", payment_method_id=_PAYMENT_ID + ) + api_write.assert_awaited_once_with( + "POST", + f"/api/services/{_SERVICE_ID}/cost-records/", + { + "fiscal_year": 2027, + "amount": 1200, + "record_type": "budget", + "payment_method_id": _PAYMENT_ID, + }, + ctx=None, + ) + self.assertNotIn("notes", result) + self.assertNotIn("recorded_by_name", result) + self.assertEqual(result["record_type"], "budget") + + async def test_create_validates_locally(self) -> None: + api_write = AsyncMock() + cases = ( + (_SERVICE_ID, 2027, 100, "forecast", {}), + (_SERVICE_ID, 1800, 100, "actual", {}), + (_SERVICE_ID, 2027, -1, "actual", {}), + (_SERVICE_ID, 2027, 100, "actual", {"purchase_year": 2200}), + (_SERVICE_ID, 2027, 100, "actual", {"payment_method_id": "card"}), + ("../users", 2027, 100, "actual", {}), + ) + with patch.object(server, "_api_write", api_write): + for service_id, year, amount, record_type, kwargs in cases: + with self.subTest(year=year, amount=amount, record_type=record_type, **kwargs): + with self.assertRaises(ValueError): + await server.create_service_cost_record( + None, service_id, year, amount, record_type, **kwargs + ) + api_write.assert_not_awaited() + + async def test_update_sends_only_given_fields(self) -> None: + api_write = AsyncMock(return_value=_RECORD) + with patch.object(server, "_api_write", api_write): + await server.update_service_cost_record(None, _SERVICE_ID, _RECORD_ID, amount=900) + api_write.assert_awaited_once_with( + "PUT", + f"/api/services/{_SERVICE_ID}/cost-records/{_RECORD_ID}", + {"amount": 900}, + ctx=None, + ) + + async def test_update_needs_a_change(self) -> None: + with self.assertRaises(ValueError): + await server.update_service_cost_record(None, _SERVICE_ID, _RECORD_ID) + + async def test_delete_calls_delete_endpoint(self) -> None: + api_request = AsyncMock(return_value=None) + with patch.object(server, "_api_request", api_request): + result = await server.delete_service_cost_record(None, _SERVICE_ID, _RECORD_ID) + api_request.assert_awaited_once_with( + "DELETE", f"/api/services/{_SERVICE_ID}/cost-records/{_RECORD_ID}", ctx=None + ) + self.assertEqual(result, {"deleted": True, "id": _RECORD_ID, "service_id": _SERVICE_ID}) + + async def test_list_uses_shared_summary(self) -> None: + api_get = AsyncMock(return_value=[_RECORD]) + with patch.object(server, "_api_get", api_get): + result = await server.get_service_cost_records(None, _SERVICE_ID) + self.assertEqual(result["cost_records"][0]["payment_method_id"], None) + self.assertNotIn("notes", result["cost_records"][0]) + + +class HardwareCostToolsTest(unittest.IsolatedAsyncioTestCase): + _PATH = f"/api/hardware/{_HARDWARE_ID}/hardware-cost" + _CURRENT = _RECORD | {"service_id": None, "hardware_id": _HARDWARE_ID, "purchase_year": 2024, "fiscal_year": 2024} + + async def test_get_returns_null_without_cost(self) -> None: + with patch.object(server, "_api_get", AsyncMock(return_value=None)): + result = await server.get_hardware_cost(None, _HARDWARE_ID) + self.assertEqual(result, {"cost_record": None}) + + async def test_set_keeps_current_years_when_omitted(self) -> None: + api_get = AsyncMock(return_value=self._CURRENT) + api_write = AsyncMock(return_value=self._CURRENT) + with patch.object(server, "_api_get", api_get), patch.object(server, "_api_write", api_write): + await server.set_hardware_cost(None, _HARDWARE_ID, 1500) + api_get.assert_awaited_once_with(self._PATH, ctx=None) + api_write.assert_awaited_once_with( + "PUT", self._PATH, {"amount": 1500, "purchase_year": 2024, "fiscal_year": 2024}, ctx=None + ) + + async def test_set_without_existing_cost_lets_api_default_years(self) -> None: + api_get = AsyncMock(return_value=None) + api_write = AsyncMock(return_value=self._CURRENT) + with patch.object(server, "_api_get", api_get), patch.object(server, "_api_write", api_write): + await server.set_hardware_cost(None, _HARDWARE_ID, 1500) + api_write.assert_awaited_once_with("PUT", self._PATH, {"amount": 1500}, ctx=None) + + async def test_set_with_both_years_skips_read(self) -> None: + api_get = AsyncMock() + api_write = AsyncMock(return_value=self._CURRENT) + with patch.object(server, "_api_get", api_get), patch.object(server, "_api_write", api_write): + await server.set_hardware_cost(None, _HARDWARE_ID, 1500, purchase_year=2025, fiscal_year=2026) + api_get.assert_not_awaited() + api_write.assert_awaited_once_with( + "PUT", self._PATH, {"amount": 1500, "purchase_year": 2025, "fiscal_year": 2026}, ctx=None + ) + + async def test_set_rejects_zero_and_bad_years(self) -> None: + for kwargs in ({"amount": 0}, {"amount": -5}, {"amount": 10, "purchase_year": 1700}): + with self.subTest(**kwargs), self.assertRaises(ValueError): + await server.set_hardware_cost(None, _HARDWARE_ID, **kwargs) + + async def test_delete_without_cost_does_not_write(self) -> None: + api_write = AsyncMock() + with patch.object(server, "_api_get", AsyncMock(return_value=None)), patch.object(server, "_api_write", api_write): + result = await server.delete_hardware_cost(None, _HARDWARE_ID) + api_write.assert_not_awaited() + self.assertEqual(result, {"deleted": False, "hardware_id": _HARDWARE_ID}) + + async def test_delete_sends_zero_amount(self) -> None: + api_write = AsyncMock(return_value=None) + with patch.object(server, "_api_get", AsyncMock(return_value=self._CURRENT)), patch.object(server, "_api_write", api_write): + result = await server.delete_hardware_cost(None, _HARDWARE_ID) + api_write.assert_awaited_once_with("PUT", self._PATH, {"amount": 0}, ctx=None) + self.assertEqual(result, {"deleted": True, "hardware_id": _HARDWARE_ID}) + + +class PaymentMethodsAndHistoryTest(unittest.IsolatedAsyncioTestCase): + async def test_list_payment_methods_filters_by_name(self) -> None: + rows = [{"id": "p1", "name": "Company card", "notes": "x"}, {"id": "p2", "name": "Invoice"}] + with patch.object(server, "_api_get", AsyncMock(return_value=rows)): + result = await server.list_payment_methods(None, query="card") + self.assertEqual(result["payment_methods"], [{"id": "p1", "name": "Company card"}]) + + async def test_cost_record_history_uses_cost_records_table(self) -> None: + payload = {"items": [], "page": 1, "total_pages": 0, "total_count": 0} + api_get = AsyncMock(return_value=payload) + with patch.object(server, "_api_get", api_get): + await server.get_record_history(None, "cost_record", _RECORD_ID) + self.assertEqual(api_get.await_args.args[0], f"/api/history/cost_records/{_RECORD_ID}") + + +class ApiResponseTest(unittest.IsolatedAsyncioTestCase): + async def _request(self, response: httpx.Response): + client = MagicMock() + client.request = AsyncMock(return_value=response) + client.__aenter__ = AsyncMock(return_value=client) + client.__aexit__ = AsyncMock(return_value=None) + with ( + patch.object(server, "_configuration", return_value="https://catalogit.test"), + patch.object(server, "_api_token", return_value="token"), + patch.object(server.httpx, "AsyncClient", return_value=client), + ): + return await server._api_request("DELETE", "/api/x", ctx=None) + + async def test_no_content_returns_none(self) -> None: + self.assertIsNone(await self._request(httpx.Response(204))) + + async def test_archived_conflict_is_passed_through(self) -> None: + response = httpx.Response(409, json={"detail": "Archived services are read-only for cost records"}) + with self.assertRaises(RuntimeError) as ctx: + await self._request(response) + self.assertIn("HTTP 409: Archived services are read-only for cost records", str(ctx.exception)) + + +class CostToolAnnotationsTest(unittest.TestCase): + def test_cost_tools_are_annotated(self) -> None: + tools = {tool.name: tool for tool in asyncio.run(server.mcp.list_tools())} + for name in ("get_hardware_cost", "list_payment_methods", "get_service_cost_records"): + with self.subTest(tool=name): + self.assertTrue(tools[name].annotations.readOnlyHint) + for name in ( + "create_service_cost_record", + "update_service_cost_record", + "set_hardware_cost", + "delete_service_cost_record", + "delete_hardware_cost", + ): + with self.subTest(tool=name): + self.assertFalse(tools[name].annotations.readOnlyHint) + for name in ("delete_service_cost_record", "delete_hardware_cost"): + with self.subTest(tool=name): + self.assertTrue(tools[name].annotations.destructiveHint) + self.assertFalse(tools[name].annotations.idempotentHint) + + +if __name__ == "__main__": + unittest.main()