diff --git a/jellyseerr_mcp/clients/arr.py b/jellyseerr_mcp/clients/arr.py index 547ec52..d74e2da 100644 --- a/jellyseerr_mcp/clients/arr.py +++ b/jellyseerr_mcp/clients/arr.py @@ -19,6 +19,12 @@ request (including preflight reads); additions never auto-search; grabs revalidate the inspected release (guid + indexerId) and never force rejected ones; episode selections are owned by the stated series and bounded to 100. + +Queue removal is deliberately narrow. ``DELETE /api/v3/queue/{id}`` defaults to +``removeFromClient=false`` and ``blocklist=false``, so the default call only +clears the *arr's own queue record and leaves the downloader's files on disk. +The client never overrides those defaults; the caller has to ask for either. +Blocklisting additionally POSTs the failed history entry to ``/api/v3/history/failed``. """ from __future__ import annotations @@ -159,6 +165,36 @@ def _command(self, command_id: object) -> dict: command_id = positive_id(command_id, 'command_id') return select(self.request_json('GET', f'api/v3/command/{command_id}') or {}, COMMAND_FIELDS) + def _history_failed(self, item_id: int, history_id: int | None) -> dict | None: + """Blocklist one entry, preferring the exact history record it came from. + + Without a history id the *arr marks the newest failure whose download id + matches, which can be ambiguous if the same release failed more than once. + The returned body is untrusted upstream data and is only checked, not echoed. + """ + payload: dict = {'id': item_id} + if history_id is not None: + payload['historyId'] = positive_id(history_id, 'history_id') + result = self.request_json('POST', 'api/v3/history/failed', json=payload, mutation=True) + return result if isinstance(result, dict) else None + + def _raw_queue_record(self, item_id: object) -> dict: + """Fetch the queue page holding one item to confirm it exists and read its history id. + + The *arr queue is a flat list addressed by download-client id, not an + addressable resource, so ``GET /api/v3/queue/{id}`` does not exist; the + page carrying the record is the only way to prove the id is real. + """ + wanted = positive_id(item_id, 'item_id') + response = self.request_json('GET', 'api/v3/queue', params={ + 'page': 1, 'pageSize': 100, 'includeUnknownMovieItems': 'true', + 'includeUnknownSeriesItems': 'true'}) or {} + for record in response.get('records') or []: + if record.get('id') == wanted: + return record + raise ValueError(f'queue item {wanted} not found in the first 100 records; ' + 'it may have already imported or been removed') + @staticmethod def _release_matches(releases: list, guid: str, indexer_id: int) -> dict | None: for release in releases: @@ -334,6 +370,31 @@ def grab(self, movie_id: int | str, guid: str, indexer_id: int | str) -> dict: self.request_json('POST', 'api/v3/release', json=payload, mutation=True) return {'grabbed': True, 'guid': guid, 'indexerId': indexer_id} + def dequeue(self, item_id: int | str, remove_from_client: bool = False, + blocklist: bool = False) -> dict: + """Clear ONE queue record; by default the downloader's files stay on disk. + + `remove_from_client` additionally tells the downloader to delete its copy, + and `blocklist` marks the release failed so it is not grabbed again. Both + default to False and are never inferred from the item's state, because each + destroys data or changes future searches. An item stuck at import (for + example a downgrade the profile refuses) only needs the default call. + """ + self.require_write() + record = self._raw_queue_record(item_id) + params: dict = {} + if remove_from_client: + params['removeFromClient'] = 'true' + if blocklist: + params['blocklist'] = 'true' + self.request_json('DELETE', f'api/v3/queue/{record["id"]}', + params=params or None, mutation=True) + if blocklist: + self._history_failed(record['id'], record.get('historyId')) + return {'removed': True, 'item_id': record['id'], + 'remove_from_client': bool(remove_from_client), + 'blocklisted': bool(blocklist), 'history_id': record.get('historyId')} + class SonarrClient(ArrClientBase): """Sonarr v3 API client (/api/v3, X-Api-Key).""" @@ -677,3 +738,28 @@ def grab(self, series_id: int | str, guid: str, indexer_id: int | str, payload['episodeId'] = episode_id self.request_json('POST', 'api/v3/release', json=payload, mutation=True) return {'grabbed': True, 'guid': guid, 'indexerId': indexer_id} + + def dequeue(self, item_id: int | str, remove_from_client: bool = False, + blocklist: bool = False) -> dict: + """Clear ONE queue record; by default the downloader's files stay on disk. + + `remove_from_client` additionally tells the downloader to delete its copy, + and `blocklist` marks the release failed so it is not grabbed again. Both + default to False and are never inferred from the item's state, because each + destroys data or changes future searches. An episode stuck at import after + an upgrade (a downgrade the profile refuses) only needs the default call. + """ + self.require_write() + record = self._raw_queue_record(item_id) + params: dict = {} + if remove_from_client: + params['removeFromClient'] = 'true' + if blocklist: + params['blocklist'] = 'true' + self.request_json('DELETE', f'api/v3/queue/{record["id"]}', + params=params or None, mutation=True) + if blocklist: + self._history_failed(record['id'], record.get('historyId')) + return {'removed': True, 'item_id': record['id'], + 'remove_from_client': bool(remove_from_client), + 'blocklisted': bool(blocklist), 'history_id': record.get('historyId')} diff --git a/jellyseerr_mcp/server.py b/jellyseerr_mcp/server.py index 83708e6..253710e 100644 --- a/jellyseerr_mcp/server.py +++ b/jellyseerr_mcp/server.py @@ -145,6 +145,7 @@ def get_services() -> dict: "set_monitoring": ("monitor", "Change only explicitly selected series/seasons/episodes; preserve unrelated monitoring.", True), "search_episodes": ("search", "Search at most 100 explicit episodes belonging to one series; returns command ID.", True), "grab_release": ("grab", "Grab a currently accepted release for a series episode/season; never force rejected releases.", True), + "remove_queue_item": ("dequeue", "Clear ONE queue record by native queue item ID. Defaults delete nothing: the downloader keeps its files and the release is not blocklisted. Ask for either explicitly.", True), } for suffix, (method, description, write) in mappings.items(): register(name + "_" + suffix, getattr(client, method), description, write) diff --git a/tests/test_arr.py b/tests/test_arr.py index 33d9cd4..bf2cfd5 100644 --- a/tests/test_arr.py +++ b/tests/test_arr.py @@ -900,3 +900,92 @@ def test_sonarr_next_up_accepts_an_iso_timestamp_cutoff(): assert client.next_up(5, since='2026-10-05T01:00:00Z')['total'] == 1 # inclusive assert client.next_up(5, since='2026-10-05T02:00:00Z')['total'] == 0 client.close() + + +# ------------------------------------------------------- queue removal + +def queue_record(id=536432398, history_id=None, **extra): + data = {'id': id, 'title': 'Example.S01E01.1080p.WEB.H264-GRP', 'status': 'completed', + 'trackedDownloadStatus': 'warning', 'trackedDownloadState': 'importPending', + 'size': 1911975621, 'sizeleft': 0, 'protocol': 'usenet', + 'downloadClient': 'NZBGet', 'downloadId': 'abc123', 'seriesId': 5, + 'episodeId': 101, 'statusMessages': []} + if history_id is not None: + data['historyId'] = history_id + data.update(extra) + return data + + +def test_dequeue_defaults_delete_nothing_beyond_the_queue_record(): + """The whole point of the default: clear the *arr's queue row, keep the + downloader's file and do not blocklist. Neither flag may be inferred.""" + record = queue_record() + client, api = make_client(SonarrClient, SONARR, [ + (r'/api/v3/queue/\d+', 'DELETE', lambda req: (204, None)), + (r'/api/v3/queue', 'GET', lambda req: (200, paged([record])))]) + result = client.dequeue(record['id']) + assert api.path(1) == f"/api/v3/queue/{record['id']}" + assert api.calls[1].method == 'DELETE' + assert api.params(1) == {} # no removeFromClient, no blocklist + assert result == {'removed': True, 'item_id': record['id'], + 'remove_from_client': False, 'blocklisted': False, 'history_id': None} + # no history call unless blocklisting was asked for + assert not any('history' in c.url.path for c in api.calls) + client.close() + + +def test_dequeue_passes_explicit_flags_as_booleans(): + record = queue_record(history_id=99) + client, api = make_client(SonarrClient, SONARR, [ + (r'/api/v3/queue/\d+', 'DELETE', lambda req: (204, None)), + (r'/api/v3/history/failed', 'POST', lambda req: (200, {'id': 7})), + (r'/api/v3/queue', 'GET', lambda req: (200, paged([record])))]) + result = client.dequeue(record['id'], remove_from_client=True, blocklist=True) + assert api.params(1) == {'removeFromClient': 'true', 'blocklist': 'true'} + assert result['remove_from_client'] is True and result['blocklisted'] is True + # blocklisting pins the exact history record, not "newest matching download" + assert api.path(2) == '/api/v3/history/failed' + assert api.bodies()[2] == {'id': record['id'], 'historyId': 99} + client.close() + + +def test_dequeue_refuses_unknown_item_without_deleting(): + client, api = make_client(SonarrClient, SONARR, [ + (r'/api/v3/queue/\d+', 'DELETE', lambda req: (204, None)), + (r'/api/v3/queue', 'GET', lambda req: (200, paged([queue_record(id=1)])))]) + with pytest.raises(ValueError, match='not found'): + client.dequeue(536432398) + assert not any(c.method == 'DELETE' for c in api.calls) + client.close() + + +def test_dequeue_validates_the_item_id_before_any_network(): + client, api = make_client(SonarrClient, SONARR, [ + (r'/api/v3/queue/\d+', 'DELETE', lambda req: (204, None)), + (r'/api/v3/queue', 'GET', lambda req: (200, paged([])))]) + for bad in (None, '', 0, -5, 'abc', True): + with pytest.raises(ValueError, match='item_id'): + client.dequeue(bad) + assert api.calls == [] # never reached the network + client.close() + + +def test_dequeue_permission_checked_before_any_network(): + client, api = make_client(SonarrClient, SONARR, [ + (r'/api/v3/queue/\d+', 'DELETE', lambda req: (204, None)), + (r'/api/v3/queue', 'GET', lambda req: (200, paged([queue_record()])))], + allow_writes=False) + with pytest.raises(PermissionError, match='writes are disabled'): + client.dequeue(queue_record()['id']) + assert api.calls == [] # the write gate precedes the existence read too + client.close() + + +def test_radarr_dequeue_uses_the_same_narrow_contract(): + record = queue_record(id=777, movieId=1) + client, api = make_client(RadarrClient, RADARR, [ + (r'/api/v3/queue/\d+', 'DELETE', lambda req: (204, None)), + (r'/api/v3/queue', 'GET', lambda req: (200, paged([record])))]) + result = client.dequeue(777) + assert api.params(1) == {} and result['remove_from_client'] is False + client.close() diff --git a/tests/test_server.py b/tests/test_server.py index af935b9..c262ba4 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -80,3 +80,22 @@ def handler(request): assert 'kodi' not in names and 'sonarr_add_movie' not in names sonarr.close() radarr.close() + + +@pytest.mark.asyncio +async def test_queue_removal_tool_registers_for_sonarr_only(): + """Registration is a property of the code, not of the environment: assert it + with injected clients so a machine with no .env still checks it.""" + def handler(request): + return httpx.Response(200, json={'totalRecords': 0, 'records': []}) + + sonarr = SonarrClient(ServiceConfig('sonarr', 'https://sonarr.test', allow_writes=True), + httpx.MockTransport(handler)) + server = build_server(AppConfig(), {'sonarr': sonarr}) + names = {tool.name for tool in await server.list_tools()} + assert 'sonarr_remove_queue_item' in names + assert 'radarr_remove_queue_item' not in names # not configured, never registered + tool = next(t for t in await server.list_tools() if t.name == 'sonarr_remove_queue_item') + # It mutates state, so it must not be advertised as read-only. + assert tool.annotations.readOnlyHint is False + sonarr.close()