From 6a41f95bb2c42afcced8130f7630982ec2022cad Mon Sep 17 00:00:00 2001 From: Amit Serper Date: Sun, 11 Oct 2026 21:42:16 -0400 Subject: [PATCH 1/2] feat(seerr): add request history reads with requester attribution Answering "who requested this?" previously required an out-of-band API call. The Seerr surface only had get_request, which needs the request ID already known, and raw_request is restricted to `GET status`. Add two read-only tools: - list_requests: paged request log with requested_by / modified_by on every entry, narrowable by requester user id and media type. - get_media_requests: every request for one title by TMDB ID, oldest first, so the first entry is the original requester. Neither endpoint is sufficient alone. /api/v1/media omits `requests`, and request?mediaId= is silently ignored (it returns the whole log), so a title-scoped read can only come from the title's own detail endpoint. Upstream behaviours that shape the implementation: - An unknown requestedBy returns 200 with an empty page rather than an error, so the response cannot confirm the filter was honored. Filters, sorts, media types and IDs are validated locally instead. - An unknown TMDB ID answers 500, not 404. That is "never requested", so it is reported as in_seerr=false rather than raised. - Page totals come from Seerr's pageInfo, which is the only trustworthy count when a requester filter legitimately matches nothing. The projection keeps requested_by and modified_by separate (the requester and the approving admin routinely differ) and drops credential-shaped keys from upstream records. --- IMPLEMENTATION_PLAN.md | 2 + README.md | 20 ++++- jellyseerr_mcp/client.py | 145 +++++++++++++++++++++++++++++++- jellyseerr_mcp/server.py | 7 ++ tests/integration/test_stdio.py | 6 +- tests/test_client.py | 105 +++++++++++++++++++++++ tests/test_server.py | 29 ++++++- 7 files changed, 307 insertions(+), 7 deletions(-) diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index d91c778..9965b9a 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -34,6 +34,8 @@ Writes require both `MCP_READ_ONLY=false` and the target service's `ALLOW_WRITES Use `/api/v1` with `X-Api-Key`. Preserve `%20` search encoding, existing tool names and the default TV season `[1]`. Service defaults come from Seerr; language-profile IDs aren't guessed. A direct Sonarr/Radarr addition is separate from a Seerr request and its approval policy. +Request history reads two endpoints because neither alone is sufficient. `GET /api/v1/request` is the paged log (`take`, `skip`, `filter`, `sort`, `requestedBy`, `mediaType`) and carries `requestedBy` on every record; `GET /api/v1/{tv|movie}/{tmdbId}` carries `mediaInfo.requests` for one title. `GET /api/v1/media` omits `requests` entirely, and `request` silently ignores a `mediaId` filter, so a title-scoped read must not be built on either. Two upstream behaviours are load-bearing: an unknown `requestedBy` returns 200 with an empty page instead of an error, so the response cannot confirm the filter was honored and the values are validated locally; and an unknown TMDB id answers 500 (not 404), which is "never requested", not a fault. + ### Radarr and Sonarr Use `/api/v3` with `X-Api-Key`. External catalog IDs and native library IDs must stay distinct. Additions check existing library membership and validate profile/root choices before posting. They don't search automatically. diff --git a/README.md b/README.md index 47ae4a1..9b58de4 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ Hermes and OpenClaw configuration follows their documentation; end-to-end sessio | "Stop monitoring season 1 of Severance. Leave the other seasons alone." | Sonarr season monitoring | | "Why hasn't Arrival imported? Check Radarr's queue and history." | Radarr queue, history and import diagnostics | | "Show the SABnzbd queue, then pause the download I choose." | Downloader queue and per-job pause | +| "Who requested Mad Men, and when?" | Seerr request history | Calendars, lookups and status checks work in read-only mode. Requests, monitoring changes, searches that trigger downloads, and download controls need [write permission](#allowing-changes). `get_services` shows which services are connected and whether writes are enabled. @@ -156,7 +157,20 @@ You can also add media directly with `radarr_add_movie` or `sonarr_add_series`. IDs depend on the operation: Seerr requests and Radarr additions use TMDB IDs; Sonarr additions use TVDB IDs. Once a title is in your library, monitoring and search tools use its Sonarr or Radarr ID. Episode tools use Sonarr episode IDs and check that they belong to the selected series. -Sonarr monitoring changes only the selected seasons or episodes. Season and episode changes require separate calls. +Sonarr monitoring changes only the selected seasons or episodes. Season and episode changes require separate calls. All of this works in read-only mode except `request_media` and the direct additions. + +### Seerr request history + +"Who asked for this?" is a request-log question, not a library one: + +- `list_requests` pages the request log newest-first (`page_number`, `limit` up to 100) and carries the requester on every entry. `requested_by` is who asked; `modified_by` is whoever last acted, usually the approving admin, and the two routinely differ. Narrow with `requested_by` (Seerr user id) and `media_type`, or `filter`. +- `get_media_requests` answers it for one title by TMDB id, oldest first, so the first entry is the original requester. Use it instead of scanning the log when the title is known. + +Both are read-only and need no writes. Two upstream quirks shape them: `/api/v1/media` deliberately omits `requests`, and `request?mediaId=` is silently ignored (it returns the whole log), so per-title history only comes from the title's own detail endpoint. Seerr also answers 500, not 404, for a TMDB id it has never seen, which these tools report as `in_seerr: false` rather than an error. Filters, sorts and media types are validated locally because Seerr rejects a bad value with 400 but silently ignores an unknown `requestedBy`. + +Paging is reported as `native` from Seerr's `pageInfo`; a title the requester list does not match returns an empty page rather than an error. + +### NZBHydra downloads ### Upcoming episodes and movie releases @@ -194,7 +208,7 @@ If NZB retrieval redirects to an indexer, add that indexer's origin to `NZBHYDRA | Group | Tools | | --- | --- | | Common | `ping`, `get_services` | -| Seerr | `search_media`, `request_media`, `get_request` | +| Seerr | `search_media`, `request_media`, `get_request`, `list_requests`, `get_media_requests` | | Radarr | `radarr_find_movies`, `radarr_get_movie`, `radarr_get_options`, `radarr_get_queue`, `radarr_get_history`, `radarr_get_health`, `radarr_get_calendar`, `radarr_get_releases`, `radarr_get_command`, `radarr_add_movie`, `radarr_set_monitored`, `radarr_search_movie`, `radarr_grab_release` | | Sonarr | `sonarr_find_series`, `sonarr_get_series`, `sonarr_get_episodes`, `sonarr_get_next_up`, `sonarr_get_missing`, `sonarr_get_calendar`, `sonarr_get_options`, `sonarr_get_queue`, `sonarr_get_history`, `sonarr_get_health`, `sonarr_get_releases`, `sonarr_get_command`, `sonarr_add_series`, `sonarr_set_monitoring`, `sonarr_search_episodes`, `sonarr_grab_release`, `sonarr_remove_queue_item` | | Downloaders | `downloads_get_status`, `downloads_get_queue`, `downloads_get_history`, `downloads_get_categories`, `downloads_pause`, `downloads_resume`, `downloads_retry` | @@ -236,4 +250,4 @@ Tests use `httpx.MockTransport` for service API calls, MCP sessions for tool beh API tests target Sonarr/Radarr `/api/v3`, NZBGet v18+, SABnzbd 5.x and NZBHydra's public Newznab API. They don't check compatibility with every server release. Use disposable media and queues when testing writes against a live service. -[Implementation notes](IMPLEMENTATION_PLAN.md) cover the code structure and follow-up work. Changes to API operations should include a mock contract test. +[Implementation notes](IMPLEMENTATION_PLAN.md) cover the code structure and follow-up work. Changes to API operations should include a mock contract test. \ No newline at end of file diff --git a/jellyseerr_mcp/client.py b/jellyseerr_mcp/client.py index 4d30e2b..ae8fe2b 100644 --- a/jellyseerr_mcp/client.py +++ b/jellyseerr_mcp/client.py @@ -7,7 +7,61 @@ import httpx from .config import AppConfig, ServiceConfig -from .http import ServiceClient, non_negative_id, positive_id +from .http import ServiceClient, ServiceError, non_negative_id, positive_id, select + +# Seerr accepts a wider take than this; the cap keeps one tool call from +# pulling an unbounded slice of the request log into the model's context. +MAX_REQUEST_PAGE = 100 + +# Enum values verified against a live instance (2026-10-12): anything outside +# these sets answers 400, so they are rejected locally instead of round-tripped. +REQUEST_FILTERS = ('all', 'approved', 'available', 'pending', 'processing', + 'unavailable', 'failed', 'deleted', 'completed') +REQUEST_SORTS = ('added', 'modified') +REQUEST_MEDIA_TYPES = ('movie', 'tv') + +REQUEST_FIELDS = ('id', 'status', 'type', 'is4k', 'createdAt', 'updatedAt', + 'seasonCount', 'profileName', 'rootFolder') +REQUESTER_FIELDS = ('id', 'displayName', 'email', 'plexUsername', 'userType') +SEASON_FIELDS = ('seasonNumber', 'status') +REQUEST_MEDIA_FIELDS = ('id', 'mediaType', 'tmdbId', 'tvdbId', 'status', 'status4k', + 'serviceId', 'serviceId4k', 'externalServiceId', + 'externalServiceId4k', 'externalServiceSlug', + 'externalServiceSlug4k', 'ratingKey', 'mediaUrl', 'serviceUrl', + 'createdAt', 'mediaAddedAt') + + +def _bounded_text(value: Any, limit: int = 500) -> str: + text = str(value) + return text if len(text) <= limit else text[:limit] + "…" + + +def _request_item(record: Any) -> dict: + """Project one Seerr request record; never pass an upstream body through. + + The requester identity is the point of this projection, so it is kept + explicit: ``requested_by`` (who asked) and ``modified_by`` (who last acted, + usually the approving admin) are different fields and routinely differ. + + ``media.externalServiceId`` is the Sonarr/Radarr instance for the normal + quality, ``externalServiceId4k`` a separate one — they are not the same + record, so both are carried through. + """ + if not isinstance(record, dict): + return {} + item = select(record, REQUEST_FIELDS) + media = record.get('media') + if isinstance(media, dict): + item['media'] = select(media, REQUEST_MEDIA_FIELDS) + seasons = [select(s, SEASON_FIELDS) for s in (record.get('seasons') or []) + if isinstance(s, dict)] + item['seasons'] = seasons + item['season_numbers'] = [s['seasonNumber'] for s in seasons if 'seasonNumber' in s] + for key, field in (('requested_by', 'requestedBy'), ('modified_by', 'modifiedBy')): + who = record.get(field) + if isinstance(who, dict): + item[key] = select(who, REQUESTER_FIELDS) + return item class JellyseerrClient(ServiceClient): @@ -68,6 +122,95 @@ def request_media(self, media_id: int, media_type: str, is_4k: bool = False, def get_request(self, request_id: int) -> dict: return self.request("GET", f"request/{positive_id(request_id, 'request_id')}") + def _requests_query(self, page_number: object, limit: object, filter: object, + sort: object, requested_by: object, + media_type: object) -> tuple[dict, int, int]: + """Validate every bounded input before the single outbound read. + + Seerr ignores an unsupported query parameter instead of rejecting it + (``mediaId=`` returns the whole log) and silently accepts an unknown + ``requestedBy``, so an unvalidated filter would look like it worked + while returning everyone's requests. Everything is checked here because + none of it can be caught from the response. + """ + page_number, limit = self._request_paging(page_number, limit) + if filter not in REQUEST_FILTERS: + raise ValueError("filter must be one of: " + ", ".join(REQUEST_FILTERS)) + if sort not in REQUEST_SORTS: + raise ValueError("sort must be one of: " + ", ".join(REQUEST_SORTS)) + params = {'take': limit, 'skip': (page_number - 1) * limit, + 'filter': filter, 'sort': sort} + if requested_by is not None: + params['requestedBy'] = positive_id(requested_by, 'requested_by') + if media_type is not None: + if media_type not in REQUEST_MEDIA_TYPES: + raise ValueError("media_type must be one of: " + ", ".join(REQUEST_MEDIA_TYPES)) + params['mediaType'] = media_type + return params, page_number, limit + + def _request_paging(self, page_number: object, limit: object) -> tuple[int, int]: + if isinstance(page_number, bool) or not isinstance(page_number, int) or page_number < 1: + raise ValueError("page_number must be a positive integer") + if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= MAX_REQUEST_PAGE: + raise ValueError(f"limit must be between 1 and {MAX_REQUEST_PAGE}") + return page_number, limit + + def list_requests(self, page_number: int = 1, limit: int = 25, + filter: str = 'all', sort: str = 'added', + requested_by: int | None = None, + media_type: str | None = None) -> dict: + """Paged Seerr request log with requester attribution. + + Seerr's own ``pageInfo`` is echoed rather than recomputed: an unknown + ``requestedBy`` returns a 200 with zero results, so the upstream page + count is the only trustworthy total. + """ + params, page_number, limit = self._requests_query(page_number, limit, filter, + sort, requested_by, media_type) + response = self.request("GET", "request", params=params) + if not isinstance(response, dict): + raise ValueError("Seerr returned an unexpected request list") + items = [_request_item(r) for r in (response.get('results') or [])] + info = response.get('pageInfo') + reported = info.get('results') if isinstance(info, dict) else None + total = reported if isinstance(reported, int) and not isinstance(reported, bool) \ + else len(items) + offset = (page_number - 1) * limit + return {'items': items, 'offset': offset, 'limit': limit, 'total': total, + 'has_more': offset + len(items) < total, 'pagination': 'native'} + + def get_media_requests(self, tmdb_id: int, media_type: str = 'tv') -> dict: + """Every Seerr request for one title, keyed by TMDB id. + + ``/api/v1/media`` deliberately omits ``requests``, and ``request`` + ignores a ``mediaId`` filter, so the title's own detail endpoint is the + only route to per-title request history. A title absent from Seerr + answers 500 (not 404), which is reported as "never requested" rather + than raised as a fault. + """ + tmdb_id = positive_id(tmdb_id, 'tmdb_id') + if media_type not in REQUEST_MEDIA_TYPES: + raise ValueError("media_type must be one of: " + ", ".join(REQUEST_MEDIA_TYPES)) + try: + detail = self.request("GET", f"{media_type}/{tmdb_id}") + except ServiceError: + detail = None + if not isinstance(detail, dict): + return {'tmdb_id': tmdb_id, 'media_type': media_type, 'title': None, + 'in_seerr': False, 'requests': [], 'total': 0} + info = detail.get('mediaInfo') + info = info if isinstance(info, dict) else {} + requests = [_request_item(r) for r in (info.get('requests') or [])] + requests.sort(key=lambda r: r.get('createdAt') or '') + title = detail.get('name') if media_type == 'tv' else detail.get('title') + return {'tmdb_id': tmdb_id, 'media_type': media_type, + 'title': _bounded_text(title) if title else None, + 'in_seerr': bool(info.get('id')), + 'media': select(info, REQUEST_MEDIA_FIELDS), + 'seasons': [select(s, ('seasonNumber', 'status')) + for s in (info.get('seasons') or []) if isinstance(s, dict)], + 'requests': requests, 'total': len(requests)} + def raw_read(self, method: str, endpoint: str, params: dict | None = None, body: dict | None = None) -> dict: # Compatibility escape hatch is inspection-only, even in operator mode. diff --git a/jellyseerr_mcp/server.py b/jellyseerr_mcp/server.py index 253710e..2a2611a 100644 --- a/jellyseerr_mcp/server.py +++ b/jellyseerr_mcp/server.py @@ -105,6 +105,13 @@ def get_services() -> dict: seerr = cast(JellyseerrClient, clients["jellyseerr"]) register("search_media", seerr.search_media, "Search Seerr/Jellyseerr by text query.") register("get_request", seerr.get_request, "Inspect an existing Seerr request by its request ID.") + register("list_requests", seerr.list_requests, + "List the Seerr request log newest-first with requester attribution (who asked, who approved), " + "optionally filtered by requester user id or media type. Prefer this over get_request when the " + "request ID is not already known.") + register("get_media_requests", seerr.get_media_requests, + "List every Seerr request for one title by TMDB ID, oldest first: requesters, seasons and " + "approval state. A title Seerr has never seen is reported as in_seerr=false, not as an error.") register("request_media", seerr.request_media, "Create a Seerr request (preserves its approval workflow). Movie or TV TMDB ID; TV seasons default to [1]. Requires Seerr writes.", True) if config.allow_raw_read: diff --git a/tests/integration/test_stdio.py b/tests/integration/test_stdio.py index 9167be2..7381e7e 100644 --- a/tests/integration/test_stdio.py +++ b/tests/integration/test_stdio.py @@ -34,10 +34,12 @@ async def test_stdio_protocol_only_stdout(module, isolated, caplog, tmp_path): async with ClientSession(read,write,read_timeout_seconds=timedelta(seconds=10)) as session: await session.initialize() names = {tool.name for tool in (await session.list_tools()).tools} + seerr_reads = {'search_media', 'get_request', 'list_requests', + 'get_media_requests', 'request_media'} if isolated: - assert names == {'ping','get_services','search_media','get_request','request_media'} + assert names == {'ping', 'get_services'} | seerr_reads else: - assert {'ping','get_services','search_media','get_request','request_media'} <= names + assert {'ping', 'get_services'} | seerr_reads <= names ping = await session.call_tool('ping',{}) assert not ping.isError denied = await session.call_tool('request_media',{'media_id':1,'media_type':'movie'}) diff --git a/tests/test_client.py b/tests/test_client.py index 0b41866..906b015 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -30,6 +30,111 @@ def handler(request): client.close() +def test_list_requests_projects_requester_and_reports_native_total(): + """The request log is only useful if it says WHO asked. + + ``requestedBy`` is the requester and ``modifiedBy`` is whoever last acted + (usually the approving admin); they routinely differ, so both are kept. + """ + seen = [] + page = {'pageInfo': {'pages': 9, 'pageSize': 2, 'results': 18, 'page': 2}, + 'results': [{'id': 72, 'status': 5, 'type': 'tv', 'is4k': False, + 'createdAt': '2026-02-03T13:41:53.000Z', 'seasonCount': 2, + 'seasons': [{'seasonNumber': 6, 'status': 5}, + {'seasonNumber': 7, 'status': 5}], + 'media': {'id': 541, 'tmdbId': 1104, 'tvdbId': 80337, + 'status': 4, 'externalServiceId': 181, + 'externalServiceId4k': None, 'apiKey': 'leak'}, + 'requestedBy': {'id': 8, 'displayName': 'Chromenom', + 'email': 'p.noamtal@gmail.com', 'userType': 1, + 'password': 'leak'}, + 'modifiedBy': {'id': 1, 'displayName': 'aserper'}}]} + def handler(request): + seen.append(request) + return httpx.Response(200, json=page) + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local'), + httpx.MockTransport(handler)) + result = client.list_requests(page_number=2, limit=2, requested_by=8, media_type='tv') + url = str(seen[0].url) + assert 'take=2' in url and 'skip=2' in url + assert 'filter=all' in url and 'sort=added' in url + assert 'requestedBy=8' in url and 'mediaType=tv' in url + item = result['items'][0] + assert item['requested_by']['displayName'] == 'Chromenom' + assert item['modified_by']['displayName'] == 'aserper' + assert item['season_numbers'] == [6, 7] + assert item['media']['externalServiceId'] == 181 + # Upstream pageInfo drives the total, not the page length. + assert (result['total'], result['has_more'], result['pagination']) == (18, True, 'native') + # Credential-shaped keys never survive the projection. + assert 'password' not in item['requested_by'] and 'apiKey' not in item['media'] + client.close() + + +def test_request_filters_are_validated_before_the_network(): + """Seerr 400s on a bad filter/sort/mediaType but SILENTLY ignores unknown + ``requestedBy`` and ``mediaId``, so an unvalidated filter would look like it + worked while returning the whole log.""" + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local'), + httpx.MockTransport(lambda request: pytest.fail('network call'))) + bad_calls: list[dict] = [ + {'filter': 'declined'}, {'filter': 'bogus'}, {'sort': 'id'}, + {'media_type': 'series'}, {'requested_by': 0}, {'requested_by': 'abc'}, + {'requested_by': True}, {'page_number': 0}, {'page_number': True}, + {'limit': 0}, {'limit': 101}, {'limit': True}, + ] + for kwargs in bad_calls: + with pytest.raises(ValueError): + client.list_requests(**kwargs) + client.close() + + +def test_get_media_requests_collects_every_request_for_one_title(): + """``/api/v1/media`` omits ``requests`` and ``request?mediaId=`` is ignored, + so per-title history only comes from the title's own detail endpoint.""" + seen = [] + detail = {'id': 1104, 'name': 'Mad Men', 'mediaInfo': { + 'id': 541, 'tmdbId': 1104, 'status': 4, 'externalServiceId': 181, + 'seasons': [{'seasonNumber': 2, 'status': 5}], + 'requests': [ + {'id': 72, 'status': 5, 'type': 'tv', 'createdAt': '2026-02-03T13:41:53.000Z', + 'seasons': [{'seasonNumber': 6, 'status': 5}], + 'requestedBy': {'id': 8, 'displayName': 'Chromenom'}}, + {'id': 63, 'status': 5, 'type': 'tv', 'createdAt': '2026-01-07T20:51:34.000Z', + 'seasons': [{'seasonNumber': 2, 'status': 5}], + 'requestedBy': {'id': 8, 'displayName': 'Chromenom'}}]}} + def handler(request): + seen.append(request.url.path) + return httpx.Response(200, json=detail) + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local'), + httpx.MockTransport(handler)) + result = client.get_media_requests(1104, media_type='tv') + assert seen == ['/api/v1/tv/1104'] + assert result['title'] == 'Mad Men' and result['in_seerr'] is True + # Oldest first, so the original requester reads as the first entry. + assert [r['id'] for r in result['requests']] == [63, 72] + assert result['requests'][0]['requested_by']['displayName'] == 'Chromenom' + assert result['total'] == 2 + client.close() + + +def test_unknown_title_is_not_an_error(): + """Seerr answers 500 (not 404) for a TMDB id it has never seen; that is + "never requested", not a service fault to raise at the caller.""" + def handler(request): + return httpx.Response(500, json={'message': 'Item does not exist'}) + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local'), + httpx.MockTransport(handler)) + result = client.get_media_requests(999999, media_type='movie') + assert result['in_seerr'] is False and result['requests'] == [] + assert result['title'] is None and result['total'] == 0 + with pytest.raises(ValueError): + client.get_media_requests(0) + with pytest.raises(ValueError): + client.get_media_requests(1104, media_type='series') + client.close() + + def test_tv_request_does_not_invent_language_profile_or_seasons(): sent = [] def handler(request): diff --git a/tests/test_server.py b/tests/test_server.py index c262ba4..9225729 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -21,12 +21,39 @@ async def test_ping_discovery_and_conditional_tools(): httpx.MockTransport(lambda request: httpx.Response(200,json={'results':[]}))) server = build_server(AppConfig(), {'jellyseerr':client}) names = {tool.name for tool in await server.list_tools()} - assert names == {'ping','get_services','search_media','get_request','request_media'} + assert names == {'ping','get_services','search_media','get_request','list_requests', + 'get_media_requests','request_media'} assert unpack(await server.call_tool('ping',{})) == {'ok':True,'service':'arrchestra-mcp'} assert not unpack(await server.call_tool('get_services',{}))['services'][0]['writes_enabled'] client.close() +@pytest.mark.asyncio +async def test_seerr_request_reads_are_registered_read_only(): + """Requester attribution is an inspection tool: it must be advertised + read-only and must work with writes disabled.""" + calls = [] + def handler(request): + calls.append((request.method, request.url.path)) + if request.url.path == '/api/v1/request': + return httpx.Response(200, json={'pageInfo': {'results': 1}, + 'results': [{'id': 72, 'requestedBy': {'id': 8, 'displayName': 'Chromenom'}}]}) + return httpx.Response(200, json={'name': 'Mad Men', 'mediaInfo': {'id': 541, 'requests': []}}) + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local'), + httpx.MockTransport(handler)) + server = build_server(AppConfig(), {'jellyseerr': client}) + tools = {tool.name: tool for tool in await server.list_tools()} + for name in ('list_requests', 'get_media_requests'): + assert tools[name].annotations.readOnlyHint is True + listed = unpack(await server.call_tool('list_requests', {'limit': 1})) + assert listed['items'][0]['requested_by']['displayName'] == 'Chromenom' + assert listed['total'] == 1 and listed['pagination'] == 'native' + per_title = unpack(await server.call_tool('get_media_requests', {'tmdb_id': 1104, 'media_type': 'tv'})) + assert per_title['title'] == 'Mad Men' and per_title['requests'] == [] + assert calls == [('GET', '/api/v1/request'), ('GET', '/api/v1/tv/1104')] + client.close() + + @pytest.mark.asyncio async def test_readonly_enforced_over_wire_dispatch(): # Even injecting a writable client does not bypass the server's global policy. From 898d1e6a757edb5d5ab23a966e9b675356fc65fd Mon Sep 17 00:00:00 2001 From: Amit Serper Date: Sun, 11 Oct 2026 22:23:35 -0400 Subject: [PATCH 2/2] feat(seerr): add request status, retry and removal tools Request history covered reading the Seerr log, but nothing could act on it. Add the four documented mutations so a stuck or unwanted request can be handled through the server instead of by hand. retry_request re-runs the arr push for a request whose externalServiceId is empty, which is the repair for a request Seerr never handed to Sonarr or Radarr. set_request_status approves or declines one request. remove_request clears one log entry while leaving the title requestable, and remove_media discards Seerr's media record and availability state. The two deletes stay separate because they remove different records. Neither delete touches files or the arr entry, and Seerr accepts any media id with a success response, so remove_media reports removed separately from verified rather than claiming a record was deleted. Enums and parameter shapes come from Seerr's published OpenAPI document. All four tools are gated behind write permission and validate ids and statuses before the request is sent. --- IMPLEMENTATION_PLAN.md | 4 +- README.md | 15 +++- jellyseerr_mcp/client.py | 95 ++++++++++++++++++++++- jellyseerr_mcp/server.py | 8 ++ tests/integration/test_stdio.py | 14 +++- tests/test_client.py | 133 ++++++++++++++++++++++++++++++++ tests/test_server.py | 57 +++++++++++++- 7 files changed, 316 insertions(+), 10 deletions(-) diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index 9965b9a..15fdc49 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -34,7 +34,9 @@ Writes require both `MCP_READ_ONLY=false` and the target service's `ALLOW_WRITES Use `/api/v1` with `X-Api-Key`. Preserve `%20` search encoding, existing tool names and the default TV season `[1]`. Service defaults come from Seerr; language-profile IDs aren't guessed. A direct Sonarr/Radarr addition is separate from a Seerr request and its approval policy. -Request history reads two endpoints because neither alone is sufficient. `GET /api/v1/request` is the paged log (`take`, `skip`, `filter`, `sort`, `requestedBy`, `mediaType`) and carries `requestedBy` on every record; `GET /api/v1/{tv|movie}/{tmdbId}` carries `mediaInfo.requests` for one title. `GET /api/v1/media` omits `requests` entirely, and `request` silently ignores a `mediaId` filter, so a title-scoped read must not be built on either. Two upstream behaviours are load-bearing: an unknown `requestedBy` returns 200 with an empty page instead of an error, so the response cannot confirm the filter was honored and the values are validated locally; and an unknown TMDB id answers 500 (not 404), which is "never requested", not a fault. +Request-history reads come from two endpoints, because neither alone is sufficient. `GET /request` pages the log and carries `requestedBy`, but ignores a `mediaId` filter; `GET /media` omits `requests`. Per-title history is therefore only available from `GET /{tv|movie}/{tmdbId}` via `mediaInfo.requests`. A TMDB id Seerr has never seen answers 500, which the tools report as `in_seerr: false` rather than as a fault, and an unknown `requestedBy` answers 200 with an empty page, so filter and sort values are validated locally instead of inferred from the response. + +Request mutations map to Seerr's documented endpoints: `POST /request/{id}/retry` re-runs the arr push for a request whose `externalServiceId` is empty, `POST /request/{id}/{approve|decline}` changes its status, `DELETE /request/{id}` clears one log entry, and `DELETE /media/{id}` discards one media item's availability state. The two deletes stay separate because they remove different records: the first leaves the title requestable, the second removes Seerr's tracking of it. Neither deletes files, and `DELETE /media/{id}` answers success for any id, so its result reports `removed` separately from `verified`. ### Radarr and Sonarr diff --git a/README.md b/README.md index 9b58de4..9efda1b 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,8 @@ Hermes and OpenClaw configuration follows their documentation; end-to-end sessio | "Why hasn't Arrival imported? Check Radarr's queue and history." | Radarr queue, history and import diagnostics | | "Show the SABnzbd queue, then pause the download I choose." | Downloader queue and per-job pause | | "Who requested Mad Men, and when?" | Seerr request history | +| "That request is stuck. Approve it and make Seerr push it again." | Seerr request status and retry | +| "Remove those bogus requests, but keep the titles." | Seerr request removal | Calendars, lookups and status checks work in read-only mode. Requests, monitoring changes, searches that trigger downloads, and download controls need [write permission](#allowing-changes). `get_services` shows which services are connected and whether writes are enabled. @@ -170,6 +172,17 @@ Both are read-only and need no writes. Two upstream quirks shape them: `/api/v1/ Paging is reported as `native` from Seerr's `pageInfo`; a title the requester list does not match returns an empty page rather than an error. +### Fixing and removing requests + +A request that never reached Sonarr or Radarr sits in the log forever without ever downloading. The signal is `media.externalServiceId` being empty on a request that is otherwise approved. `retry_request` is Seerr's own repair for it: it re-runs the push and reports `pushed_to_arr` from the result, instead of creating a second request. `set_request_status` approves or declines one request (`approve` or `decline`); approval is the decision that lets Seerr push to the arr, not a bookkeeping flag. + +Removal comes in two deliberately separate operations, because they delete different things: + +- `remove_request` clears ONE log entry. The title's media record survives, so it can be requested again later. A request Seerr has already forgotten reports `removed: false` instead of failing. +- `remove_media` deletes ONE Seerr media item, discarding its availability status, request history and availability state. It does **not** delete the file on disk and does **not** remove the title from Sonarr or Radarr. + +A media ID is neither a TMDB ID nor a request ID. Seerr also accepts any media ID with a success response, even one it never had, so `remove_media` reports `removed` (the delete was accepted) separately from `verified` (a record is known to have existed). Neither tool can be used to delete files. + ### NZBHydra downloads ### Upcoming episodes and movie releases @@ -208,7 +221,7 @@ If NZB retrieval redirects to an indexer, add that indexer's origin to `NZBHYDRA | Group | Tools | | --- | --- | | Common | `ping`, `get_services` | -| Seerr | `search_media`, `request_media`, `get_request`, `list_requests`, `get_media_requests` | +| Seerr | `search_media`, `request_media`, `get_request`, `list_requests`, `get_media_requests`, `set_request_status`, `retry_request`, `remove_request`, `remove_media` | | Radarr | `radarr_find_movies`, `radarr_get_movie`, `radarr_get_options`, `radarr_get_queue`, `radarr_get_history`, `radarr_get_health`, `radarr_get_calendar`, `radarr_get_releases`, `radarr_get_command`, `radarr_add_movie`, `radarr_set_monitored`, `radarr_search_movie`, `radarr_grab_release` | | Sonarr | `sonarr_find_series`, `sonarr_get_series`, `sonarr_get_episodes`, `sonarr_get_next_up`, `sonarr_get_missing`, `sonarr_get_calendar`, `sonarr_get_options`, `sonarr_get_queue`, `sonarr_get_history`, `sonarr_get_health`, `sonarr_get_releases`, `sonarr_get_command`, `sonarr_add_series`, `sonarr_set_monitoring`, `sonarr_search_episodes`, `sonarr_grab_release`, `sonarr_remove_queue_item` | | Downloaders | `downloads_get_status`, `downloads_get_queue`, `downloads_get_history`, `downloads_get_categories`, `downloads_pause`, `downloads_resume`, `downloads_retry` | diff --git a/jellyseerr_mcp/client.py b/jellyseerr_mcp/client.py index ae8fe2b..c78f018 100644 --- a/jellyseerr_mcp/client.py +++ b/jellyseerr_mcp/client.py @@ -1,7 +1,7 @@ """Backward-compatible Jellyseerr/Seerr tools with explicit mutation policy.""" from __future__ import annotations -from typing import Any +from typing import Any, Literal from urllib.parse import quote import httpx @@ -21,9 +21,14 @@ REQUEST_MEDIA_TYPES = ('movie', 'tv') REQUEST_FIELDS = ('id', 'status', 'type', 'is4k', 'createdAt', 'updatedAt', - 'seasonCount', 'profileName', 'rootFolder') + 'seasonCount', 'profileName', 'rootFolder', 'serverId', 'profileId') REQUESTER_FIELDS = ('id', 'displayName', 'email', 'plexUsername', 'userType') SEASON_FIELDS = ('seasonNumber', 'status') +# Seerr's own status enums, from its published OpenAPI document. Invalid values +# are rejected upstream, so they are rejected here without a round trip. +REQUEST_APPROVAL_STATUSES = ('approve', 'decline') +MEDIA_STATUSES = ('available', 'partial', 'processing', 'pending', 'unknown', 'deleted') +ApprovalStatus = Literal['approve', 'decline'] REQUEST_MEDIA_FIELDS = ('id', 'mediaType', 'tmdbId', 'tvdbId', 'status', 'status4k', 'serviceId', 'serviceId4k', 'externalServiceId', 'externalServiceId4k', 'externalServiceSlug', @@ -73,7 +78,7 @@ def __init__(self, config: AppConfig | ServiceConfig, transport: httpx.BaseTrans def request(self, method: str, endpoint: str, *, params: dict | None = None, json: dict | None = None) -> Any: method = method.upper() - if method not in {"GET", "POST", "PUT"}: + if method not in {"GET", "POST", "PUT", "DELETE"}: raise ValueError("Unsupported service method") return self.request_json(method, "api/v1/" + endpoint.lstrip("/"), params=params, json=json, mutation=method != "GET") @@ -211,6 +216,90 @@ def get_media_requests(self, tmdb_id: int, media_type: str = 'tv') -> dict: for s in (info.get('seasons') or []) if isinstance(s, dict)], 'requests': requests, 'total': len(requests)} + def remove_request(self, request_id: int) -> dict: + """Remove one Seerr request, without touching the title it asked for. + + Deleting a request only clears the log entry. The ``media`` record it + pointed at survives, so a later request for the same title is accepted + again instead of being rejected as a duplicate. ``remove_media`` is the + operation that also deletes the title and its file. + + A request Seerr has already forgotten answers 404, which is reported as + ``removed: false`` rather than raised. + """ + request_id = positive_id(request_id, 'request_id') + try: + self.request("DELETE", f"request/{request_id}") + except ServiceError as exc: + # The mutation carries no read-back of its own, so a 404 is checked + # from a fresh read rather than assumed from the error text. + if self._request_exists(request_id): + raise + return {'request_id': request_id, 'removed': False, 'reason': 'not_found'} + return {'request_id': request_id, 'removed': True} + + def remove_media(self, media_id: int) -> dict: + """Delete one Seerr media item, discarding its availability status. + + This removes the title from Seerr's tracking, its request history and + its availability state; it does NOT delete the file on disk or remove + the title from Sonarr/Radarr. A media id is NOT a TMDB id and NOT a + request id; both are valid-looking numbers that address other records. + + Seerr answers 204 for ANY media id, present or not, so the response + cannot confirm a record existed. The result therefore reports + ``removed`` (the delete was accepted) separately from ``verified`` + (a record is known to have existed), and never claims a file was + touched. + """ + media_id = positive_id(media_id, 'media_id') + self.request("DELETE", f"media/{media_id}") + return {'media_id': media_id, 'removed': True, 'verified': False, + 'note': 'Seerr tracking only; files and the Sonarr/Radarr entry are ' + 'untouched. Seerr accepts any id here, so removal is not verifiable.'} + + def retry_request(self, request_id: int) -> dict: + """Re-run the arr push for a request that never reached Sonarr/Radarr. + + This is the supported repair for a request stuck with a null + ``externalServiceId``: Seerr re-attempts the add instead of creating a + duplicate request. It does not search for or download anything. + """ + request_id = positive_id(request_id, 'request_id') + result = self.request("POST", f"request/{request_id}/retry") + payload = result if isinstance(result, dict) else {} + item = _request_item(payload) or {'id': request_id} + media = item.get('media') or {} + return {'request_id': request_id, 'retried': True, + 'request': item, + 'external_service_id': media.get('externalServiceId'), + 'pushed_to_arr': bool(media.get('externalServiceId'))} + + def set_request_status(self, request_id: int, status: ApprovalStatus) -> dict: + """Approve or decline one request. + + Approval is what lets Seerr push a request to Sonarr/Radarr, so this is + the decision point, not a bookkeeping flag. + """ + request_id = positive_id(request_id, 'request_id') + if status not in REQUEST_APPROVAL_STATUSES: + raise ValueError("status must be one of: " + ", ".join(REQUEST_APPROVAL_STATUSES)) + result = self.request("POST", f"request/{request_id}/{status}") + payload = result if isinstance(result, dict) else {} + item = _request_item(payload) or {'id': request_id} + return {'request_id': request_id, 'status': status, 'request': item} + + def _request_exists(self, request_id: int) -> bool: + """Whether a request id is still readable; used to classify a delete. + + Deliberately boolean: the point is only to tell "already gone" apart + from a real failure, never to surface an upstream body. + """ + try: + return isinstance(self.request("GET", f"request/{request_id}"), dict) + except ServiceError: + return False + def raw_read(self, method: str, endpoint: str, params: dict | None = None, body: dict | None = None) -> dict: # Compatibility escape hatch is inspection-only, even in operator mode. diff --git a/jellyseerr_mcp/server.py b/jellyseerr_mcp/server.py index 2a2611a..c776ee0 100644 --- a/jellyseerr_mcp/server.py +++ b/jellyseerr_mcp/server.py @@ -114,6 +114,14 @@ def get_services() -> dict: "approval state. A title Seerr has never seen is reported as in_seerr=false, not as an error.") register("request_media", seerr.request_media, "Create a Seerr request (preserves its approval workflow). Movie or TV TMDB ID; TV seasons default to [1]. Requires Seerr writes.", True) + register("remove_request", seerr.remove_request, + "Remove ONE Seerr request by its request ID. Clears the log entry only: the title's media record and its file are untouched, so it can be requested again. Already-absent requests report removed=false instead of failing. Never deletes files.", True) + register("remove_media", seerr.remove_media, + "Delete ONE Seerr media item by its media ID, discarding its availability status and request history. Does NOT delete the file on disk and does NOT remove the title from Sonarr/Radarr. A media ID is neither a TMDB ID nor a request ID. Seerr answers success even for an unknown ID, so this means 'no longer tracked', not 'a record was deleted'.", True) + register("retry_request", seerr.retry_request, + "Re-run the Sonarr/Radarr push for a request that never reached the arr (null externalServiceId), instead of creating a duplicate request. Reports pushed_to_arr from the response. Does not search or download. Requires Seerr writes.", True) + register("set_request_status", seerr.set_request_status, + "Approve or decline ONE Seerr request by its request ID. Approval is what lets Seerr push the request to Sonarr/Radarr, not a bookkeeping flag. Requires Seerr writes.", True) if config.allow_raw_read: register("raw_request", seerr.raw_read, "Legacy opt-in inspection: GET status only; no body or query parameters, never writes.") diff --git a/tests/integration/test_stdio.py b/tests/integration/test_stdio.py index 7381e7e..23eb4c6 100644 --- a/tests/integration/test_stdio.py +++ b/tests/integration/test_stdio.py @@ -35,16 +35,22 @@ async def test_stdio_protocol_only_stdout(module, isolated, caplog, tmp_path): await session.initialize() names = {tool.name for tool in (await session.list_tools()).tools} seerr_reads = {'search_media', 'get_request', 'list_requests', - 'get_media_requests', 'request_media'} + 'get_media_requests'} + seerr_writes = {'request_media', 'remove_request', 'remove_media', + 'retry_request', 'set_request_status'} if isolated: - assert names == {'ping', 'get_services'} | seerr_reads + assert names == {'ping', 'get_services'} | seerr_reads | seerr_writes else: - assert {'ping', 'get_services'} | seerr_reads <= names + assert {'ping', 'get_services'} | seerr_reads | seerr_writes <= names ping = await session.call_tool('ping',{}) assert not ping.isError denied = await session.call_tool('request_media',{'media_id':1,'media_type':'movie'}) assert denied.isError - assert 'wire-secret-key' not in str(ping) + str(denied) + # Read-only mode must refuse every new mutation too, over the + # real wire path rather than only in-process. + refused = await session.call_tool('remove_request', {'request_id': 74}) + assert refused.isError + assert 'wire-secret-key' not in str(ping) + str(denied) + str(refused) errlog.seek(0) assert 'wire-secret-key' not in errlog.read() assert 'Failed to parse' not in caplog.text diff --git a/tests/test_client.py b/tests/test_client.py index 906b015..050cf89 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -5,6 +5,7 @@ from jellyseerr_mcp.client import JellyseerrClient from jellyseerr_mcp.config import AppConfig, ServiceConfig +from jellyseerr_mcp.http import ServiceError def test_client_and_search_encoding(): @@ -163,6 +164,138 @@ def test_permissions_before_network_and_raw_allowlist(): client.close() +def test_request_mutations_require_writes_and_validated_ids(): + """Every new mutation is gated and validated BEFORE the network is touched.""" + dead = lambda request: pytest.fail('network call') + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local'), + httpx.MockTransport(dead)) + for function, args in [(client.remove_request, (5,)), (client.remove_media, (9,)), + (client.retry_request, (5,)), + (client.set_request_status, (5, 'approve'))]: + with pytest.raises(PermissionError): + function(*args) + client.close() + + writable = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local',allow_writes=True), + httpx.MockTransport(dead)) + for bad in (0, -1, 'abc', True): + for function in (writable.remove_request, writable.remove_media, writable.retry_request): + with pytest.raises(ValueError): + function(bad) + with pytest.raises(ValueError): + writable.set_request_status(bad, 'approve') + with pytest.raises(ValueError): + writable.set_request_status(5, 'denied') + writable.close() + + +def test_remove_request_clears_only_the_log_entry(): + """Deleting a request must not delete the title it asked for. + + The media record is what makes a later re-request of the same title fail as + a duplicate, so the two deletes are deliberately separate operations. + """ + seen = [] + def handler(request): + seen.append((request.method, request.url.path)) + return httpx.Response(204) + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local',allow_writes=True), + httpx.MockTransport(handler)) + assert client.remove_request(74) == {'request_id': 74, 'removed': True} + assert seen == [('DELETE', '/api/v1/request/74')] + result = client.remove_media(550) + assert result['media_id'] == 550 and result['removed'] is True + # Seerr accepts any media id, so the tool must not claim a verified delete + # or imply it deleted a file. + assert result['verified'] is False + assert 'file' in result['note'] and 'untouched' in result['note'] + assert seen[-1] == ('DELETE', '/api/v1/media/550') + client.close() + + +def test_remove_request_reports_an_already_absent_request(): + """A 404 is 'already gone', not a failure: the state the caller wanted holds. + + Classified from a follow-up read rather than by parsing the error text. + """ + def handler(request): + if request.method == 'DELETE': + return httpx.Response(404, json={'message': 'Request not found'}) + assert request.method == 'GET' + return httpx.Response(404, json={'message': 'Request not found'}) + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local',allow_writes=True), + httpx.MockTransport(handler)) + assert client.remove_request(999999) == {'request_id': 999999, 'removed': False, + 'reason': 'not_found'} + client.close() + + +def test_remove_request_still_raises_when_the_delete_really_failed(): + """A delete that failed for any reason other than absence is a real error.""" + def handler(request): + if request.method == 'DELETE': + return httpx.Response(500, json={'message': 'boom'}) + return httpx.Response(200, json={'id': 74}) # request still there + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local',allow_writes=True), + httpx.MockTransport(handler)) + with pytest.raises(ServiceError): + client.remove_request(74) + client.close() + + +def test_retry_request_reports_whether_the_arr_push_succeeded(): + """The whole point of a retry is the externalServiceId it leaves behind.""" + seen = [] + def handler(request): + seen.append((request.method, request.url.path)) + return httpx.Response(200, json={'id': 74, 'status': 2, 'type': 'movie', + 'media': {'id': 550, 'tmdbId': 334541, + 'externalServiceId': None, + 'externalServiceId4k': None}}) + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local',allow_writes=True), + httpx.MockTransport(handler)) + result = client.retry_request(74) + assert seen == [('POST', '/api/v1/request/74/retry')] + assert result['retried'] is True and result['pushed_to_arr'] is False + assert result['external_service_id'] is None + assert result['request']['media']['id'] == 550 + client.close() + + +def test_set_request_status_maps_to_the_approval_endpoint(): + seen = [] + def handler(request): + seen.append((request.method, request.url.path)) + return httpx.Response(200, json={'id': 74, 'status': 2, 'type': 'movie'}) + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local',allow_writes=True), + httpx.MockTransport(handler)) + assert client.set_request_status(74, 'approve')['status'] == 'approve' + assert client.set_request_status(74, 'decline')['status'] == 'decline' + assert seen == [('POST', '/api/v1/request/74/approve'), + ('POST', '/api/v1/request/74/decline')] + client.close() + + +def test_orphaned_requests_are_visible_as_never_pushed(): + """A request Seerr never pushed has a null externalServiceId. + + That is the only signal distinguishing a stuck request from one merely + waiting on a release, so the projection has to carry it through. + """ + page = {'pageInfo': {'results': 1}, 'results': [ + {'id': 74, 'status': 2, 'type': 'movie', 'is4k': False, + 'createdAt': '2026-02-06T01:22:20.000Z', + 'media': {'id': 550, 'tmdbId': 334541, 'externalServiceId': None, + 'externalServiceId4k': None}, + 'requestedBy': {'id': 11, 'displayName': 'dado779'}}]} + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local'), + httpx.MockTransport(lambda request: httpx.Response(200, json=page))) + item = client.list_requests(limit=1)['items'][0] + assert item['media']['externalServiceId'] is None + assert item['requested_by']['displayName'] == 'dado779' + client.close() + + def test_server_id_zero_is_accepted(): """Seerr numbers its configured servers from 0; the default server is id 0. diff --git a/tests/test_server.py b/tests/test_server.py index 9225729..90c6d54 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -22,7 +22,8 @@ async def test_ping_discovery_and_conditional_tools(): server = build_server(AppConfig(), {'jellyseerr':client}) names = {tool.name for tool in await server.list_tools()} assert names == {'ping','get_services','search_media','get_request','list_requests', - 'get_media_requests','request_media'} + 'get_media_requests','request_media','remove_request','remove_media', + 'retry_request','set_request_status'} assert unpack(await server.call_tool('ping',{})) == {'ok':True,'service':'arrchestra-mcp'} assert not unpack(await server.call_tool('get_services',{}))['services'][0]['writes_enabled'] client.close() @@ -82,6 +83,60 @@ def handler(request): client.close() +@pytest.mark.asyncio +async def test_seerr_request_mutations_are_write_annotated_and_gated(): + """The new request mutations must be advertised as writes (not read-only) + and must be refused by global read-only mode over the real dispatch path.""" + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local',allow_writes=True), + httpx.MockTransport(lambda request: pytest.fail('network call'))) + server = build_server(AppConfig(read_only=True), {'jellyseerr': client}) + tools = {tool.name: tool for tool in await server.list_tools()} + for name in ('remove_request', 'remove_media', 'retry_request', 'set_request_status'): + assert tools[name].annotations.readOnlyHint is False + for name, args in [('remove_request', {'request_id': 74}), + ('remove_media', {'media_id': 550}), + ('retry_request', {'request_id': 74}), + ('set_request_status', {'request_id': 74, 'status': 'approve'})]: + with pytest.raises(Exception, match='read-only'): + await server.call_tool(name, args) + client.close() + + +@pytest.mark.asyncio +async def test_remove_request_tool_reaches_only_the_request_endpoint(): + """Wire-level contract: removing a request must never touch /media. + + Collapsing the two deletes into one call would silently delete the title + (and, on the file variant, its content), so the endpoint is asserted. + """ + seen = [] + def handler(request): + seen.append((request.method, request.url.path)) + return httpx.Response(204) + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local',allow_writes=True), + httpx.MockTransport(handler)) + # AppConfig defaults to read-only, so operator mode must be explicit here. + server = build_server(AppConfig(read_only=False), {'jellyseerr': client}) + result = unpack(await server.call_tool('remove_request', {'request_id': 74})) + assert result == {'request_id': 74, 'removed': True} + assert seen == [('DELETE', '/api/v1/request/74')] + client.close() + + +@pytest.mark.asyncio +async def test_retry_request_tool_reports_the_arr_push_state(): + def handler(request): + return httpx.Response(200, json={'id': 74, 'type': 'movie', + 'media': {'id': 550, 'externalServiceId': 812}}) + client = JellyseerrClient(ServiceConfig('jellyseerr','https://test.local',allow_writes=True), + httpx.MockTransport(handler)) + server = build_server(AppConfig(read_only=False), {'jellyseerr': client}) + result = unpack(await server.call_tool('retry_request', {'request_id': 74})) + assert result['retried'] is True and result['pushed_to_arr'] is True + assert result['external_service_id'] == 812 + client.close() + + @pytest.mark.asyncio async def test_arr_calendar_tools_register_only_for_the_configured_service(): """Sonarr is the only service with a next-up read, and both services expose