Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions IMPLEMENTATION_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
20 changes: 17 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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

Expand Down Expand Up @@ -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` |
Expand Down Expand Up @@ -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.
145 changes: 144 additions & 1 deletion jellyseerr_mcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions jellyseerr_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 4 additions & 2 deletions tests/integration/test_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'})
Expand Down
Loading
Loading