feat: expand API coverage with new tools, params, and 90% test threshold
This commit is contained in:
parent
8bb8e5507e
commit
fa913d1561
21 changed files with 1573 additions and 88 deletions
|
|
@ -6,6 +6,9 @@ import type {
|
|||
WatchProvidersResponse,
|
||||
CreditsResponse,
|
||||
StatsResponse,
|
||||
AutocompleteResponse,
|
||||
TrackResponse,
|
||||
ScanRequestResponse,
|
||||
} from "./types.js";
|
||||
|
||||
export class ApiError extends Error {
|
||||
|
|
@ -15,6 +18,8 @@ export class ApiError extends Error {
|
|||
) {
|
||||
const messages: Record<number, string> = {
|
||||
400: "Bad request — check that all parameters are valid.",
|
||||
401: "API key required or invalid. Set TORRENTCLAW_API_KEY environment variable.",
|
||||
403: "Insufficient API tier or endpoint not allowed for this key.",
|
||||
404: "Not found — the requested content ID does not exist. Use search_content to find valid IDs.",
|
||||
429: "Rate limit exceeded. Wait 10-30 seconds before retrying.",
|
||||
500: "TorrentClaw server error. Try again in a moment.",
|
||||
|
|
@ -32,13 +37,16 @@ interface CacheEntry<T> {
|
|||
}
|
||||
|
||||
const DEFAULT_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
|
||||
const DEFAULT_CACHE_MAX_SIZE = 200;
|
||||
|
||||
export class ResponseCache {
|
||||
private store = new Map<string, CacheEntry<unknown>>();
|
||||
private ttl: number;
|
||||
private maxSize: number;
|
||||
|
||||
constructor(ttl = DEFAULT_CACHE_TTL) {
|
||||
constructor(ttl = DEFAULT_CACHE_TTL, maxSize = DEFAULT_CACHE_MAX_SIZE) {
|
||||
this.ttl = ttl;
|
||||
this.maxSize = maxSize;
|
||||
}
|
||||
|
||||
get<T>(key: string): T | undefined {
|
||||
|
|
@ -48,10 +56,21 @@ export class ResponseCache {
|
|||
this.store.delete(key);
|
||||
return undefined;
|
||||
}
|
||||
// Move to end for LRU ordering (Map preserves insertion order)
|
||||
this.store.delete(key);
|
||||
this.store.set(key, entry);
|
||||
return entry.data as T;
|
||||
}
|
||||
|
||||
set<T>(key: string, data: T): void {
|
||||
// Delete first to refresh position if key exists
|
||||
this.store.delete(key);
|
||||
// Evict oldest entries if at capacity
|
||||
while (this.store.size >= this.maxSize) {
|
||||
const oldest = this.store.keys().next().value;
|
||||
if (oldest !== undefined) this.store.delete(oldest);
|
||||
else break;
|
||||
}
|
||||
this.store.set(key, { data, expiresAt: Date.now() + this.ttl });
|
||||
}
|
||||
|
||||
|
|
@ -73,6 +92,12 @@ export interface SearchParams {
|
|||
min_rating?: number;
|
||||
quality?: string;
|
||||
language?: string;
|
||||
audio?: string;
|
||||
hdr?: string;
|
||||
availability?: string;
|
||||
locale?: string;
|
||||
season?: number;
|
||||
episode?: number;
|
||||
sort?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
|
|
@ -82,14 +107,59 @@ export interface SearchParams {
|
|||
export class TorrentClawClient {
|
||||
private baseUrl: string;
|
||||
private userAgent: string;
|
||||
private apiKey: string | undefined;
|
||||
readonly cache: ResponseCache;
|
||||
|
||||
constructor(cacheTtl?: number) {
|
||||
this.baseUrl = config.apiUrl;
|
||||
this.userAgent = `torrentclaw-mcp/${config.version}`;
|
||||
this.apiKey = config.apiKey;
|
||||
this.cache = new ResponseCache(cacheTtl);
|
||||
}
|
||||
|
||||
private buildHeaders(): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
"User-Agent": this.userAgent,
|
||||
Accept: "application/json",
|
||||
"X-Search-Source": "mcp",
|
||||
};
|
||||
if (this.apiKey) {
|
||||
headers["Authorization"] = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
private async handleErrorResponse(response: Response): Promise<never> {
|
||||
let body = "";
|
||||
if (response.status >= 400 && response.status < 500) {
|
||||
try {
|
||||
body = (await response.text()).slice(0, 200);
|
||||
} catch {}
|
||||
}
|
||||
throw new ApiError(response.status, body);
|
||||
}
|
||||
|
||||
private async fetchWithRetry(
|
||||
url: string,
|
||||
init: RequestInit,
|
||||
): Promise<Response> {
|
||||
const MAX_RETRIES = 2;
|
||||
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
||||
const response = await fetch(url, {
|
||||
...init,
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
if (response.status === 429 && attempt < MAX_RETRIES) {
|
||||
const delay = Math.min(1000 * 2 ** attempt, 10_000);
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
continue;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
// Unreachable, but TypeScript needs it
|
||||
throw new ApiError(429, "");
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
path: string,
|
||||
params?: Record<string, string | number | undefined>,
|
||||
|
|
@ -107,24 +177,12 @@ export class TorrentClawClient {
|
|||
const cached = this.cache.get<T>(cacheKey);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
const response = await fetch(url.toString(), {
|
||||
headers: {
|
||||
"User-Agent": this.userAgent,
|
||||
Accept: "application/json",
|
||||
"X-Search-Source": "mcp",
|
||||
},
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
const response = await this.fetchWithRetry(url.toString(), {
|
||||
headers: this.buildHeaders(),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// Only expose body for 4xx (client errors); omit for 5xx (may leak internals)
|
||||
let body = "";
|
||||
if (response.status >= 400 && response.status < 500) {
|
||||
try {
|
||||
body = (await response.text()).slice(0, 200);
|
||||
} catch {}
|
||||
}
|
||||
throw new ApiError(response.status, body);
|
||||
await this.handleErrorResponse(response);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as T;
|
||||
|
|
@ -132,6 +190,27 @@ export class TorrentClawClient {
|
|||
return data;
|
||||
}
|
||||
|
||||
private async postRequest<T>(
|
||||
path: string,
|
||||
body: Record<string, unknown>,
|
||||
): Promise<T> {
|
||||
const url = new URL(path, this.baseUrl);
|
||||
const headers = this.buildHeaders();
|
||||
headers["Content-Type"] = "application/json";
|
||||
|
||||
const response = await this.fetchWithRetry(url.toString(), {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
await this.handleErrorResponse(response);
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
async search(params: SearchParams): Promise<SearchResponse> {
|
||||
return this.request<SearchResponse>("/api/v1/search", {
|
||||
q: params.query,
|
||||
|
|
@ -142,6 +221,12 @@ export class TorrentClawClient {
|
|||
min_rating: params.min_rating,
|
||||
quality: params.quality,
|
||||
lang: params.language,
|
||||
audio: params.audio,
|
||||
hdr: params.hdr,
|
||||
availability: params.availability,
|
||||
locale: params.locale,
|
||||
season: params.season,
|
||||
episode: params.episode,
|
||||
sort: params.sort,
|
||||
page: params.page,
|
||||
limit: params.limit,
|
||||
|
|
@ -149,12 +234,34 @@ export class TorrentClawClient {
|
|||
});
|
||||
}
|
||||
|
||||
async getPopular(limit?: number, page?: number): Promise<PopularResponse> {
|
||||
return this.request<PopularResponse>("/api/v1/popular", { limit, page });
|
||||
async autocomplete(query: string): Promise<AutocompleteResponse> {
|
||||
return this.request<AutocompleteResponse>("/api/v1/autocomplete", {
|
||||
q: query,
|
||||
});
|
||||
}
|
||||
|
||||
async getRecent(limit?: number, page?: number): Promise<RecentResponse> {
|
||||
return this.request<RecentResponse>("/api/v1/recent", { limit, page });
|
||||
async getPopular(
|
||||
limit?: number,
|
||||
page?: number,
|
||||
locale?: string,
|
||||
): Promise<PopularResponse> {
|
||||
return this.request<PopularResponse>("/api/v1/popular", {
|
||||
limit,
|
||||
page,
|
||||
locale,
|
||||
});
|
||||
}
|
||||
|
||||
async getRecent(
|
||||
limit?: number,
|
||||
page?: number,
|
||||
locale?: string,
|
||||
): Promise<RecentResponse> {
|
||||
return this.request<RecentResponse>("/api/v1/recent", {
|
||||
limit,
|
||||
page,
|
||||
locale,
|
||||
});
|
||||
}
|
||||
|
||||
async getWatchProviders(
|
||||
|
|
@ -177,6 +284,33 @@ export class TorrentClawClient {
|
|||
return this.request<StatsResponse>("/api/v1/stats");
|
||||
}
|
||||
|
||||
async track(
|
||||
infoHash: string,
|
||||
action: "magnet" | "torrent_download" | "copy",
|
||||
): Promise<TrackResponse> {
|
||||
return this.postRequest<TrackResponse>("/api/v1/track", {
|
||||
infoHash,
|
||||
action,
|
||||
});
|
||||
}
|
||||
|
||||
async submitScanRequest(
|
||||
infoHash: string,
|
||||
email: string,
|
||||
): Promise<ScanRequestResponse> {
|
||||
return this.postRequest<ScanRequestResponse>("/api/v1/scan-request", {
|
||||
infoHash,
|
||||
email,
|
||||
website: "",
|
||||
});
|
||||
}
|
||||
|
||||
async getScanStatus(infoHash: string): Promise<ScanRequestResponse> {
|
||||
return this.request<ScanRequestResponse>(
|
||||
`/api/v1/scan-request/${infoHash}`,
|
||||
);
|
||||
}
|
||||
|
||||
getTorrentDownloadUrl(infoHash: string): string {
|
||||
return `${this.baseUrl}/api/v1/torrent/${infoHash}`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,14 +24,11 @@ export function validateApiUrl(raw: string): string {
|
|||
);
|
||||
}
|
||||
|
||||
const allowPrivate = process.env.TORRENTCLAW_ALLOW_PRIVATE === "true";
|
||||
if (!allowPrivate) {
|
||||
const hostname = parsed.hostname.replace(/^\[|\]$/g, "");
|
||||
if (PRIVATE_IP_PATTERNS.some((re) => re.test(hostname))) {
|
||||
throw new Error(
|
||||
`Invalid TORRENTCLAW_API_URL: private/reserved addresses not allowed. Set TORRENTCLAW_ALLOW_PRIVATE=true for self-hosted setups.`,
|
||||
);
|
||||
}
|
||||
const hostname = parsed.hostname.replace(/^\[|\]$/g, "");
|
||||
if (PRIVATE_IP_PATTERNS.some((re) => re.test(hostname))) {
|
||||
throw new Error(
|
||||
`Invalid TORRENTCLAW_API_URL: private/reserved addresses not allowed`,
|
||||
);
|
||||
}
|
||||
|
||||
return raw;
|
||||
|
|
@ -41,5 +38,6 @@ export const config = {
|
|||
apiUrl: validateApiUrl(
|
||||
process.env.TORRENTCLAW_API_URL || "https://torrentclaw.com",
|
||||
),
|
||||
apiKey: process.env.TORRENTCLAW_API_KEY || undefined,
|
||||
version: process.env.npm_package_version || "1.0.0",
|
||||
} as const;
|
||||
|
|
|
|||
|
|
@ -42,13 +42,42 @@ function formatTorrent(t: TorrentInfo, compact?: boolean): string {
|
|||
|
||||
let line = ` - ${label} (${size}) | ${seeds}`;
|
||||
if (score) line += ` | ${score}`;
|
||||
|
||||
if (t.season != null) {
|
||||
const ep =
|
||||
t.episode != null ? `E${String(t.episode).padStart(2, "0")}` : "";
|
||||
line += ` | S${String(t.season).padStart(2, "0")}${ep}`;
|
||||
}
|
||||
|
||||
line += `\n Info hash: ${t.infoHash}`;
|
||||
if (compact) {
|
||||
// Short magnet (hash only, no trackers) — still clickable, saves ~200 chars per torrent
|
||||
line += `\n Magnet: magnet:?xt=urn:btih:${t.infoHash}`;
|
||||
} else if (t.magnetUrl) {
|
||||
line += `\n Magnet: ${t.magnetUrl}`;
|
||||
}
|
||||
if (t.torrentUrl) {
|
||||
line += `\n Torrent: ${t.torrentUrl}`;
|
||||
}
|
||||
|
||||
// Audio/subtitle track summary (from scanned torrents)
|
||||
if (t.audioTracks && t.audioTracks.length > 0) {
|
||||
const langs = t.audioTracks
|
||||
.map((a) => a.lang || "?")
|
||||
.filter((v, i, arr) => arr.indexOf(v) === i);
|
||||
line += `\n Audio: ${langs.join(", ")}`;
|
||||
const codecs = t.audioTracks
|
||||
.map((a) => a.codec)
|
||||
.filter((v): v is string => v != null)
|
||||
.filter((v, i, arr) => arr.indexOf(v) === i);
|
||||
if (codecs.length > 0) line += ` (${codecs.join(", ")})`;
|
||||
}
|
||||
if (t.subtitleTracks && t.subtitleTracks.length > 0) {
|
||||
const langs = t.subtitleTracks
|
||||
.map((s) => s.lang || "?")
|
||||
.filter((v, i, arr) => arr.indexOf(v) === i);
|
||||
line += `\n Subtitles: ${langs.join(", ")}`;
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
|
|
@ -99,6 +128,7 @@ function formatResult(
|
|||
` Content ID: ${r.id} — use with get_watch_providers(content_id=${r.id}) or get_credits(content_id=${r.id})`,
|
||||
);
|
||||
if (r.imdbId) lines.push(` IMDb: ${r.imdbId}`);
|
||||
if (r.contentUrl) lines.push(` URL: ${r.contentUrl}`);
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
|
@ -111,9 +141,21 @@ export function formatSearchResults(
|
|||
return "No results found. Try: (1) a shorter or alternate title, (2) removing filters like quality or year, (3) checking spelling. You can also try get_popular or get_recent to browse available content.";
|
||||
}
|
||||
|
||||
const header = `Found ${data.total} results (page ${data.page}, showing ${data.results.length}):`;
|
||||
const headerParts = [
|
||||
`Found ${data.total} results (page ${data.page}, showing ${data.results.length}):`,
|
||||
];
|
||||
if (data.parsedSeason != null) {
|
||||
const ep =
|
||||
data.parsedEpisode != null
|
||||
? `E${String(data.parsedEpisode).padStart(2, "0")}`
|
||||
: "";
|
||||
headerParts.push(
|
||||
`Detected season/episode: S${String(data.parsedSeason).padStart(2, "0")}${ep}`,
|
||||
);
|
||||
}
|
||||
|
||||
const results = data.results.map((r, i) => formatResult(r, i + 1, opts));
|
||||
return [header, "", ...results].join("\n");
|
||||
return [...headerParts, "", ...results].join("\n");
|
||||
}
|
||||
|
||||
function formatPopularItem(item: PopularItem, index: number): string {
|
||||
|
|
|
|||
|
|
@ -9,6 +9,9 @@ import { registerGetRecent } from "./tools/get-recent.js";
|
|||
import { registerGetWatchProviders } from "./tools/get-watch-providers.js";
|
||||
import { registerGetCredits } from "./tools/get-credits.js";
|
||||
import { registerGetTorrentUrl } from "./tools/get-torrent-url.js";
|
||||
import { registerAutocomplete } from "./tools/autocomplete.js";
|
||||
import { registerTrackInteraction } from "./tools/track-interaction.js";
|
||||
import { registerScanRequest } from "./tools/scan-request.js";
|
||||
import { registerStatsResource } from "./resources/stats.js";
|
||||
import { registerPrompts } from "./prompts.js";
|
||||
|
||||
|
|
@ -18,16 +21,19 @@ const server = new McpServer({
|
|||
name: "torrentclaw",
|
||||
version: config.version,
|
||||
description:
|
||||
"Search and discover movies and TV shows with torrent downloads, streaming availability, and cast/crew metadata. Start with search_content to find content, then use get_watch_providers or get_credits with the content_id. Use get_popular/get_recent to browse (no torrents — search for a title to get torrents).",
|
||||
"Search and discover movies and TV shows with torrent downloads, streaming availability, and cast/crew metadata. Start with autocomplete to validate titles, then search_content for full results with torrents. Use get_watch_providers or get_credits with the content_id. Use get_popular/get_recent to browse. Track interactions with track_interaction and request quality scans with submit_scan_request.",
|
||||
});
|
||||
|
||||
// Register tools
|
||||
registerSearchContent(server, client);
|
||||
registerAutocomplete(server, client);
|
||||
registerGetPopular(server, client);
|
||||
registerGetRecent(server, client);
|
||||
registerGetWatchProviders(server, client);
|
||||
registerGetCredits(server, client);
|
||||
registerGetTorrentUrl(server, client);
|
||||
registerTrackInteraction(server, client);
|
||||
registerScanRequest(server, client);
|
||||
|
||||
// Register resources
|
||||
registerStatsResource(server, client);
|
||||
|
|
|
|||
60
src/tools/autocomplete.ts
Normal file
60
src/tools/autocomplete.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
import type { TorrentClawClient } from "../api-client.js";
|
||||
import { ApiError } from "../api-client.js";
|
||||
|
||||
export function registerAutocomplete(
|
||||
server: McpServer,
|
||||
client: TorrentClawClient,
|
||||
): void {
|
||||
server.tool(
|
||||
"autocomplete",
|
||||
"Get type-ahead search suggestions for movies and TV shows. Use this to validate or disambiguate a title before calling search_content. Returns up to 8 suggestions with id, title, year, and content type. Much faster than a full search.",
|
||||
{
|
||||
query: z
|
||||
.string()
|
||||
.min(2)
|
||||
.max(200)
|
||||
.refine(
|
||||
(q) => !/[\x00-\x08\x0B-\x0C\x0E-\x1F]/.test(q),
|
||||
"Query contains invalid control characters",
|
||||
)
|
||||
.describe(
|
||||
"Partial title to get suggestions for (min 2 chars). E.g. 'break' → 'Breaking Bad', 'The Break-Up'.",
|
||||
),
|
||||
},
|
||||
async (params) => {
|
||||
try {
|
||||
const data = await client.autocomplete(params.query);
|
||||
if (data.suggestions.length === 0) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `No suggestions for "${params.query}". Try search_content for a full search.`,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
const lines = data.suggestions.map((s, i) => {
|
||||
const yearStr = s.year ? ` (${s.year})` : "";
|
||||
return `${i + 1}. ${s.title}${yearStr} [${s.contentType}] — ID: ${s.id}`;
|
||||
});
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Suggestions for "${params.query}":\n${lines.join("\n")}`,
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof ApiError
|
||||
? `TorrentClaw API error (${error.status}): ${error.message}`
|
||||
: `Request failed: ${error instanceof Error ? error.message : "Unknown error"}`;
|
||||
return { content: [{ type: "text", text: message }], isError: true };
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
|
@ -18,17 +18,28 @@ export function registerGetPopular(
|
|||
.min(1)
|
||||
.max(24)
|
||||
.optional()
|
||||
.describe("Number of items (default: 10)"),
|
||||
.describe("Number of items (default: 12)"),
|
||||
page: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Page number (default: 1)"),
|
||||
locale: z
|
||||
.string()
|
||||
.regex(/^[a-z]{2}$/, "Must be a lowercase 2-letter language code")
|
||||
.optional()
|
||||
.describe(
|
||||
"Locale for translated titles (e.g. 'es' for Spanish, 'fr' for French). If omitted, returns English.",
|
||||
),
|
||||
},
|
||||
async (params) => {
|
||||
try {
|
||||
const data = await client.getPopular(params.limit ?? 10, params.page);
|
||||
const data = await client.getPopular(
|
||||
params.limit ?? 12,
|
||||
params.page,
|
||||
params.locale,
|
||||
);
|
||||
return {
|
||||
content: [{ type: "text", text: formatPopularResults(data) }],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -18,17 +18,28 @@ export function registerGetRecent(
|
|||
.min(1)
|
||||
.max(24)
|
||||
.optional()
|
||||
.describe("Number of items (default: 10)"),
|
||||
.describe("Number of items (default: 12)"),
|
||||
page: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Page number (default: 1)"),
|
||||
locale: z
|
||||
.string()
|
||||
.regex(/^[a-z]{2}$/, "Must be a lowercase 2-letter language code")
|
||||
.optional()
|
||||
.describe(
|
||||
"Locale for translated titles (e.g. 'es' for Spanish, 'fr' for French). If omitted, returns English.",
|
||||
),
|
||||
},
|
||||
async (params) => {
|
||||
try {
|
||||
const data = await client.getRecent(params.limit ?? 10, params.page);
|
||||
const data = await client.getRecent(
|
||||
params.limit ?? 12,
|
||||
params.page,
|
||||
params.locale,
|
||||
);
|
||||
return {
|
||||
content: [{ type: "text", text: formatRecentResults(data) }],
|
||||
};
|
||||
|
|
|
|||
77
src/tools/scan-request.ts
Normal file
77
src/tools/scan-request.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
import type { TorrentClawClient } from "../api-client.js";
|
||||
import { ApiError } from "../api-client.js";
|
||||
|
||||
export function registerScanRequest(
|
||||
server: McpServer,
|
||||
client: TorrentClawClient,
|
||||
): void {
|
||||
server.tool(
|
||||
"submit_scan_request",
|
||||
"Submit a torrent for audio/video quality analysis (codec, tracks, resolution, HDR). Use when the user wants to know the exact media specs of a torrent before downloading. Results are not instant — use get_scan_status to check progress. Rate limited to 5 requests per hour.",
|
||||
{
|
||||
info_hash: z
|
||||
.string()
|
||||
.regex(/^[a-fA-F0-9]{40}$/)
|
||||
.describe("40-character hex torrent info_hash to scan"),
|
||||
email: z
|
||||
.string()
|
||||
.email()
|
||||
.max(200)
|
||||
.describe("Email address for scan completion notification"),
|
||||
},
|
||||
async (params) => {
|
||||
try {
|
||||
const data = await client.submitScanRequest(
|
||||
params.info_hash.toLowerCase(),
|
||||
params.email,
|
||||
);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Scan request submitted for ${params.info_hash.toLowerCase()}.\nStatus: ${data.status}\nUse get_scan_status(info_hash="${params.info_hash.toLowerCase()}") to check progress.`,
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof ApiError
|
||||
? `TorrentClaw API error (${error.status}): ${error.message}`
|
||||
: `Request failed: ${error instanceof Error ? error.message : "Unknown error"}`;
|
||||
return { content: [{ type: "text", text: message }], isError: true };
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"get_scan_status",
|
||||
"Check the status of a torrent audio/video scan request. Returns the current scan status (pending, scanning, completed, failed). Use after submit_scan_request.",
|
||||
{
|
||||
info_hash: z
|
||||
.string()
|
||||
.regex(/^[a-fA-F0-9]{40}$/)
|
||||
.describe("40-character hex torrent info_hash to check"),
|
||||
},
|
||||
async (params) => {
|
||||
try {
|
||||
const data = await client.getScanStatus(params.info_hash.toLowerCase());
|
||||
const lines = [`Scan status for ${params.info_hash.toLowerCase()}:`];
|
||||
lines.push(` Status: ${data.status}`);
|
||||
if (data.source) lines.push(` Source: ${data.source}`);
|
||||
if (data.createdAt) lines.push(` Submitted: ${data.createdAt}`);
|
||||
if (data.completedAt) lines.push(` Completed: ${data.completedAt}`);
|
||||
return {
|
||||
content: [{ type: "text", text: lines.join("\n") }],
|
||||
};
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof ApiError
|
||||
? `TorrentClaw API error (${error.status}): ${error.message}`
|
||||
: `Request failed: ${error instanceof Error ? error.message : "Unknown error"}`;
|
||||
return { content: [{ type: "text", text: message }], isError: true };
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
|
@ -10,7 +10,7 @@ export function registerSearchContent(
|
|||
): void {
|
||||
server.tool(
|
||||
"search_content",
|
||||
"Search for movies and TV shows by title, genre, year, rating, or quality. Returns matching content with metadata (title, year, genres, IMDb/TMDB ratings) and torrent download options (magnet links, quality, seeders, file size). This is the primary tool — use it first when a user asks to find, download, or learn about a movie or TV show. Results include a content_id needed by get_watch_providers and get_credits.",
|
||||
"Search for movies and TV shows by title, genre, year, rating, or quality. Returns matching content with metadata (title, year, genres, IMDb/TMDB ratings) and torrent download options (magnet links, quality, seeders, file size). This is the primary tool — use it first when a user asks to find, download, or learn about a movie or TV show. Results include a content_id needed by get_watch_providers and get_credits. For TV shows, you can filter by season/episode. Season/episode can also be auto-detected from the query (e.g. 'Bluey s01e05').",
|
||||
{
|
||||
query: z
|
||||
.string()
|
||||
|
|
@ -21,7 +21,7 @@ export function registerSearchContent(
|
|||
"Query contains invalid control characters",
|
||||
)
|
||||
.describe(
|
||||
"Search query — typically a movie or TV show title (e.g. 'The Matrix', 'Breaking Bad'). Supports partial matches.",
|
||||
"Search query — typically a movie or TV show title (e.g. 'The Matrix', 'Breaking Bad'). Supports partial matches. Season/episode can be included in query (e.g. 'Bluey s01e05').",
|
||||
),
|
||||
type: z
|
||||
.enum(["movie", "show"])
|
||||
|
|
@ -62,10 +62,59 @@ export function registerSearchContent(
|
|||
.describe("Filter torrents by resolution"),
|
||||
language: z
|
||||
.string()
|
||||
.regex(
|
||||
/^[a-z]{2}$/,
|
||||
"Must be a lowercase 2-letter ISO 639-1 language code",
|
||||
)
|
||||
.optional()
|
||||
.describe(
|
||||
"ISO 639-1 language code to filter torrents (e.g. 'en' for English, 'es' for Spanish, 'fr' for French). Lowercase 2-letter code.",
|
||||
),
|
||||
audio: z
|
||||
.string()
|
||||
.regex(
|
||||
/^[a-zA-Z0-9.]+$/,
|
||||
"Audio codec must contain only alphanumeric characters and dots",
|
||||
)
|
||||
.optional()
|
||||
.describe(
|
||||
"Filter torrents by audio codec (e.g. 'aac', 'flac', 'atmos', 'opus', 'dts'). Substring match.",
|
||||
),
|
||||
hdr: z
|
||||
.enum(["hdr10", "dolby_vision", "hdr10plus", "hlg"])
|
||||
.optional()
|
||||
.describe("Filter torrents by HDR format"),
|
||||
availability: z
|
||||
.enum(["all", "available", "unavailable"])
|
||||
.optional()
|
||||
.describe(
|
||||
"Filter by torrent availability: 'available' (has seeders), 'unavailable' (no seeders), 'all' (default).",
|
||||
),
|
||||
season: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(99)
|
||||
.optional()
|
||||
.describe(
|
||||
"Season number for TV shows (0-99). Use with type='show' to filter torrents for a specific season.",
|
||||
),
|
||||
episode: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(999)
|
||||
.optional()
|
||||
.describe(
|
||||
"Episode number for TV shows (0-999). Use with season to filter torrents for a specific episode.",
|
||||
),
|
||||
locale: z
|
||||
.string()
|
||||
.regex(/^[a-z]{2}$/, "Must be a lowercase 2-letter language code")
|
||||
.optional()
|
||||
.describe(
|
||||
"Locale for translated titles and overviews (e.g. 'es' for Spanish, 'fr' for French). If omitted, returns English.",
|
||||
),
|
||||
sort: z
|
||||
.enum(["relevance", "seeders", "year", "rating", "added"])
|
||||
.default("relevance")
|
||||
|
|
@ -74,16 +123,16 @@ export function registerSearchContent(
|
|||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.max(1000)
|
||||
.optional()
|
||||
.describe("Page number (default: 1)"),
|
||||
.describe("Page number (default: 1, max: 1000)"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(20)
|
||||
.max(50)
|
||||
.optional()
|
||||
.describe("Results per page (default: 10, max: 20)"),
|
||||
.describe("Results per page (default: 20, max: 50)"),
|
||||
country: z
|
||||
.string()
|
||||
.regex(
|
||||
|
|
@ -112,9 +161,15 @@ export function registerSearchContent(
|
|||
min_rating: params.min_rating,
|
||||
quality: params.quality,
|
||||
language: params.language,
|
||||
audio: params.audio,
|
||||
hdr: params.hdr,
|
||||
availability: params.availability,
|
||||
locale: params.locale,
|
||||
season: params.season,
|
||||
episode: params.episode,
|
||||
sort: params.sort,
|
||||
page: params.page,
|
||||
limit: params.limit ?? 10,
|
||||
limit: params.limit ?? 20,
|
||||
country: params.country,
|
||||
});
|
||||
return {
|
||||
|
|
|
|||
44
src/tools/track-interaction.ts
Normal file
44
src/tools/track-interaction.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
import type { TorrentClawClient } from "../api-client.js";
|
||||
import { ApiError } from "../api-client.js";
|
||||
|
||||
export function registerTrackInteraction(
|
||||
server: McpServer,
|
||||
client: TorrentClawClient,
|
||||
): void {
|
||||
server.tool(
|
||||
"track_interaction",
|
||||
"Track a user interaction with a torrent (magnet link click, .torrent download, or hash copy). Use this after presenting a magnet link or torrent URL to the user, to keep popularity stats accurate. Fire-and-forget — does not block.",
|
||||
{
|
||||
info_hash: z
|
||||
.string()
|
||||
.regex(/^[a-fA-F0-9]{40}$/)
|
||||
.describe("40-character hex torrent info_hash"),
|
||||
action: z
|
||||
.enum(["magnet", "torrent_download", "copy"])
|
||||
.describe(
|
||||
"Type of interaction: 'magnet' (clicked magnet link), 'torrent_download' (downloaded .torrent file), 'copy' (copied info hash or magnet)",
|
||||
),
|
||||
},
|
||||
async (params) => {
|
||||
try {
|
||||
await client.track(params.info_hash.toLowerCase(), params.action);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Tracked ${params.action} for ${params.info_hash.toLowerCase()}.`,
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof ApiError
|
||||
? `TorrentClaw API error (${error.status}): ${error.message}`
|
||||
: `Request failed: ${error instanceof Error ? error.message : "Unknown error"}`;
|
||||
return { content: [{ type: "text", text: message }], isError: true };
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
63
src/types.ts
63
src/types.ts
|
|
@ -1,7 +1,32 @@
|
|||
// Response types mirrored from TorrentClaw API (src/types/api.ts)
|
||||
|
||||
export interface AudioTrack {
|
||||
lang: string | null;
|
||||
codec: string | null;
|
||||
channels: string | null;
|
||||
title: string | null;
|
||||
default: boolean | null;
|
||||
}
|
||||
|
||||
export interface SubtitleTrack {
|
||||
lang: string | null;
|
||||
codec: string | null;
|
||||
title: string | null;
|
||||
forced: boolean | null;
|
||||
}
|
||||
|
||||
export interface VideoInfo {
|
||||
codec: string | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
bitDepth: number | null;
|
||||
hdr: string | null;
|
||||
frameRate: string | null;
|
||||
}
|
||||
|
||||
export interface TorrentInfo {
|
||||
infoHash: string;
|
||||
rawTitle: string | null;
|
||||
quality: string | null;
|
||||
codec: string | null;
|
||||
sourceType: string | null;
|
||||
|
|
@ -9,6 +34,7 @@ export interface TorrentInfo {
|
|||
seeders: number;
|
||||
leechers: number;
|
||||
magnetUrl: string | null;
|
||||
torrentUrl: string | null;
|
||||
source: string;
|
||||
qualityScore: number | null;
|
||||
uploadedAt: string | null;
|
||||
|
|
@ -19,6 +45,12 @@ export interface TorrentInfo {
|
|||
isProper: boolean | null;
|
||||
isRepack: boolean | null;
|
||||
isRemastered: boolean | null;
|
||||
season: number | null;
|
||||
episode: number | null;
|
||||
audioTracks: AudioTrack[] | null;
|
||||
subtitleTracks: SubtitleTrack[] | null;
|
||||
videoInfo: VideoInfo | null;
|
||||
scanStatus: string | null;
|
||||
}
|
||||
|
||||
export interface StreamingProviderItem {
|
||||
|
|
@ -49,6 +81,7 @@ export interface SearchResult {
|
|||
genres: string[] | null;
|
||||
ratingImdb: string | null;
|
||||
ratingTmdb: string | null;
|
||||
contentUrl: string | null;
|
||||
hasTorrents: boolean;
|
||||
torrents: TorrentInfo[];
|
||||
streaming?: StreamingInfo;
|
||||
|
|
@ -58,9 +91,39 @@ export interface SearchResponse {
|
|||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
parsedSeason?: number;
|
||||
parsedEpisode?: number;
|
||||
results: SearchResult[];
|
||||
}
|
||||
|
||||
export interface AutocompleteItem {
|
||||
id: number;
|
||||
title: string;
|
||||
year: number | null;
|
||||
contentType: string;
|
||||
posterUrl: string | null;
|
||||
}
|
||||
|
||||
export interface AutocompleteResponse {
|
||||
suggestions: AutocompleteItem[];
|
||||
}
|
||||
|
||||
export interface TrackRequest {
|
||||
infoHash: string;
|
||||
action: "magnet" | "torrent_download" | "copy";
|
||||
}
|
||||
|
||||
export interface TrackResponse {
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export interface ScanRequestResponse {
|
||||
status: string;
|
||||
source?: string;
|
||||
createdAt?: string;
|
||||
completedAt?: string;
|
||||
}
|
||||
|
||||
export interface PopularItem {
|
||||
id: number;
|
||||
title: string;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue