@orellbuehler/sonarr-mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Orell Bühler
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # sonarr-mcp
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@orellbuehler/sonarr-mcp)](https://www.npmjs.com/package/@orellbuehler/sonarr-mcp)
4
+ [![CI](https://github.com/OrellBuehler/sonarr-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/OrellBuehler/sonarr-mcp/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/@orellbuehler/sonarr-mcp)](LICENSE)
6
+ [![node](https://img.shields.io/node/v/@orellbuehler/sonarr-mcp)](package.json)
7
+
8
+ Connect AI agents to [Sonarr](https://sonarr.tv/). This [Model Context Protocol](https://modelcontextprotocol.io/) server exposes the Sonarr v3 API as 136 tools, so assistants like Claude can manage your TV library — add series, chase missing episodes, unstick the download queue, tune quality profiles, and diagnose health issues.
9
+
10
+ Works with any MCP client: Claude Code, Claude Desktop, or your own agent.
11
+
12
+ ## Highlights
13
+
14
+ - **Library management** — search TVDB, add and remove series, edit them one at a time or in bulk, and monitor or unmonitor whole seasons
15
+ - **Episodes and files** — list episodes, find what is missing, delete or re-tag episode files, preview renames
16
+ - **Downloads** — inspect the queue, remove or blocklist stuck grabs, force imports, and diagnose files needing manual interaction
17
+ - **Interactive search** — query indexers live, see why releases were rejected, and grab the one you want by hand
18
+ - **Quality tuning** — quality profiles and definitions, custom formats, release and delay profiles
19
+ - **Configuration** — indexers, download clients, import lists, notifications, root folders, tags, naming, and media management
20
+ - **Diagnostics** — system status, health checks, disk space, scheduled tasks, command history, and log files
21
+ - **Compact by default** — list tools return summaries instead of Sonarr's very large objects, with `detailed: true` when you need everything
22
+
23
+ Things you can ask once it's connected:
24
+
25
+ > "What's airing this week, and is anything already missing?"
26
+ >
27
+ > "Add Severance, 1080p profile, into /tv and search for the whole thing"
28
+ >
29
+ > "The queue is stuck — what's wrong and can you fix it?"
30
+ >
31
+ > "Find me a release for the season finale that isn't x265"
32
+ >
33
+ > "Which of my series are still below their quality cutoff?"
34
+
35
+ ## Quick start
36
+
37
+ The package is published as [`@orellbuehler/sonarr-mcp`](https://www.npmjs.com/package/@orellbuehler/sonarr-mcp) and runs directly with `npx` — no clone or build needed.
38
+
39
+ 1. Get your API key from Sonarr: **Settings > General > Security > API Key**
40
+ 2. Register the server with your MCP client. With Claude Code:
41
+
42
+ ```bash
43
+ claude mcp add sonarr \
44
+ --env SONARR_URL=http://your-sonarr-host:8989 \
45
+ --env SONARR_API_KEY=your-api-key \
46
+ -- npx -y @orellbuehler/sonarr-mcp
47
+ ```
48
+
49
+ Or as JSON config (Claude Desktop and most other MCP clients use the same shape):
50
+
51
+ ```json
52
+ {
53
+ "mcpServers": {
54
+ "sonarr": {
55
+ "command": "npx",
56
+ "args": ["-y", "@orellbuehler/sonarr-mcp"],
57
+ "env": {
58
+ "SONARR_URL": "http://your-sonarr-host:8989",
59
+ "SONARR_API_KEY": "your-api-key"
60
+ }
61
+ }
62
+ }
63
+ }
64
+ ```
65
+
66
+ 3. Restart your MCP client. The tools are available immediately.
67
+
68
+ If Sonarr runs behind a reverse proxy with a URL base, include it in `SONARR_URL` (e.g. `https://media.example.com/sonarr`).
69
+
70
+ ## Environment variables
71
+
72
+ | Variable | Required | Description |
73
+ | ---------------- | -------- | -------------------------------------------------------------------------------------------------------------- |
74
+ | `SONARR_URL` | yes | Base URL of your Sonarr instance, e.g. `http://192.168.1.10:8989`. `http://` is assumed if no scheme is given. |
75
+ | `SONARR_SERVER` | – | Accepted as an alias for `SONARR_URL`. |
76
+ | `SONARR_API_KEY` | yes | API key from Settings > General > Security. |
77
+
78
+ The server speaks stdio only — it is a single-user, single-instance server. It is never asked for your key over the network; the key is read from the environment and sent to Sonarr as the `X-Api-Key` header.
79
+
80
+ ## Available tools
81
+
82
+ | Category | Tools |
83
+ | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
84
+ | Series | `list_series`, `get_series`, `lookup_series`, `add_series`, `update_series`, `delete_series`, `edit_series_bulk`, `delete_series_bulk`, `get_series_folder`, `set_season_monitored` |
85
+ | Episodes | `list_episodes`, `get_episode`, `set_episodes_monitored` |
86
+ | Episode files | `list_episode_files`, `get_episode_file`, `delete_episode_file`, `delete_episode_files`, `update_episode_files` |
87
+ | Calendar & wanted | `get_calendar`, `get_missing_episodes`, `get_cutoff_unmet_episodes` |
88
+ | Queue | `get_queue`, `get_queue_details`, `get_queue_status`, `remove_queue_item`, `remove_queue_items`, `grab_queue_item`, `grab_queue_items` |
89
+ | History | `get_history`, `get_history_since`, `get_series_history`, `mark_history_item_failed` |
90
+ | Blocklist | `get_blocklist`, `remove_blocklist_item`, `remove_blocklist_items` |
91
+ | Search & releases | `search_releases`, `grab_release`, `get_manual_import_candidates`, `get_rename_preview`, `parse_release_title` |
92
+ | Commands | `run_command`, `list_commands`, `get_command`, `cancel_command`, `refresh_series`, `rescan_series`, `search_series`, `search_season`, `search_episodes`, `list_scheduled_tasks`, `get_scheduled_task` |
93
+ | Quality profiles | `list_quality_profiles`, `get_quality_profile`, `get_quality_profile_schema`, `create_quality_profile`, `update_quality_profile`, `delete_quality_profile` |
94
+ | Quality & formats | `list_quality_definitions`, `update_quality_definitions`, `list_custom_formats`, `get_custom_format`, `get_custom_format_schema`, `create_custom_format`, `update_custom_format`, `delete_custom_format` |
95
+ | Release rules | `list_release_profiles`, `create_release_profile`, `update_release_profile`, `delete_release_profile`, `list_delay_profiles`, `list_languages` |
96
+ | Indexers | `list_indexers`, `get_indexer`, `get_indexer_schema`, `create_indexer`, `update_indexer`, `delete_indexer`, `test_indexer` |
97
+ | Download clients | `list_download_clients`, `get_download_client`, `get_download_client_schema`, `create_download_client`, `update_download_client`, `delete_download_client`, `test_download_client` |
98
+ | Import lists | `list_import_lists`, `get_import_list`, `get_import_list_schema`, `create_import_list`, `update_import_list`, `delete_import_list`, `test_import_list` |
99
+ | Notifications | `list_notifications`, `get_notification`, `get_notification_schema`, `create_notification`, `update_notification`, `delete_notification`, `test_notification` |
100
+ | Root folders | `list_root_folders`, `get_root_folder`, `add_root_folder`, `delete_root_folder` |
101
+ | Tags | `list_tags`, `list_tag_details`, `create_tag`, `update_tag`, `delete_tag` |
102
+ | Exclusions & paths | `list_import_list_exclusions`, `add_import_list_exclusion`, `delete_import_list_exclusion`, `list_remote_path_mappings`, `add_remote_path_mapping`, `delete_remote_path_mapping` |
103
+ | Configuration | `get_naming_config`, `update_naming_config`, `get_naming_examples`, `get_media_management_config`, `update_media_management_config`, `get_indexer_config`, `update_indexer_config`, `get_download_client_config`, `update_download_client_config`, `get_import_list_config`, `update_import_list_config`, `get_host_config`, `get_ui_config` |
104
+ | System | `get_system_status`, `get_health`, `get_disk_space`, `get_updates`, `list_logs`, `list_log_files`, `get_log_file`, `list_backups`, `restart_sonarr` |
105
+
106
+ ### Notes
107
+
108
+ - **List tools return summaries.** `list_series`, `list_episodes`, `get_calendar`, `search_releases` and the wanted lists strip images, overviews and alternate titles so a large library still fits in context. Pass `detailed: true`, or use the matching `get_*` tool, when you need the full object.
109
+ - **Ids.** Sonarr series ids are not TVDB ids. `lookup_series` returns `tvdbId` (what `add_series` takes); everything else takes the Sonarr `id` from `list_series`.
110
+ - **Searching.** `search_series`, `search_season` and `search_episodes` queue Sonarr's own automatic search and return a command id — poll it with `get_command`. `search_releases` instead queries indexers live and returns the candidate releases for you to pick from, which you then send with `grab_release`.
111
+ - **Provider configuration.** Indexers, download clients, import lists and notifications are configured through an implementation-specific `fields` array. Call `get_*_schema` for the template, then pass the whole object to `create_*`; for updates, fetch with `get_*`, change what you need, and send it back. Sonarr masks secrets in responses, so re-sending a fetched object keeps the stored secret.
112
+ - **Destructive operations are explicit.** `delete_series`, `delete_series_bulk` and the queue tools only touch files on disk when you pass `delete_files` / `remove_from_client`, and both default to the safe choice. `restart_sonarr` is included; there is deliberately no shutdown, restore-backup or update-install tool.
113
+ - **Sonarr v4.** The v3 API paths are what Sonarr v4 serves, so this works against both v3 and v4. A handful of endpoints in the published spec (language profiles) exist only on v3 and are not exposed.
114
+
115
+ ## Development
116
+
117
+ ```bash
118
+ npm install
119
+ npm run build # tsc -> dist/
120
+ npm test # vitest run
121
+ npm run lint # eslint src
122
+ npm run typecheck # tsc --noEmit
123
+ npm run format # prettier --write .
124
+ npm run spec:update # refresh sonarr-openapi.json from the Sonarr repo
125
+ ```
126
+
127
+ `sonarr-openapi.json` is a vendored copy of the [Sonarr v3 OpenAPI spec](https://sonarr.tv/docs/api/) and is the reference for tool parameters — it is not used at runtime.
128
+
129
+ ## License
130
+
131
+ MIT
package/dist/config.js ADDED
@@ -0,0 +1,19 @@
1
+ import { SonarrClient } from "./sonarr/client.js";
2
+ const rawUrl = (process.env.SONARR_URL || process.env.SONARR_SERVER || "").trim();
3
+ const apiKey = (process.env.SONARR_API_KEY || "").trim();
4
+ if (!rawUrl || !apiKey) {
5
+ console.error("SONARR_URL (or SONARR_SERVER) and SONARR_API_KEY environment variables are required. " +
6
+ "The API key is in Sonarr under Settings > General > Security.");
7
+ process.exit(1);
8
+ }
9
+ export function normalizeBaseUrl(url) {
10
+ const withScheme = /^https?:\/\//i.test(url) ? url : `http://${url}`;
11
+ return withScheme.replace(/\/+$/, "");
12
+ }
13
+ const baseUrl = normalizeBaseUrl(rawUrl);
14
+ export const config = {
15
+ baseUrl,
16
+ apiKey,
17
+ transport: "stdio",
18
+ };
19
+ export const client = new SonarrClient(baseUrl, apiKey);
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { client } from "./config.js";
4
+ import { createServer } from "./server.js";
5
+ const server = createServer(client);
6
+ const transport = new StdioServerTransport();
7
+ try {
8
+ await server.connect(transport);
9
+ }
10
+ catch (e) {
11
+ console.error(`Failed to start sonarr-mcp: ${String(e)}`);
12
+ process.exit(1);
13
+ }
package/dist/server.js ADDED
@@ -0,0 +1,33 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { registerSeriesTools } from "./tools/series.js";
3
+ import { registerEpisodeTools } from "./tools/episodes.js";
4
+ import { registerCalendarTools } from "./tools/calendar.js";
5
+ import { registerQueueTools } from "./tools/queue.js";
6
+ import { registerHistoryTools } from "./tools/history.js";
7
+ import { registerWantedTools } from "./tools/wanted.js";
8
+ import { registerBlocklistTools } from "./tools/blocklist.js";
9
+ import { registerCommandTools } from "./tools/commands.js";
10
+ import { registerReleaseTools } from "./tools/releases.js";
11
+ import { registerProfileTools } from "./tools/profiles.js";
12
+ import { registerProviderTools } from "./tools/providers.js";
13
+ import { registerOrganizationTools } from "./tools/organization.js";
14
+ import { registerSettingsTools } from "./tools/settings.js";
15
+ import { registerSystemTools } from "./tools/system.js";
16
+ export function createServer(client) {
17
+ const server = new McpServer({ name: "sonarr-mcp", version: "0.1.0" });
18
+ registerSeriesTools(server, client);
19
+ registerEpisodeTools(server, client);
20
+ registerCalendarTools(server, client);
21
+ registerQueueTools(server, client);
22
+ registerHistoryTools(server, client);
23
+ registerWantedTools(server, client);
24
+ registerBlocklistTools(server, client);
25
+ registerCommandTools(server, client);
26
+ registerReleaseTools(server, client);
27
+ registerProfileTools(server, client);
28
+ registerProviderTools(server, client);
29
+ registerOrganizationTools(server, client);
30
+ registerSettingsTools(server, client);
31
+ registerSystemTools(server, client);
32
+ return server;
33
+ }
@@ -0,0 +1,73 @@
1
+ export class SonarrClient {
2
+ baseUrl;
3
+ apiKey;
4
+ timeoutMs;
5
+ constructor(baseUrl, apiKey, timeoutMs = 30000) {
6
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
7
+ this.apiKey = apiKey;
8
+ this.timeoutMs = timeoutMs;
9
+ }
10
+ headers(options) {
11
+ return {
12
+ "X-Api-Key": this.apiKey,
13
+ Accept: "application/json",
14
+ ...(typeof options.body === "string" ? { "Content-Type": "application/json" } : {}),
15
+ ...(options.headers ?? {}),
16
+ };
17
+ }
18
+ async request(path, options) {
19
+ let res;
20
+ try {
21
+ res = await fetch(`${this.baseUrl}${path}`, {
22
+ ...options,
23
+ headers: this.headers(options),
24
+ signal: options.signal ?? AbortSignal.timeout(this.timeoutMs),
25
+ });
26
+ }
27
+ catch (e) {
28
+ if (e instanceof DOMException && e.name === "TimeoutError") {
29
+ throw new Error(`Sonarr request timed out after ${this.timeoutMs}ms`, { cause: e });
30
+ }
31
+ throw e;
32
+ }
33
+ if (!res.ok) {
34
+ const body = await res.text();
35
+ throw new Error(`${res.status} ${res.statusText}: ${body}`);
36
+ }
37
+ return res;
38
+ }
39
+ async fetch(path, options = {}) {
40
+ const res = await this.request(path, options);
41
+ if (res.status === 204)
42
+ return { success: true };
43
+ const ct = res.headers.get("content-type") ?? "";
44
+ if (!ct.includes("application/json"))
45
+ return res.text();
46
+ const text = await res.text();
47
+ return text ? JSON.parse(text) : { success: true };
48
+ }
49
+ async fetchText(path, options = {}) {
50
+ return (await this.request(path, options)).text();
51
+ }
52
+ get(path) {
53
+ return this.fetch(path);
54
+ }
55
+ post(path, body) {
56
+ return this.fetch(path, {
57
+ method: "POST",
58
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
59
+ });
60
+ }
61
+ put(path, body) {
62
+ return this.fetch(path, {
63
+ method: "PUT",
64
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
65
+ });
66
+ }
67
+ delete(path, body) {
68
+ return this.fetch(path, {
69
+ method: "DELETE",
70
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
71
+ });
72
+ }
73
+ }
@@ -0,0 +1,108 @@
1
+ export function buildQS(params) {
2
+ const sp = new URLSearchParams();
3
+ for (const [k, v] of Object.entries(params)) {
4
+ if (v === undefined || v === null)
5
+ continue;
6
+ if (Array.isArray(v)) {
7
+ for (const item of v) {
8
+ if (item === undefined || item === null)
9
+ continue;
10
+ sp.append(k, String(item));
11
+ }
12
+ }
13
+ else {
14
+ sp.set(k, String(v));
15
+ }
16
+ }
17
+ const s = sp.toString();
18
+ return s ? `?${s}` : "";
19
+ }
20
+ export function ok(data) {
21
+ const text = typeof data === "string" ? data : JSON.stringify(data);
22
+ return { content: [{ type: "text", text }] };
23
+ }
24
+ export function err(e) {
25
+ return { content: [{ type: "text", text: String(e) }], isError: true };
26
+ }
27
+ export function pruneUndefined(obj) {
28
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
29
+ }
30
+ export function summarizeSeries(s) {
31
+ const stats = (s.statistics ?? {});
32
+ return pruneUndefined({
33
+ id: s.id,
34
+ title: s.title,
35
+ year: s.year,
36
+ status: s.status,
37
+ monitored: s.monitored,
38
+ seriesType: s.seriesType,
39
+ network: s.network,
40
+ qualityProfileId: s.qualityProfileId,
41
+ path: s.path,
42
+ tvdbId: s.tvdbId,
43
+ tags: s.tags,
44
+ nextAiring: s.nextAiring,
45
+ seasonCount: stats.seasonCount,
46
+ episodeFileCount: stats.episodeFileCount,
47
+ episodeCount: stats.episodeCount,
48
+ totalEpisodeCount: stats.totalEpisodeCount,
49
+ sizeOnDisk: stats.sizeOnDisk,
50
+ percentOfEpisodes: stats.percentOfEpisodes,
51
+ });
52
+ }
53
+ export function summarizeEpisode(e) {
54
+ return pruneUndefined({
55
+ id: e.id,
56
+ seriesId: e.seriesId,
57
+ seriesTitle: e.series?.title,
58
+ seasonNumber: e.seasonNumber,
59
+ episodeNumber: e.episodeNumber,
60
+ absoluteEpisodeNumber: e.absoluteEpisodeNumber ?? undefined,
61
+ title: e.title,
62
+ airDateUtc: e.airDateUtc,
63
+ hasFile: e.hasFile,
64
+ monitored: e.monitored,
65
+ episodeFileId: e.episodeFileId || undefined,
66
+ finaleType: e.finaleType ?? undefined,
67
+ });
68
+ }
69
+ export function summarizeRelease(r) {
70
+ const quality = r.quality?.quality?.name;
71
+ const languages = r.languages?.map((l) => l.name);
72
+ return pruneUndefined({
73
+ guid: r.guid,
74
+ title: r.title,
75
+ indexer: r.indexer,
76
+ indexerId: r.indexerId,
77
+ protocol: r.protocol,
78
+ quality,
79
+ languages,
80
+ customFormatScore: r.customFormatScore,
81
+ size: r.size,
82
+ ageHours: r.ageHours,
83
+ publishDate: r.publishDate,
84
+ seeders: r.seeders,
85
+ leechers: r.leechers,
86
+ seasonNumber: r.seasonNumber,
87
+ episodeNumbers: r.episodeNumbers,
88
+ fullSeason: r.fullSeason,
89
+ approved: r.approved,
90
+ rejected: r.rejected,
91
+ rejections: r.rejections,
92
+ downloadAllowed: r.downloadAllowed,
93
+ releaseWeight: r.releaseWeight,
94
+ });
95
+ }
96
+ export function summarizeList(data, fn, detailed) {
97
+ if (detailed)
98
+ return data;
99
+ if (Array.isArray(data))
100
+ return data.map((item) => fn(item));
101
+ if (data && typeof data === "object") {
102
+ const obj = data;
103
+ if (Array.isArray(obj.records)) {
104
+ return { ...obj, records: obj.records.map((item) => fn(item)) };
105
+ }
106
+ }
107
+ return data;
108
+ }
@@ -0,0 +1,47 @@
1
+ import { z } from "zod";
2
+ import { buildQS, ok, err } from "../sonarr/format.js";
3
+ const sortDirection = ["default", "ascending", "descending"];
4
+ export function registerBlocklistTools(server, client) {
5
+ server.tool("get_blocklist", "Page through blocklisted releases — releases Sonarr has been told never to grab again, with the reason they were blocked.", {
6
+ page: z.number().optional().describe("Page number (default 1)"),
7
+ page_size: z.number().optional().describe("Items per page (default 10 on the Sonarr side)"),
8
+ sort_key: z.string().optional().describe("Field to sort by, e.g. 'date'"),
9
+ sort_direction: z.enum(sortDirection).optional().describe("Sort direction"),
10
+ series_ids: z.array(z.number()).optional().describe("Only entries for these series ids"),
11
+ protocols: z
12
+ .array(z.enum(["unknown", "usenet", "torrent"]))
13
+ .optional()
14
+ .describe("Only these download protocols"),
15
+ }, async ({ page, page_size, sort_key, sort_direction, series_ids, protocols }) => {
16
+ try {
17
+ const qs = buildQS({
18
+ page,
19
+ pageSize: page_size,
20
+ sortKey: sort_key,
21
+ sortDirection: sort_direction,
22
+ seriesIds: series_ids,
23
+ protocols,
24
+ });
25
+ return ok(await client.get(`/api/v3/blocklist${qs}`));
26
+ }
27
+ catch (e) {
28
+ return err(e);
29
+ }
30
+ });
31
+ server.tool("remove_blocklist_item", "Remove one release from the blocklist so Sonarr may grab it again.", { id: z.number().describe("Blocklist entry id") }, async ({ id }) => {
32
+ try {
33
+ return ok(await client.delete(`/api/v3/blocklist/${id}`));
34
+ }
35
+ catch (e) {
36
+ return err(e);
37
+ }
38
+ });
39
+ server.tool("remove_blocklist_items", "Remove several releases from the blocklist at once.", { ids: z.array(z.number()).describe("Blocklist entry ids") }, async ({ ids }) => {
40
+ try {
41
+ return ok(await client.delete("/api/v3/blocklist/bulk", { ids }));
42
+ }
43
+ catch (e) {
44
+ return err(e);
45
+ }
46
+ });
47
+ }
@@ -0,0 +1,38 @@
1
+ import { z } from "zod";
2
+ import { buildQS, ok, err, summarizeEpisode } from "../sonarr/format.js";
3
+ export function registerCalendarTools(server, client) {
4
+ server.tool("get_calendar", "List episodes airing in a date range — what aired recently and what is coming up. Defaults to today and tomorrow on the Sonarr side.", {
5
+ start: z.string().optional().describe("ISO 8601 start date, e.g. '2026-09-01'"),
6
+ end: z.string().optional().describe("ISO 8601 end date, e.g. '2026-09-08'"),
7
+ unmonitored: z
8
+ .boolean()
9
+ .optional()
10
+ .describe("Include unmonitored episodes (default false on the Sonarr side)"),
11
+ include_series: z
12
+ .boolean()
13
+ .optional()
14
+ .describe("Include the parent series object; the summary shows seriesTitle either way"),
15
+ include_episode_file: z.boolean().optional().describe("Include the episode file object"),
16
+ tags: z.array(z.number()).optional().describe("Only series carrying these tag ids"),
17
+ detailed: z.boolean().optional().describe("Return full episode objects instead of summaries"),
18
+ }, async ({ start, end, unmonitored, include_series, include_episode_file, tags, detailed }) => {
19
+ try {
20
+ const qs = buildQS({
21
+ start,
22
+ end,
23
+ unmonitored,
24
+ includeSeries: include_series ?? true,
25
+ includeEpisodeFile: include_episode_file,
26
+ tags: tags?.join(","),
27
+ });
28
+ const rows = (await client.get(`/api/v3/calendar${qs}`));
29
+ return ok({
30
+ count: rows.length,
31
+ episodes: detailed ? rows : rows.map(summarizeEpisode),
32
+ });
33
+ }
34
+ catch (e) {
35
+ return err(e);
36
+ }
37
+ });
38
+ }
@@ -0,0 +1,142 @@
1
+ import { z } from "zod";
2
+ import { ok, err } from "../sonarr/format.js";
3
+ function summarizeCommand(c) {
4
+ return {
5
+ id: c.id,
6
+ name: c.commandName ?? c.name,
7
+ status: c.status,
8
+ queued: c.queued,
9
+ started: c.started,
10
+ ended: c.ended,
11
+ duration: c.duration,
12
+ trigger: c.trigger,
13
+ message: c.message,
14
+ exception: c.exception,
15
+ };
16
+ }
17
+ export function registerCommandTools(server, client) {
18
+ server.tool("list_commands", "List commands Sonarr is currently running or has recently run, with their status and duration.", {}, async () => {
19
+ try {
20
+ const data = (await client.get("/api/v3/command"));
21
+ return ok({ count: data.length, commands: data.map(summarizeCommand) });
22
+ }
23
+ catch (e) {
24
+ return err(e);
25
+ }
26
+ });
27
+ server.tool("get_command", "Get the status of a single command by id — poll this after starting a search or refresh.", { id: z.number().describe("Command id returned when the command was queued") }, async ({ id }) => {
28
+ try {
29
+ return ok(await client.get(`/api/v3/command/${id}`));
30
+ }
31
+ catch (e) {
32
+ return err(e);
33
+ }
34
+ });
35
+ server.tool("run_command", "Queue any Sonarr command by name. Known names: RefreshSeries, RescanSeries, EpisodeSearch, SeasonSearch, SeriesSearch, MissingEpisodeSearch, CutoffUnmetEpisodeSearch, DownloadedEpisodesScan, RenameFiles, RenameSeries, RssSync, RefreshMonitoredDownloads, ImportListSync, ManualImport, ClearBlocklist, CheckHealth, Housekeeping, Backup, ApplicationUpdate. Prefer the dedicated tools (refresh_series, search_series, ...) where one exists.", {
36
+ name: z.string().describe("Command name, e.g. 'RssSync'"),
37
+ params: z
38
+ .record(z.unknown())
39
+ .optional()
40
+ .describe("Extra command body fields, e.g. { seriesId: 12 } or { episodeIds: [1, 2] }"),
41
+ }, async ({ name, params }) => {
42
+ try {
43
+ const res = (await client.post("/api/v3/command", {
44
+ name,
45
+ ...(params ?? {}),
46
+ }));
47
+ return ok(summarizeCommand(res));
48
+ }
49
+ catch (e) {
50
+ return err(e);
51
+ }
52
+ });
53
+ server.tool("cancel_command", "Cancel a queued or running command.", { id: z.number().describe("Command id") }, async ({ id }) => {
54
+ try {
55
+ return ok(await client.delete(`/api/v3/command/${id}`));
56
+ }
57
+ catch (e) {
58
+ return err(e);
59
+ }
60
+ });
61
+ server.tool("refresh_series", "Refresh metadata from TVDB for one series, or for the whole library when no id is given.", { series_id: z.number().optional().describe("Sonarr series id; all series when omitted") }, async ({ series_id }) => {
62
+ try {
63
+ const res = (await client.post("/api/v3/command", {
64
+ name: "RefreshSeries",
65
+ ...(series_id === undefined ? {} : { seriesId: series_id }),
66
+ }));
67
+ return ok(summarizeCommand(res));
68
+ }
69
+ catch (e) {
70
+ return err(e);
71
+ }
72
+ });
73
+ server.tool("rescan_series", "Rescan the folder of one series (or all series) to pick up files added or removed outside Sonarr.", { series_id: z.number().optional().describe("Sonarr series id; all series when omitted") }, async ({ series_id }) => {
74
+ try {
75
+ const res = (await client.post("/api/v3/command", {
76
+ name: "RescanSeries",
77
+ ...(series_id === undefined ? {} : { seriesId: series_id }),
78
+ }));
79
+ return ok(summarizeCommand(res));
80
+ }
81
+ catch (e) {
82
+ return err(e);
83
+ }
84
+ });
85
+ server.tool("search_series", "Start an automatic search for all monitored missing episodes of a series.", { series_id: z.number().describe("Sonarr series id") }, async ({ series_id }) => {
86
+ try {
87
+ const res = (await client.post("/api/v3/command", {
88
+ name: "SeriesSearch",
89
+ seriesId: series_id,
90
+ }));
91
+ return ok(summarizeCommand(res));
92
+ }
93
+ catch (e) {
94
+ return err(e);
95
+ }
96
+ });
97
+ server.tool("search_season", "Start an automatic search for one season of a series.", {
98
+ series_id: z.number().describe("Sonarr series id"),
99
+ season_number: z.number().describe("Season number (0 is specials)"),
100
+ }, async ({ series_id, season_number }) => {
101
+ try {
102
+ const res = (await client.post("/api/v3/command", {
103
+ name: "SeasonSearch",
104
+ seriesId: series_id,
105
+ seasonNumber: season_number,
106
+ }));
107
+ return ok(summarizeCommand(res));
108
+ }
109
+ catch (e) {
110
+ return err(e);
111
+ }
112
+ });
113
+ server.tool("search_episodes", "Start an automatic search for specific episodes. Use search_releases first if you want to pick a release by hand.", { episode_ids: z.array(z.number()).describe("Sonarr episode ids") }, async ({ episode_ids }) => {
114
+ try {
115
+ const res = (await client.post("/api/v3/command", {
116
+ name: "EpisodeSearch",
117
+ episodeIds: episode_ids,
118
+ }));
119
+ return ok(summarizeCommand(res));
120
+ }
121
+ catch (e) {
122
+ return err(e);
123
+ }
124
+ });
125
+ server.tool("list_scheduled_tasks", "List Sonarr's scheduled maintenance tasks with their interval and last and next execution times.", {}, async () => {
126
+ try {
127
+ const data = (await client.get("/api/v3/system/task"));
128
+ return ok({ count: data.length, tasks: data });
129
+ }
130
+ catch (e) {
131
+ return err(e);
132
+ }
133
+ });
134
+ server.tool("get_scheduled_task", "Get a single scheduled task by id.", { id: z.number().describe("Scheduled task id") }, async ({ id }) => {
135
+ try {
136
+ return ok(await client.get(`/api/v3/system/task/${id}`));
137
+ }
138
+ catch (e) {
139
+ return err(e);
140
+ }
141
+ });
142
+ }