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.