feat: expand Emby MCP with library audits, image previews and guarded FSK actions (1.4.0)
This commit is contained in:
1 parent
d586bce078
commit
4c9b8a230d
23 files changed
+1438
-20
No files matched your search
@@ -4,9 +4,13 @@
|
||||
|
||||
## Status
|
||||
|
||||
Version **1.3.0** ergänzt die paginierte Serien-Bestandsabfrage. 18 Werkzeuge; die bisherigen 17 bleiben kompatibel. Build und lokale Tests erfolgreich, offizielle Emby-Sammelabfragen live geprüft. Version 1.3.0 wurde am 11.10.2026 installiert und anschließend über MCP live erfolgreich geprüft (278 Episoden, vollständige Pagination).
|
||||
Version **1.4.0**: 37 MCP-Werkzeuge für Serienbestand, kombinierte Suche, Sammeldetails, Bild-/Sprach-/Metadaten-/FSK-Prüfung, Provider-Folgenabgleich, Änderungsvergleich und Diagnosen. Gezielte Schreibaktionen sind standardmäßig deaktiviert und starten als Vorschau.
|
||||
|
||||
Details, Testnachweise, Installation und Rollback: [Serienbestand](docs/series-inventory.md).
|
||||
1.3.0 läuft seit 11.10.2026 live erfolgreich (278 Episoden, vollständige Pagination). **1.4.0 ist gebaut und lokal geprüft; Aktivierung und neuer MCP-Livetest warten auf Freigabe für einen kontrollierten Neustart.**
|
||||
|
||||
- [Neue Werkzeuge, Bildprüfung, FSK-Ablauf und Testgrenzen](docs/advanced-tools.md)
|
||||
- [Serienbestand und bisherige Live-Abnahme](docs/series-inventory.md)
|
||||
- [Installierbares Paket 1.4.0](releases/1.4.0/INSTALL.md)
|
||||
|
||||
## Konzept
|
||||
|
||||
@@ -20,7 +24,7 @@ eMCPy-Plugin (läuft IN Emby Server)
|
||||
Emby-Server (Bibliothek, Playback, User, Tasks, …)
|
||||
```
|
||||
|
||||
### Implementierte MCP-Tools
|
||||
### Bisherige MCP-Tools (weiterhin verfügbar)
|
||||
|
||||
| Tool | Beschreibung |
|
||||
|---|---|
|
||||
@@ -36,6 +40,8 @@ Emby-Server (Bibliothek, Playback, User, Tasks, …)
|
||||
| `emby_library_stats`, `emby_library_browse`, `emby_library_folders` | Bibliotheksstatistik, Blättern, Bibliotheken |
|
||||
| `emby_recently_added`, `emby_next_up`, `emby_random`, `emby_top_rated`, `emby_missing_metadata` | Weitere Bibliotheksabfragen |
|
||||
|
||||
Die 19 neuen Werkzeuge sind vollständig in [advanced-tools.md](docs/advanced-tools.md) beschrieben.
|
||||
|
||||
## Emby-Plugin-Grundlagen (Recherche)
|
||||
|
||||
### Wie Emby-Plugins funktionieren
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# eMCPy 1.4.0 – Bibliotheksprüfung, Bilder und FSK
|
||||
|
||||
## Umfang und Status
|
||||
|
||||
19 zusätzliche Werkzeuge, insgesamt 37. Die bestehenden 18 Werkzeuge bleiben erhalten, einschließlich `emby_series_inventory`. Version 1.4.0 ist gebaut und lokal getestet. Vor Aktivierung steht der Integrationstest im laufenden Emby noch aus. Die einmalige Erlaubnis, bei der Installation von 1.3.0 eine Wiedergabe zu unterbrechen, gilt hier **nicht**.
|
||||
|
||||
| Werkzeug | Zweck |
|
||||
|---|---|
|
||||
| `emby_search_advanced` | Bibliothek, Typ, Genre, Titel, Laufzeit, Ton-/Untertitelsprache, benutzerspezifischer Gesehen-Status und Sortierung |
|
||||
| `emby_batch_details` | Bis zu 200 IDs, Gruppen basic/media/images/userdata, Medienversionen inkl. Größen, Codecs, HDR-Hinweisen und Sprachen |
|
||||
| `emby_duplicate_candidates` | Gemeinsam belegte Provider-Identitäten vergleichen; keine Gleichsetzung unterschiedlicher Schnittfassungen mit löschbaren Dubletten |
|
||||
| `emby_missing_episodes` | Lokalen Index mit Referenzepisoden der bereits eingerichteten Emby-Metadatenprovider vergleichen |
|
||||
| `emby_image_audit` | Vorhandene Bildtypen, fehlendes Primary und visuell zu prüfende Cover/Poster |
|
||||
| `emby_image_review` | Vorhandene Bilder von bis zu 20 Items als kleine MCP-Bildvorschauen |
|
||||
| `emby_track_audit` | Gewünschte Audio-/Untertitelsprache vorhanden, fehlend oder unbekannt |
|
||||
| `emby_metadata_audit` | Fehlende IDs, Titel, Bilder, Laufzeiten und Episodennummern |
|
||||
| `emby_rating_audit` | Fehlende, ausländische, unbekannte oder nicht kanonische deutsche Altersfreigaben und CustomRating-Übersteuerungen |
|
||||
| `emby_library_changes` | Seit einem Zeitpunkt hinzugefügte oder gespeicherte/geänderte Einträge |
|
||||
| `emby_inventory_snapshot` | Explizite lokale Index-Baseline und Vergleich für hinzugefügte/geänderte/verschwundene IDs |
|
||||
| `emby_users` | Explizite Benutzerwahl per ID; keine Kennwörter/Tokens |
|
||||
| `emby_server_diagnostics` | Echte Version, Dienste, Queue, Aufgabenstatus und Schreibfreigabe |
|
||||
| `emby_playback_diagnostics` | Tatsächlich von Emby gemeldete Wiedergabe-/Transcodingdaten und Gründe |
|
||||
| `emby_set_rating` | Quellenbelegte Einzelkorrektur einer deutschen Freigabe, zunächst Vorschau |
|
||||
| `emby_set_played` | Gesehen-Status eines einzelnen Items für einen expliziten Benutzer |
|
||||
| `emby_pause_session` | Genau eine überprüfte Sitzung pausieren |
|
||||
| `emby_refresh_item` | Einzelnen nichtrekursiven Metadaten-Refresh einreihen |
|
||||
| `emby_scan_library` | Rekursive Validierung einer ausgewählten Bibliothek in Embys Refresh-Queue |
|
||||
|
||||
## Pagination und Aufwand
|
||||
|
||||
Abfragen nach Bibliothek/Typ/Genre scannen höchstens `limit` Kandidaten pro Seite (Standard 100, max 200). `start` und `nextStart` beziehen sich auf diese Kandidatenliste. `totalCandidates` zählt Kandidaten, `returned` nur Treffer der aktuellen Seite; `totalMatches` bleibt unbekannt, bis der Aufrufer vollständig durchgeblättert hat. **Eine leere Trefferseite kann `hasMore: true` haben.** Nicht vorzeitig aufhören.
|
||||
|
||||
`inventoryRevision` der ersten Seite in `expectedRevision` weitergeben. Geänderte ID-Reihenfolge/-Menge wird erkannt; reine Metadatenänderungen sind kein transaktionaler Snapshot. Suche sortiert nach id/title/dateCreated/runtime/rating; wiederholte Gleichstände werden durch die Bestandskennung überwacht. Dubletten laden Medienquellen ebenfalls in Batches (kein Einzelaufruf je Item) und nutzen Gruppenseiten (`total`) plus begrenzte Mitglieder pro Gruppe (`memberStart`, `memberLimit`, `memberHasMore`).
|
||||
|
||||
Maximal 100000 Kandidaten pro Abfrage. Bei mehr Items muss eingegrenzt werden; keine still abgeschnittenen Listen. DTOs werden in Sammelaufrufen für maximal 200 Items erstellt. Dublettensuche und explizite Snapshots müssen den eingegrenzten Index vollständig in solchen Batches lesen und sind entsprechend teurer; keine Mediendateien werden gescannt/gehasht. Bildprüfung kann lokale Bildheader lesen, Vorschauen erzeugen normale Emby-Bildcaches.
|
||||
|
||||
## Dokumentationen: Cover oder Filmstandbild?
|
||||
|
||||
1. `emby_library_folders` → eindeutige ID von „Dokumentationen“ wählen (hier aktuell `9`, nicht fest im Code).
|
||||
2. `emby_image_audit {"libraryId":"9","limit":100}` seitenweise durchlaufen.
|
||||
3. Problemkandidaten: fehlendes Primary, unbekannte Maße, querformatiges Primary bei Nicht-Episoden. `onlyProblems:false` liefert auch andere Bilder.
|
||||
4. `emby_image_review {"ids":["…","…"]}` liefert bis zu 20 Vorschauen, jeweils mit Item-ID und Titel. Das aufrufende Modell benötigt Bildverständnis; Text-only-Clients erhalten keine automatische Klassifikation.
|
||||
|
||||
**Wichtige Grenze:** Emby speichert am ItemImageInfo keinen zuverlässigen Erzeuger/Provider. Screen Grabber kann genauso ein Primary erzeugen wie ein Posterprovider. `origin` ist daher `unknown`, `screenshotConfirmed` bleibt `null`. Querformat, Dateiname oder „Primary vorhanden“ sind kein Herkunftsbeweis. Auch ein Hochformat kann ein zugeschnittenes Standbild sein. Episoden haben oft absichtlich querformatige Stills; sie werden nicht pauschal als fehlerhaft markiert. Eine visuelle Einschätzung ist als solche zu kennzeichnen.
|
||||
|
||||
Fehlende Maße werden mit `IImageProcessor.GetImageSize` gelesen. Vorschauen sind maximal 768×768, 1 MiB je Bild und 8 MiB pro Aufruf. Originalbilder werden nicht ersetzt. Fehlende/nicht lesbare Bilder ergeben pro Item einen Status. Kein Download beliebiger URLs, keine neuen Screenshots aus Videodateien. API-Quellen/Medien-URLs werden ohne Credentials, Query und Fragment ausgegeben.
|
||||
|
||||
## FSK-Arbeitsablauf
|
||||
|
||||
```json
|
||||
{"libraryId":"3","types":["Movie"],"limit":100}
|
||||
```
|
||||
|
||||
An `emby_rating_audit` übergeben. Die Antwort enthält `acceptedGermanRatings` direkt aus `ILocalizationManager.GetParentalRatings("DE")` und die paginierte `page`. Live bestätigt: **FSK-0/6/12/16/18** und **DE-0/6/12/16/18**. Formatklassifikation allein heißt nicht, dass ein nichtkanonischer Wert vom Server erkannt wird; dafür gibt es `officialRatingRecognized`.
|
||||
|
||||
Das aufrufende Modell recherchiert mit seinen eigenen Webwerkzeugen. Titel, Originaltitel, Produktionsjahr, Provider-IDs und konkrete Fassung/Medium berücksichtigen. Eine US-/UK-Freigabe darf nicht in FSK umgerechnet werden. Bei unklarer Fassung nichts setzen. Das MCP enthält keinen Browser und bestätigt die Quelle nicht selbst.
|
||||
|
||||
Vorschau mit `emby_set_rating`:
|
||||
|
||||
```json
|
||||
{
|
||||
"id":"12345",
|
||||
"rating":"FSK-12",
|
||||
"expectedOfficialRating":"PG-13",
|
||||
"expectedCustomRating":null,
|
||||
"sourceUrl":"https://www.fsk.de/…",
|
||||
"evidence":"Recherchierter Beleg für Titel, Jahr und konkrete Fassung/Medium.",
|
||||
"dryRun":true
|
||||
}
|
||||
```
|
||||
|
||||
Das Beispiel enthält Platzhalter, keinen echten Freigabenachweis. Ausführen erst mit `dryRun:false`, `confirm:true`, aktivierter Schreibfreigabe und gesetztem MCP-API-Key. Bisherige Werte müssen exakt übereinstimmen, sonst Abbruch. Schreibrechte umfassen Movie/Series/Season/Episode/Video; keine Benutzer-/Serverkonfiguration.
|
||||
|
||||
- `CustomRating` bleibt standardmäßig erhalten und kann den normalen Wert übersteuern. Nur `clearCustomRating:true` entfernt es ausdrücklich. Beide bisherigen Werte werden geprüft.
|
||||
- `lockField:true` sperrt OfficialRating zusätzlich gegen spätere Refreshs; Standard false. Vorhandene Sperren bleiben bestehen.
|
||||
- `effectiveRating` beschreibt nur die expliziten Item-Werte; geerbte Freigaben/Benutzerrichtlinien sind nicht vollständig ausgewertet (`inheritedRatingEvaluated:false`).
|
||||
- HTTPS-Quellen mit öffentlichen Dokument-/Suchparametern sind erlaubt, Credentials/Token-Parameter nicht. Quelle/Begründung werden als **vom Aufrufer geliefert, nicht unabhängig verifiziert** markiert.
|
||||
- Protokoll unter Emby `data/emcpy/actions.jsonl`; Rotation bei 1 MiB, höchstens eine vorherige Datei. Enthält vorherige/neue Werte, Beleg und Status, keine API-Keys. Ein Eintrag vor dem Save erlaubt bei unklarem Fehler gezieltes Nachprüfen. Ein Loggingfehler nach erfolgreichem Save wird als `saved:true, journalComplete:false` gemeldet und darf nicht zu blindem Wiederholen führen.
|
||||
- Rücknahme: vorherige Freigabe anhand des Journals über Embys normalen Metadateneditor zurücksetzen. Das Set-Werkzeug selbst akzeptiert bewusst nur deutsche Freigaben; es ist kein allgemeiner Metadateneditor.
|
||||
|
||||
## Andere Funktionen und Grenzen
|
||||
|
||||
**Folgenabgleich:** `IProviderManager.GetAllEpisodes` nutzt bestehende Emby-Provider samt dort verwalteten Zugangsdaten. Keine neue externe Anbindung oder Schlüsselkopie. Kann Provider-Netzwerkzugriff auslösen. Leere Providerantwort bedeutet unbekannt, nicht „alles vorhanden“. Provider-ID-Treffer und reine Nummerntreffer werden getrennt gezählt (`matchedByProvider`, `matchedByNumber`). Mehrfachepisoden über IndexNumberEnd, zukünftige Folgen und unnummerierte Einträge werden berücksichtigt. DVD-/Aired-Reihenfolgen, unvollständige Providerlisten und nicht indexierte Dateien bleiben Grenzen; Ausgabe sind fehlende **Kandidaten**, keine garantierte Komplettheitsbescheinigung.
|
||||
|
||||
**Sprachen:** Deutsch de/ger/deu wird normalisiert, ebenso en/eng und fr/fre/fra. Nicht bezeichnete Tonspuren sind unbekannt, nicht automatisch fremdsprachig. Fehlende Untertitelspuren beweisen keine eingebrannten Untertitel; dieser Status bleibt unbekannt.
|
||||
|
||||
**Versionen:** Gemeinsame Provider-IDs erzeugen Vergleichskandidaten, keine Löschentscheidung. Mehrere Medienquellen innerhalb eines einzigen Emby-Items werden ebenfalls als Versionsgruppe ausgewiesen. Eine Gruppe kann unter mehreren IDs erscheinen. Medienversionen und deren Qualitätsmerkmale mit `emby_batch_details` vergleichen; kein pauschales „größer ist besser“ oder Gleichsetzen unterschiedlicher Fassungen.
|
||||
|
||||
**Snapshots:** `capture` legt pro Bibliothek eine kleine JSON-Baseline im Plugin-Datenordner an; erneutes Erfassen benötigt `replace:true`. `compare` verändert die Baseline nicht. Maximal 20 Baselines, 100000 Einträge je Baseline. Kein Timer und keine Mediendatei-Sicherung. „removed_from_emby_index“ bedeutet nur aus dem Index verschwunden, nicht physisch gelöscht. Dies ist explizite interne Inventarverwaltung und funktioniert auch bei deaktivierten Emby-Schreibaktionen.
|
||||
|
||||
**Aktionen:** `EnableWriteTools` ist standardmäßig false; alle fünf Emby-Schreibwerkzeuge starten als Vorschau. Pausen gelten nur für die benannte Sitzung und erwartete Item-ID, Gesehen-Status nur für benannten Benutzer/ein einzelnes Item. Refresh/Scan wird nur eingereiht; `queued` heißt nicht fertig. Bibliotheksvalidierung verwendet `ValidationOnly`; kein vollständiger Metadaten-/Bildersatz. Es gibt keine Lösch- oder Neustartwerkzeuge. Freischalten der Schreibaktionen allein startet den MCP-Listener nicht neu; nur Änderungen an Port, Key, Bind-Adresse oder Aktivierung tun dies wie zuvor.
|
||||
|
||||
## Prüfung und Aktivierung
|
||||
|
||||
- `dotnet run --project tests/eMCPy.Tests -c Release`: bestehende 132 plus 97 erweiterte Assertions (229 insgesamt). Schreibaktionen ausschließlich mit SDK-Testdoubles; keine realen Altersfreigaben/Wiedergaben geändert.
|
||||
- `scripts/verify-expansion-baseline.py` live ausschließlich lesend ausgeführt: Dokumentationen enthält im gewählten Typfilter **790** Einträge. Stichprobe: 20/20 ohne OfficialRating, 19/20 mit MediaSources. Drei Bildmetadatensätze ohne Herkunft und ohne ausgegebene Maße. Das ist eine Stichprobe, keine Aussage über sämtliche 790 Freigaben.
|
||||
- `scripts/verify-live-expansion.php` ist für die Abnahme **nach genehmigter Aktivierung** vorbereitet: Version/37 Tools, Bild-/Rating-/Sprach-/Metadatenabfragen, Pagination, Sammelbilder, Diagnosen und ausschließlich Vorschauen. Keine echte Schreibaktion. Provider-Abgleich und Snapshots sind vor Aktivierung mit Testdoubles getestet, nicht als live bestätigt dargestellt.
|
||||
- Paket: `releases/1.4.0/eMCPy.dll` plus SHA-256. Installation wie in `series-inventory.md`: neues Go, keine laufenden Requests/Wiedergaben, kontrollierter Stop, bisherige DLL kurzfristig sichern, ausschließlich Plugin-DLL ersetzen, starten und prüfen. Konfiguration/Keys unverändert, kein automatisches Freischalten der Schreibaktionen.
|
||||
- Rollback: vorherige 1.3.0-DLL wieder einsetzen (ebenfalls nur nach freigegebenem Stop). Neu erzeugte Plugin-Journale/Snapshots sind unabhängig von Embys Medienbank. Nach erfolgreicher Abnahme temporäre Installationssicherung entfernen. Paket 1.3.0 bleibt im Git verfügbar.
|
||||
|
||||
## Primärquellen und SDK-Nachweise
|
||||
|
||||
- [Emby Items-Sammelabfragen und Felder](https://dev.emby.media/reference/RestAPI/ItemsService/getItems.html)
|
||||
- [Emby Bildmetadaten](https://dev.emby.media/reference/RestAPI/ImageService/getItemsByIdImages.html)
|
||||
- [Emby-Team zur Screen-Grabber-Ablage als Primary](https://emby.media/community/topic/91758-where-are-screen-grabber-thumbnail-files/)
|
||||
- [Emby unterstützte Altersfreigaben](https://dev.emby.media/reference/RestAPI/LocalizationService/getLocalizationParentalratings.html)
|
||||
- [Emby Sitzungen](https://dev.emby.media/reference/RestAPI/SessionsService.html)
|
||||
- [Emby Playstate-Kommandos](https://dev.emby.media/reference/RestAPI/SessionsService/postSessionsByIdPlayingByCommand.html)
|
||||
|
||||
Zusätzlich konkrete Signaturen/Enums aus NuGet **MediaBrowser.Server.Core 4.9.1.90** per Reflection/XML geprüft: GetInternalItemIds/GetItemsResult/GetBaseItemDtos, ItemImageInfo, IImageProcessor.GetImageSize/ProcessImage, GetAllEpisodes, QueueRefresh/MetadataRefreshOptions, IUserDataManager.SaveUserData, ILibraryManager.UpdateItem, ILocalizationManager.GetParentalRatings, ISessionManager.SendPlaystateCommand, IScheduledTaskWorker und echte ApplicationVersion. Keine erfundenen REST-Endpunkte; die Implementierung verwendet diese injizierten SDK-Dienste.
|
||||
@@ -0,0 +1,17 @@
|
||||
# eMCPy 1.4.0 – Ausbauplan
|
||||
|
||||
Auftrag: alle vorgeschlagenen Abfrage-/Diagnosefunktionen, Bildprüfung inkl. Screenshot-Verdacht, FSK-Audit und quellenbelegte Einzelkorrektur. Keine Löschwerkzeuge. Kein Neustart ohne neues Go; vorherige Wiedergabeunterbrechung war einmalig.
|
||||
|
||||
- [x] Gemeinsame begrenzte Bulk-Abfragen, Schema-/Argumentvalidierung, unveränderte Altwerkzeuge.
|
||||
- [x] Sammeldetails + kombinierte Suche, Versions-/Dublettenvergleich, Sprach-/Untertitelprüfung, Metadatenqualität.
|
||||
- [x] Bildaudit mit explizit unbekannter Herkunft (SDK besitzt keinen Herkunftsnachweis); Bildansicht für visuelle Prüfung.
|
||||
- [x] Altersfreigaben-Audit (deutsch/ausländisch/fehlend/unbekannt); Setzen eines belegten Wertes mit Vergleich gegen bisherigen Stand.
|
||||
- [x] Fehlende Episoden über vorhandene Emby-Metadatenprovider und deren GetAllEpisodes, keine neue TVDB-Zugangsdatenkopie.
|
||||
- [x] Änderungen seit Datum + begrenzte explizite Inventar-Snapshots für Löschvergleich.
|
||||
- [x] Sitzungs-/Transcodingdiagnose, echte Serverdaten und Aufgabenstatus.
|
||||
- [x] Schreibaktionen (gezielter Refresh/Scan, Pause, Gesehen-Status, FSK) standardmäßig aus, API-Key und explizite Bestätigung nötig. Nur Mocks testen.
|
||||
- [x] SDK-Tests, read-only Live-Baselines, Paket/Checksummen, Doku, Commit/Push; Aktivierung wartet auf neues Go.
|
||||
|
||||
Recherche: SDK 4.9.1.90 reflektiert. ItemImageInfo hat Path/Type/Width/Height/IsLocalFile, aber keine Provider-/ScreenGrabber-Herkunft. GetAllEpisodes(Series,LibraryOptions,CancellationToken) vorhanden. ILocalizationManager.GetParentalRatings(countryCode) vorhanden. Laufender Server/Client-Zugang unverändert.
|
||||
|
||||
Aktivierung/SDK-Integration im laufenden Emby ist ausdrücklich noch offen. 132 bestehende + 97 neue Testassertions erfolgreich; reale Schreibaktionen wurden nicht getestet/ausgeführt. Quellen, Grenzen und Restabnahme stehen in advanced-tools.md.
|
||||
@@ -0,0 +1,15 @@
|
||||
# eMCPy 1.4.0
|
||||
|
||||
37 Werkzeuge; bisherige 18 bleiben erhalten. Neue Bild-/FSK-/Sprach-/Metadatenprüfung, Sammeldetails, Suche, Versionsvergleich, Provider-Folgenabgleich, Änderungen/Snapshots und Diagnosen. Gezielte Schreibaktionen standardmäßig deaktiviert und als Vorschau.
|
||||
|
||||
Prüfen: `sha256sum -c SHA256SUMS` (Linux) oder `shasum -a 256 -c SHA256SUMS` (macOS).
|
||||
|
||||
Nur eMCPy.dll installieren, keine MediaBrowser-Abhängigkeiten. Ziel net6.0, SDK MediaBrowser.Server.Core 4.9.1.90, bestehender Emby 4.9.x.
|
||||
|
||||
Installation braucht ein neues Neustart-Go. Die einmalige Unterbrechungsfreigabe für Version 1.3.0 gilt nicht für dieses Update. Erst Clients pausieren/Anfragen auslaufen lassen und laufende Wiedergaben prüfen; Emby kontrolliert stoppen; vorherige DLL kurzfristig außerhalb des Plugin-Ordners sichern; DLL bei gleichen Rechten ersetzen; Emby starten; Live-Abnahme ausführen. Konfiguration und API-Key nicht kopieren oder ändern.
|
||||
|
||||
Abnahme: `scripts/verify-live-mcp.php` und `scripts/verify-live-expansion.php`, ausschließlich lesend bzw. Vorschau. Kein tatsächlicher FSK-/Gesehen-/Pause-/Refresh-/Scan-Schreibtest am realen Server.
|
||||
|
||||
Rollback: nach freigegebenem kontrolliertem Stop vorherige 1.3.0-DLL zurückkopieren und starten. Nach erfolgreicher Abnahme die temporäre Sicherung/Staging löschen. Details: ../../docs/advanced-tools.md und ../../docs/series-inventory.md.
|
||||
|
||||
Build/229 lokale Assertions erfolgreich; Integration dieser Version im laufenden Emby steht vor Aktivierung noch aus.
|
||||
@@ -0,0 +1 @@
|
||||
314301ba274d197a92c8e3358fe0be0f27078cf08ab1069c7d345daa843f3978 eMCPy.dll
|
||||
Binary file not shown.
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only inspection of actual Emby data before 1.4 activation. No secrets/media paths output."""
|
||||
import json
|
||||
import os
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from collections import Counter
|
||||
|
||||
base = os.environ['EMBY_URL'].rstrip('/')
|
||||
def get(path, query=None):
|
||||
req = urllib.request.Request(base + path + ('?' + urllib.parse.urlencode(query) if query else ''),
|
||||
headers={'X-Emby-Token': os.environ['EMBY_API_KEY']})
|
||||
with urllib.request.urlopen(req, timeout=30) as response:
|
||||
return json.load(response)
|
||||
folders = get('/Library/VirtualFolders')
|
||||
docs = [f for f in folders if f['Name'] == 'Dokumentationen']
|
||||
assert len(docs) == 1, 'Select a unique documentary library'
|
||||
page = get('/Items', {'ParentId': docs[0]['ItemId'], 'Recursive': 'true',
|
||||
'IncludeItemTypes': 'Movie,Series,Episode,Video', 'Limit': 20,
|
||||
'Fields': 'ProviderIds,MediaSources,MediaStreams,OfficialRating,CustomRating'})
|
||||
images = []
|
||||
for item in page['Items'][:3]:
|
||||
info = get('/Items/' + item['Id'] + '/Images')
|
||||
primary = [i for i in info if i['ImageType'] == 'Primary']
|
||||
images.append({'id': item['Id'], 'types': [i['ImageType'] for i in info],
|
||||
'primaryDimensions': [[i.get('Width'), i.get('Height')] for i in primary],
|
||||
'providerOriginExposed': any('Provider' in k or 'Origin' in k for i in info for k in i)})
|
||||
ratings = get('/Localization/ParentalRatings')
|
||||
print(json.dumps({'test': 'REST baseline, not new MCP execution', 'documentaryItems': page['TotalRecordCount'],
|
||||
'sampleSize': len(page['Items']), 'sampleRatings': dict(Counter(i.get('OfficialRating', '<missing>') for i in page['Items'])),
|
||||
'sampleWithMediaSources': sum(bool(i.get('MediaSources')) for i in page['Items']),
|
||||
'images': images,
|
||||
'germanRatings': [i['Name'] for i in ratings if i['Name'].startswith(('FSK-', 'DE-'))]}, indent=2))
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
// Read-only acceptance test AFTER the separately approved plugin restart.
|
||||
// Run on the Emby host. No tokens or episode paths are printed.
|
||||
$config = $argv[1] ?? '/mnt/nvme-storage/appdata/Emby/plugins/configurations/eMCPy.xml';
|
||||
$x = simplexml_load_file($config);
|
||||
if (!$x) throw new RuntimeException('Cannot read local plugin configuration');
|
||||
$calls = 0;
|
||||
function rpc($method, $params) {
|
||||
global $x, $calls;
|
||||
$calls++;
|
||||
$c = curl_init('http://127.0.0.1:'.(int)$x->McpPort.'/mcp');
|
||||
curl_setopt_array($c, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_POST=>true,
|
||||
CURLOPT_HTTPHEADER=>['Content-Type: application/json','X-Api-Key: '.(string)$x->ApiKey],
|
||||
CURLOPT_POSTFIELDS=>json_encode(['jsonrpc'=>'2.0','id'=>$calls,'method'=>$method,'params'=>$params]),CURLOPT_TIMEOUT=>60]);
|
||||
$body = curl_exec($c); $code = curl_getinfo($c, CURLINFO_HTTP_CODE); curl_close($c);
|
||||
if ($code !== 200) throw new RuntimeException('MCP request failed: HTTP '.$code);
|
||||
$r = json_decode($body,true,512,JSON_THROW_ON_ERROR);
|
||||
if (isset($r['error'])) throw new RuntimeException('MCP JSON-RPC error');
|
||||
return $r['result'];
|
||||
}
|
||||
function requireTrue($ok,$message) { if (!$ok) throw new RuntimeException($message); }
|
||||
function callTool($name,$args,$expectError=false) {
|
||||
$r=rpc('tools/call',['name'=>$name,'arguments'=>$args]);
|
||||
if ($expectError) {requireTrue(!empty($r['isError']), 'Expected MCP tool error');return null;}
|
||||
requireTrue(empty($r['isError']), 'MCP tool failed: '.$name);
|
||||
return json_decode($r['content'][0]['text'],true,512,JSON_THROW_ON_ERROR);
|
||||
}
|
||||
$init=rpc('initialize',(object)[]);
|
||||
requireTrue($init['serverInfo']['version']==='1.4.0','Expected loaded eMCPy 1.4.0');
|
||||
$tools=rpc('tools/list',(object)[]);
|
||||
requireTrue(count($tools['tools'])===37,'Expected 37 tools');
|
||||
$diagnostics=callTool('emby_server_diagnostics',(object)[]);
|
||||
requireTrue($diagnostics['services']['library'] && $diagnostics['services']['dto'],'Required services missing');
|
||||
$folders=callTool('emby_library_folders',(object)[]);
|
||||
$docs=array_values(array_filter($folders['folders'],fn($f)=>$f['name']==='Dokumentationen'));
|
||||
requireTrue(count($docs)===1,'Expected unique documentary library');
|
||||
$id=(string)$docs[0]['itemId'];
|
||||
$summary=[];
|
||||
foreach(['emby_image_audit','emby_rating_audit','emby_metadata_audit','emby_track_audit','emby_search_advanced'] as $name) {
|
||||
$result=callTool($name,['libraryId'=>$id,'limit'=>5]);
|
||||
$page=$name==='emby_rating_audit'?$result['page']:$result;
|
||||
requireTrue($page['scanned']<=5 && $page['returned']===count($page['items']),'Invalid page');
|
||||
$summary[$name]=['candidates'=>$page['totalCandidates'],'scanned'=>$page['scanned'],'returned'=>$page['returned']];
|
||||
if($page['hasMore']) {
|
||||
$next=callTool($name,['libraryId'=>$id,'limit'=>5,'start'=>$page['nextStart'],'expectedRevision'=>$page['inventoryRevision']]);
|
||||
$next=$name==='emby_rating_audit'?$next['page']:$next;
|
||||
requireTrue($next['start']===$page['nextStart'],'Bad next page');
|
||||
}
|
||||
}
|
||||
$search=callTool('emby_search_advanced',['libraryId'=>$id,'limit'=>2]);
|
||||
$ids=array_column($search['items'],'id');
|
||||
if($ids) {
|
||||
$batch=callTool('emby_batch_details',['ids'=>$ids]);requireTrue($batch['returned']===count($ids),'Batch mismatch');
|
||||
$image=rpc('tools/call',['name'=>'emby_image_review','arguments'=>['ids'=>$ids]]);
|
||||
requireTrue(empty($image['isError']),'Image review failed');
|
||||
$summary['imagePreviewCount']=count(array_filter($image['content'],fn($c)=>$c['type']==='image'));
|
||||
$localPrimary=false;foreach($batch['items'] as $entry)foreach($entry['images']??[] as $pic)if($pic['type']==='Primary'&&$pic['isLocalFile'])$localPrimary=true;
|
||||
if($localPrimary)requireTrue($summary['imagePreviewCount']>0,'Local primary images exist but none could be rendered');
|
||||
}
|
||||
callTool('emby_library_changes',['libraryId'=>$id,'since'=>'2026-10-01T00:00:00Z','limit'=>5]);
|
||||
callTool('emby_users',(object)[]);
|
||||
callTool('emby_playback_diagnostics',(object)[]);
|
||||
callTool('emby_scan_library',['libraryId'=>$id]); // default preview ONLY
|
||||
$movie=callTool('emby_search_advanced',['types'=>['Movie'],'limit'=>1]);
|
||||
if($movie['items']) {
|
||||
$m=$movie['items'][0];
|
||||
$rating=callTool('emby_set_rating',['id'=>$m['id'],'rating'=>'FSK-12','expectedOfficialRating'=>$m['officialRating'],
|
||||
'expectedCustomRating'=>$m['customRating'],'sourceUrl'=>'https://www.fsk.de',
|
||||
'evidence'=>'Technischer Vorschautest, keine recherchierte Freigabe; nichts speichern.']);
|
||||
requireTrue($rating['dryRun']===true,'Rating must be preview');
|
||||
$after=callTool('emby_batch_details',['ids'=>[$m['id']],'include'=>['basic']]);
|
||||
requireTrue($after['items'][0]['officialRating']===$m['officialRating']&&$after['items'][0]['customRating']===$m['customRating'],'Preview changed rating');
|
||||
callTool('emby_refresh_item',['id'=>$m['id']]); // default preview ONLY
|
||||
}
|
||||
callTool('emby_search_advanced',['libraryId'=>'invalid'],true);
|
||||
callTool('emby_image_review',[],true);
|
||||
echo json_encode(['version'=>'1.4.0','calls'=>$calls,'results'=>$summary,'mutationsExecuted'=>0,
|
||||
'note'=>'Snapshots, provider episode retrieval, duplicates and real writes tested separately with SDK doubles; no live write executed.'],JSON_PRETTY_PRINT).PHP_EOL;
|
||||
@@ -26,9 +26,9 @@ function callTool($name,$args,$expectError=false) {
|
||||
return json_decode($r['content'][0]['text'],true,512,JSON_THROW_ON_ERROR);
|
||||
}
|
||||
$init=rpc('initialize',(object)[]);
|
||||
requireTrue($init['serverInfo']['version']==='1.3.0','Expected loaded eMCPy 1.3.0');
|
||||
requireTrue(in_array($init['serverInfo']['version'],['1.3.0','1.4.0'],true),'Expected loaded eMCPy 1.3.0 or 1.4.0');
|
||||
$tools=rpc('tools/list',(object)[]);
|
||||
requireTrue(count($tools['tools'])===18,'Expected 18 tools');
|
||||
requireTrue(count($tools['tools'])>=18,'Expected at least the existing 18 tools');
|
||||
$search=callTool('emby_search',['query'=>'Proper People','type'=>'Series']);
|
||||
requireTrue(count($search['items'])===1,'Select explicit series ID; search ambiguous');
|
||||
$id=$search['items'][0]['id'];
|
||||
|
||||
@@ -33,6 +33,14 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="checkboxContainer" style="margin-top: 1em;">
|
||||
<label><input is="emby-checkbox" type="checkbox" id="enableWriteTools" />
|
||||
<span>Gezielte Schreibaktionen erlauben</span></label>
|
||||
<div class="fieldDescription">Standardmäßig aus. Erlaubt Altersfreigabe, Gesehen-Status, Pause und Refresh/Scan.
|
||||
Benötigt einen gesetzten MCP-API-Key; Aktionen starten als Vorschau und erfordern explizite Bestätigung.
|
||||
Keine Lösch- oder Neustartwerkzeuge. Diese Freigabe lässt den MCP-Listener weiterlaufen.</div>
|
||||
</div>
|
||||
|
||||
<div class="inputContainer" style="margin-top: 1em;">
|
||||
<label class="inputLabel inputLabelUnfocused" for="mcpPort">Port</label>
|
||||
<input is="emby-input" type="number" id="mcpPort" min="1024" max="65535" step="1" />
|
||||
|
||||
@@ -78,6 +78,7 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) {
|
||||
loading.show();
|
||||
getPluginConfiguration().then(config => {
|
||||
view.querySelector('#enableMcpServer').checked = config.EnableMcpServer !== false;
|
||||
view.querySelector('#enableWriteTools').checked = config.EnableWriteTools === true;
|
||||
view.querySelector('#mcpPort').value = config.McpPort || 8097;
|
||||
view.querySelector('#listenAddress').value = config.ListenAddress || '0.0.0.0';
|
||||
view.querySelector('#apiKey').value = config.ApiKey || '';
|
||||
@@ -102,6 +103,10 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) {
|
||||
|
||||
getPluginConfiguration().then(config => {
|
||||
config.EnableMcpServer = view.querySelector('#enableMcpServer').checked;
|
||||
config.EnableWriteTools = view.querySelector('#enableWriteTools').checked;
|
||||
if (config.EnableWriteTools && !view.querySelector('#apiKey').value.trim()) {
|
||||
loading.hide(); toast({ type: 'error', text: 'Schreibaktionen benötigen einen MCP-API-Key.' }); return;
|
||||
}
|
||||
config.McpPort = port;
|
||||
config.ListenAddress = view.querySelector('#listenAddress').value.trim() || '0.0.0.0';
|
||||
config.ApiKey = view.querySelector('#apiKey').value.trim();
|
||||
@@ -111,7 +116,7 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) {
|
||||
updatePluginConfiguration(config).then(result => {
|
||||
loading.hide();
|
||||
Dashboard.processPluginConfigurationUpdateResult(result);
|
||||
toast({ type: 'success', text: 'Gespeichert. MCP-Server wird neu gestartet.' });
|
||||
toast({ type: 'success', text: 'Gespeichert. Nur geänderte Listener-Einstellungen erfordern einen MCP-Neustart.' });
|
||||
setTimeout(() => this.checkServerStatus(view, config), 2000);
|
||||
}).catch(() => {
|
||||
loading.hide();
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace eMCPy.Mcp
|
||||
{
|
||||
public static class AdvancedSchemas
|
||||
{
|
||||
static object Str(string description, params string[] values) => values.Length == 0
|
||||
? new { type = "string", description, minLength = 1, maxLength = 2000 } as object
|
||||
: new { type = "string", description, @enum = values };
|
||||
static object Int(string description, int min, int max) => new { type = "integer", description, minimum = min, maximum = max };
|
||||
static object Bool(string description) => new { type = "boolean", description };
|
||||
static object ArrayOf(string description, int max, params string[] values) => new { type = "array", description, minItems = 1, maxItems = max, uniqueItems = true, items = Str("Wert", values) };
|
||||
static Dictionary<string, object> Scope() => new Dictionary<string, object>
|
||||
{
|
||||
["libraryId"] = Str("Optional: eindeutige Bibliotheks-/Ordner-ID aus emby_library_folders; kein Name."),
|
||||
["types"] = ArrayOf("Item-Typen; Standard Movie,Series,Season,Episode,Video,MusicVideo.", 10, "Movie", "Series", "Season", "Episode", "Video", "MusicVideo", "Audio", "MusicAlbum", "MusicArtist", "Photo"),
|
||||
["genre"] = Str("Exakter Emby-Genrename, z.B. Documentary. Bibliothek Dokumentationen alternativ per libraryId wählen."),
|
||||
["query"] = Str("Optionaler Titel-Suchbegriff."),
|
||||
["start"] = Int("Startposition in der Kandidatenliste, Standard 0. Auch bei leerer Trefferseite nextStart folgen.", 0, int.MaxValue),
|
||||
["limit"] = Int("Maximal gescannte Items pro Seite, Standard 100, höchstens 200.", 1, 200),
|
||||
["expectedRevision"] = Str("Bestandskennung der ersten Seite; erkennt Änderungen der geordneten Kandidaten-IDs.")
|
||||
};
|
||||
static object Tool(string name, string description, Dictionary<string, object> p, string[] required = null, bool write = false) => new
|
||||
{
|
||||
name,
|
||||
description,
|
||||
inputSchema = new { type = "object", properties = p, required = required ?? Array.Empty<string>(), additionalProperties = false },
|
||||
annotations = new { readOnlyHint = !write, destructiveHint = write, openWorldHint = name == "emby_missing_episodes" }
|
||||
};
|
||||
static Dictionary<string, object> Action() => new Dictionary<string, object>
|
||||
{
|
||||
["dryRun"] = Bool("Standard true: nur Vorschau. Erst false führt die Aktion aus."),
|
||||
["confirm"] = Bool("Für Ausführung explizit true; zusätzlich Plugin-Schreibfreigabe und gesetzter MCP-Key erforderlich.")
|
||||
};
|
||||
static List<object> BuildDefinitions()
|
||||
{
|
||||
var list = new List<object>();
|
||||
var p = Scope(); p["userId"] = Str("Pflicht bei played; eindeutiger Emby-Benutzer, niemals automatisch erster Benutzer."); p["played"] = Bool("Gesehen-Status für userId."); p["maxRuntimeMinutes"] = Int("Maximale Laufzeit; fehlende Laufzeit wird nicht als passend gewertet.", 1, 100000); p["audioLanguage"] = Str("Sprache als ISO-Code, z.B. deu; de/ger werden als Deutsch normalisiert."); p["subtitleLanguage"] = Str("Untertitelsprache als ISO-Code."); p["sortBy"] = Str("Standard id; zusätzlich title/dateCreated/runtime/rating.", "id", "title", "dateCreated", "runtime", "rating"); p["descending"] = Bool("Absteigend sortieren.");
|
||||
list.Add(Tool("emby_search_advanced", "Kombinierte Mediensuche: Bibliothek, Typ, Genre, Titel, Laufzeit, Audio-/Untertitelsprache und benutzerspezifisch gesehen/ungesehen. Pagination zählt Kandidaten; returned zählt passende Items der Seite, totalMatches ist unbekannt. Bis hasMore=false weiterblättern.", p));
|
||||
list.Add(Tool("emby_batch_details", "Sammeldetails und Qualitätsvergleich für bis zu 200 explizite Item-IDs in einem Bulk-Aufruf. Wählbare Gruppen; keine Detailaufrufe je Item. Medienquellen enthalten Auflösung, HDR-Hinweise, Codecs, Tonspuren, Größe und Laufzeit; kein pauschales Qualitätsranking verschiedener Schnittfassungen.", new Dictionary<string, object> { ["ids"] = ArrayOf("Emby-IDs als Strings (GUID oder numerisch).", 200), ["include"] = ArrayOf("Standard basic,media,images; userdata benötigt userId.", 4, "basic", "media", "images", "userdata"), ["userId"] = Str("Expliziter Benutzer für userdata.") }, new[] { "ids" }));
|
||||
p = Scope(); p["onlyProblems"] = Bool("Standard true; false liefert auch unauffällige Items.");
|
||||
list.Add(Tool("emby_image_audit", "Cover-/Poster-/Bildprüfung einer ganzen Bibliothek, z.B. Dokumentationen: fehlendes Primary, vorhandene Backdrops/Logo/Thumb/Screenshot, Maße, Layout und visuelle Prüfkandidaten. Querformat ist KEIN Beweis für Screen Grabber. origin bleibt unknown, da Emby die Herkunft nicht speichert. emby_image_review zeigt das Bild. Pagination nach gescannten Kandidaten.", p));
|
||||
list.Add(Tool("emby_metadata_audit", "Findet fehlende Titel, Provider-IDs, Bilder, Laufzeiten und Episodennummerierung. Unbekannt bleibt unbekannt. Pagination nach gescannten Kandidaten.", Scope()));
|
||||
p = Scope(); p["language"] = Str("Gewünschte Sprache, Standard deu (Deutsch)."); p["kind"] = Str("Standard audio; audio oder subtitle prüfen.", "audio", "subtitle");
|
||||
list.Add(Tool("emby_track_audit", "Prüft Audio-/Untertitelsprachen seitenweise über Medienquellen. Unterscheidet vorhanden, fehlend und unbekannt. Eingebrannte Untertitel sind aus fehlenden Spuren NICHT ableitbar; burnedInSubtitleStatus bleibt unknown.", p));
|
||||
p = Scope(); p["onlyProblems"] = Bool("Standard true; listet fehlende/ausländische/unbekannte OfficialRating sowie abweichende CustomRating.");
|
||||
list.Add(Tool("emby_rating_audit", "FSK-/Altersfreigabenprüfung: Welche Filme/Serien haben keine deutsche FSK-/DE-Freigabe? Liefert Originalwert, benutzerdefinierte/effective Freigabe, deutsche SDK-Werte und Recherchekontext (Titel/Jahr/Provider-IDs/Fassungshinweis). Keine Umrechnung ausländischer Ratings. Folgewerkzeug emby_set_rating.", p));
|
||||
p = Scope(); p["memberStart"] = Int("Start innerhalb jeder Kandidatengruppe.", 0, int.MaxValue); p["memberLimit"] = Int("Mitglieder je Gruppe, Standard 50, max 200. Für weitere Mitglieder memberStart erhöhen.", 1, 200);
|
||||
list.Add(Tool("emby_duplicate_candidates", "Versions- und Dublettenkandidaten anhand gemeinsamer Provider-IDs, Typ und bei Folgen Serie/Staffel/Episode. Erkennt auch mehrere Medienversionen innerhalb eines einzelnen Emby-Items. Vollständiger begrenzter Bulk-Vergleich, Gruppenseiten. Gleiche IDs sind kein Beweis für identische Dateien oder gleiche Schnittfassung. Details mit emby_batch_details vergleichen; keine Löschung.", p));
|
||||
list.Add(Tool("emby_missing_episodes", "Vergleicht lokal gespeicherte Episoden mit GetAllEpisodes der bereits konfigurierten Emby-Metadatenprovider (kann deren Internetzugriff auslösen). Fehlende Folgen werden anhand Provider-ID oder passender Nummerierung als Kandidaten ausgewiesen; unterschiedliche Reihenfolgen und unbekannte lokale Nummern machen den Vergleich unsicher. Keine Ableitung bloß aus Nummernlücken.", new Dictionary<string, object> { ["seriesId"] = Str("Eindeutige Series-ID."), ["season"] = Int("Optionaler Staffelfilter.", 0, int.MaxValue), ["start"] = Int("Start in der Liste fehlender Kandidaten.", 0, int.MaxValue), ["limit"] = Int("Standard 100, max 200.", 1, 200) }, new[] { "seriesId" }));
|
||||
p = Scope(); p["since"] = Str("ISO-Zeitstempel mit Zeitzone, z.B. 2026-10-01T00:00:00Z.");
|
||||
list.Add(Tool("emby_library_changes", "Seit Zeitpunkt hinzugefügte oder in Emby gespeicherte/geänderte Items. Meldet keine gelöschten Dateien ohne früheren Snapshot. Für gelöschte Bibliothekseinträge emby_inventory_snapshot verwenden. Pagination nach Kandidaten.", p, new[] { "since" }));
|
||||
list.Add(Tool("emby_inventory_snapshot", "Erfasst/verglicht ausdrücklich einen schlanken Bibliotheksindex (keine Mediendatei-Sicherung). Pro libraryId eine Baseline, max 20 Bibliotheken/100000 Items. capture ersetzt Baseline nur mit replace=true; compare verändert sie nicht. Erkennt aus dem Emby-Index verschwundene IDs, nicht bewiesene physische Dateilöschung. Keine automatischen Snapshots.", new Dictionary<string, object> { ["libraryId"] = Str("Bibliotheks-ID."), ["operation"] = Str("capture oder compare.", "capture", "compare"), ["replace"] = Bool("Vorhandene Baseline ausdrücklich ersetzen."), ["start"] = Int("Vergleichsseite.", 0, int.MaxValue), ["limit"] = Int("Standard 100, max 200.", 1, 200) }, new[] { "libraryId", "operation" }, true));
|
||||
list.Add(Tool("emby_users", "Benutzer-IDs/Namen zur expliziten Auswahl für Suche/Gesehen-Status; keine Zugangsdaten.", new Dictionary<string, object>()));
|
||||
list.Add(Tool("emby_server_diagnostics", "Echte Emby-/Plugin-Version, Start-/Neustartstatus, verfügbare Dienste, Schreibfreigabe, Refresh-Queue und geplante Aufgaben mit Status/Fortschritt. Führt keine Aufgaben aus und startet nichts neu.", new Dictionary<string, object>()));
|
||||
list.Add(Tool("emby_playback_diagnostics", "Wiedergabe-/Transcodingdiagnose: Gerät, Item, Pause, PlayMethod, Video-/Audio-Direct-Flags und von Emby gemeldete TranscodeReasons. Fehlende Gründe bleiben unknown; keine vermuteten Ursachen als Fakten.", new Dictionary<string, object> { ["sessionId"] = Str("Optional: konkrete Sitzung; sonst alle aktuellen Wiedergaben.") }));
|
||||
list.Add(Tool("emby_image_review", "Liefert vorhandene lokale Bilder als kleine MCP-Bildvorschauen zur visuellen Prüfung von Poster vs. Filmstandbild. id ODER bis zu 20 ids. Emby erzeugt nur Vorschaucache, keine neuen Film-Screenshots. Keine KI-Klassifikation eingebaut. Max 1 MiB/Bild und 8 MiB/Aufruf; kein beliebiger Pfad, kein externer Download.", new Dictionary<string, object> { ["id"] = Str("Einzelne Item-ID, alternativ ids."), ["ids"] = ArrayOf("Bis zu 20 Item-IDs für gemeinsame visuelle Prüfung.", 20), ["imageType"] = Str("Standard Primary.", "Primary", "Backdrop", "Thumb", "Logo", "Screenshot"), ["index"] = Int("Bildindex pro Typ, Standard 0.", 0, 100) }));
|
||||
p = Action(); p["id"] = Str("Movie-/Series-/Episode-/Season-/Video-ID."); p["rating"] = Str("Exakter deutscher Wert aus emby_rating_audit, z.B. FSK-12 oder DE-12."); p["expectedOfficialRating"] = new { type = new[] { "string", "null" }, description = "Bisheriger OfficialRating; null falls fehlend. Schutz gegen veraltete Änderungen." }; p["expectedCustomRating"] = new { type = new[] { "string", "null" }, description = "Bisheriger CustomRating; null falls fehlend." }; p["sourceUrl"] = Str("HTTPS-Quellenbeleg ohne Zugangsdaten/Token; öffentliche Such-/Dokumentparameter sind erlaubt. Vorzugsweise offizieller FSK-Beleg zur richtigen Fassung."); p["evidence"] = Str("Recherchebegründung mit Titel, Jahr und geprüfter Fassung/Medium. Vom aufrufenden Modell recherchiert, nicht vom MCP verifiziert."); p["clearCustomRating"] = Bool("Standard false; nur ausdrücklich true entfernt einen übersteuernden CustomRating."); p["lockField"] = Bool("Standard false; true sperrt OfficialRating gegen spätere Metadaten-Refreshs.");
|
||||
list.Add(Tool("emby_set_rating", "Setzt ausschließlich die quellenbelegte deutsche Altersfreigabe eines Items. Standard dryRun=true. Ausführung braucht Plugin-Schreibfreigabe, API-Key, confirm=true und passende bisherige Werte. Keine ausländischen Ratings umrechnen, keine Recherchebehauptung ohne Beleg. Quellenangabe wird lokal protokolliert, aber nicht automatisch als wahr verifiziert.", p, new[] { "id", "rating", "expectedOfficialRating", "expectedCustomRating", "sourceUrl", "evidence" }, true));
|
||||
p = Action(); p["id"] = Str("Einzelnes abspielbares Item, keine Series/Season/Folder."); p["userId"] = Str("Expliziter Benutzer."); p["played"] = Bool("Gewünschter Gesehen-Status."); p["expectedPlayed"] = Bool("Bisheriger Status zum Schutz vor veralteten Änderungen.");
|
||||
list.Add(Tool("emby_set_played", "Ändert Gesehen-Status eines einzelnen Items für einen expliziten Benutzer. Standard nur Vorschau, kein rekursives Markieren ganzer Serien.", p, new[] { "id", "userId", "played", "expectedPlayed" }, true));
|
||||
p = Action(); p["sessionId"] = Str("Konkrete aktuelle Sitzung aus playback_diagnostics."); p["expectedItemId"] = Str("Aktuell erwartete Item-ID, verhindert Pausieren inzwischen anderer Wiedergabe.");
|
||||
list.Add(Tool("emby_pause_session", "Pausiert genau eine überprüfte Sitzung. Standard nur Vorschau; kein Stop, kein Neustart.", p, new[] { "sessionId", "expectedItemId" }, true));
|
||||
p = Action(); p["id"] = Str("Einzelnes Item; keine Bibliotheksordner.");
|
||||
list.Add(Tool("emby_refresh_item", "Stellt einen nichtrekursiven Metadaten-Refresh eines Items in Embys Queue. Kein Ersetzen aller Bilder/Metadaten, kein Neustart. Standard Vorschau; queued bedeutet nicht abgeschlossen.", p, new[] { "id" }, true));
|
||||
p = Action(); p["libraryId"] = Str("Konkrete Bibliothek aus emby_library_folders.");
|
||||
list.Add(Tool("emby_scan_library", "Stellt die rekursive Validierung einer einzelnen Bibliothek in Embys Refresh-Queue (ValidationOnly, kein vollständiger Metadatenersatz). Standard Vorschau; Fortschritt in server_diagnostics, queued ist nicht abgeschlossen.", p, new[] { "libraryId" }, true));
|
||||
return list;
|
||||
}
|
||||
|
||||
static readonly List<object> Cached = BuildDefinitions();
|
||||
static readonly Dictionary<string, object> ByName = Cached.ToDictionary(d => JsonSerializer.SerializeToElement(d).GetProperty("name").GetString());
|
||||
public static List<object> Definitions() => new List<object>(Cached);
|
||||
public static bool IsKnown(string name) => name != null && ByName.ContainsKey(name);
|
||||
public static object Get(string name) => IsKnown(name) ? ByName[name] : throw new ToolInputException("Unbekanntes Werkzeug.");
|
||||
|
||||
public static void Validate(object definition, JsonElement args)
|
||||
{
|
||||
var schema = JsonSerializer.SerializeToElement(definition).GetProperty("inputSchema");
|
||||
if (args.ValueKind == JsonValueKind.Undefined) args = JsonSerializer.SerializeToElement(new { });
|
||||
if (args.ValueKind != JsonValueKind.Object) throw new ToolInputException("arguments muss ein Objekt sein.");
|
||||
foreach (var key in schema.GetProperty("required").EnumerateArray()) if (!args.TryGetProperty(key.GetString(), out _)) throw new ToolInputException(key.GetString() + " ist erforderlich.");
|
||||
foreach (var prop in args.EnumerateObject())
|
||||
{
|
||||
if (!schema.GetProperty("properties").TryGetProperty(prop.Name, out var rule)) throw new ToolInputException("Unbekannter Parameter: " + prop.Name);
|
||||
ValidateValue(prop.Value, rule, prop.Name);
|
||||
}
|
||||
}
|
||||
static void ValidateValue(JsonElement value, JsonElement rule, string key)
|
||||
{
|
||||
var type = rule.GetProperty("type");
|
||||
if (type.ValueKind == JsonValueKind.Array && value.ValueKind == JsonValueKind.Null) return;
|
||||
var kind = type.ValueKind == JsonValueKind.Array ? "string" : type.GetString();
|
||||
bool ok = kind switch { "string" => value.ValueKind == JsonValueKind.String, "integer" => value.ValueKind == JsonValueKind.Number && value.TryGetInt32(out _), "boolean" => value.ValueKind == JsonValueKind.True || value.ValueKind == JsonValueKind.False, "array" => value.ValueKind == JsonValueKind.Array, _ => false };
|
||||
if (!ok) throw new ToolInputException("Ungültiger Typ für " + key);
|
||||
if (kind == "string" && (rule.TryGetProperty("minLength", out _) && string.IsNullOrWhiteSpace(value.GetString()) || value.GetString().Length > 2000)) throw new ToolInputException("Ungültiger Text für " + key);
|
||||
if (rule.TryGetProperty("enum", out var choices) && !choices.EnumerateArray().Any(x => x.GetString() == value.GetString())) throw new ToolInputException("Ungültiger Wert für " + key);
|
||||
if (kind == "integer" && (value.GetInt32() < rule.GetProperty("minimum").GetInt32() || value.GetInt32() > rule.GetProperty("maximum").GetInt32())) throw new ToolInputException("Wert außerhalb der Grenzen: " + key);
|
||||
if (kind == "array") { var a = value.EnumerateArray().ToArray(); if (a.Length < rule.GetProperty("minItems").GetInt32() || a.Length > rule.GetProperty("maxItems").GetInt32() || a.Select(x => x.GetRawText()).Distinct().Count() != a.Length) throw new ToolInputException("Ungültige Liste: " + key); foreach (var x in a) ValidateValue(x, rule.GetProperty("items"), key); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace eMCPy.Mcp
|
||||
{
|
||||
public sealed class AdvancedTools
|
||||
{
|
||||
readonly EmbyServices services;
|
||||
public AdvancedTools(EmbyServices s) { services = s; }
|
||||
public object Execute(string name, JsonElement arguments)
|
||||
{
|
||||
var definition = AdvancedSchemas.Get(name);
|
||||
AdvancedSchemas.Validate(definition, arguments);
|
||||
var a = new ToolArgs(arguments); var library = new LibraryOperations(services); var management = new ManagementOperations(services);
|
||||
return name switch
|
||||
{
|
||||
"emby_search_advanced" => library.Search(a),
|
||||
"emby_batch_details" => library.Batch(a),
|
||||
"emby_image_audit" => library.ImageAudit(a),
|
||||
"emby_image_review" => library.ImageReview(a),
|
||||
"emby_metadata_audit" => library.Metadata(a),
|
||||
"emby_track_audit" => library.Tracks(a),
|
||||
"emby_rating_audit" => library.Ratings(a),
|
||||
"emby_duplicate_candidates" => library.Duplicates(a),
|
||||
"emby_missing_episodes" => library.MissingEpisodes(a),
|
||||
"emby_library_changes" => library.Changes(a),
|
||||
"emby_inventory_snapshot" => management.Snapshot(a),
|
||||
"emby_users" => management.Users(),
|
||||
"emby_server_diagnostics" => management.Diagnostics(),
|
||||
"emby_playback_diagnostics" => management.Playback(a),
|
||||
"emby_set_rating" => management.SetRating(a),
|
||||
"emby_set_played" => management.Played(a),
|
||||
"emby_pause_session" => management.Pause(a),
|
||||
"emby_refresh_item" => management.Refresh(a, false),
|
||||
"emby_scan_library" => management.Refresh(a, true),
|
||||
_ => throw new ToolInputException("Werkzeug ohne Implementierung.")
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Controller.Dto;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Entities.TV;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Querying;
|
||||
|
||||
namespace eMCPy.Mcp
|
||||
{
|
||||
public sealed class LibraryOperations
|
||||
{
|
||||
readonly EmbyServices s;
|
||||
public LibraryOperations(EmbyServices services) { s = services; }
|
||||
public static readonly string[] DefaultTypes = { "Movie", "Series", "Season", "Episode", "Video", "MusicVideo" };
|
||||
internal DtoOptions Options(bool media = false, bool images = false, bool user = false) => new DtoOptions
|
||||
{
|
||||
EnableImages = images,
|
||||
EnableUserData = user,
|
||||
Fields = (new[] { ItemFields.Id, ItemFields.Name, ItemFields.Path, ItemFields.ProviderIds, ItemFields.RunTimeTicks, ItemFields.OfficialRating, ItemFields.CustomRating, ItemFields.DateCreated, ItemFields.DateModified, ItemFields.IndexNumber, ItemFields.SeriesId, ItemFields.ProductionYear })
|
||||
.Concat(media ? new[] { ItemFields.MediaSources, ItemFields.AlternateMediaSources, ItemFields.MediaStreams } : Array.Empty<ItemFields>()).ToArray()
|
||||
};
|
||||
internal InternalItemsQuery Scope(ToolArgs a)
|
||||
{
|
||||
var q = new InternalItemsQuery
|
||||
{
|
||||
Recursive = true,
|
||||
IncludeItemTypes = a.Has("types") ? a.Strings("types") : DefaultTypes,
|
||||
GroupByPresentationUniqueKey = false,
|
||||
EnableTotalRecordCount = false
|
||||
};
|
||||
if (a.Has("libraryId"))
|
||||
{
|
||||
var folder = ToolSupport.Item(s.Library, a.Text("libraryId"));
|
||||
if (!(folder is Folder)) throw new ToolInputException("libraryId muss einen Ordner bezeichnen.");
|
||||
q.AncestorIds = new[] { folder.InternalId };
|
||||
}
|
||||
if (a.Has("genre")) q.Genres = new[] { a.Text("genre") };
|
||||
if (a.Has("query")) q.SearchTerm = a.Text("query");
|
||||
if (a.Has("userId")) q.User = ToolSupport.User(s, a.Text("userId"));
|
||||
if (a.Has("played"))
|
||||
{
|
||||
if (q.User == null) throw new ToolInputException("played benötigt eine explizite userId.");
|
||||
q.IsPlayed = a.Bool("played");
|
||||
}
|
||||
return q;
|
||||
}
|
||||
internal long[] Ids(InternalItemsQuery query, string sort = "id", bool descending = false)
|
||||
{
|
||||
// Hard cap avoids silently unbounded server-wide scans. Scope to a library if exceeded.
|
||||
query.Limit = 100001;
|
||||
var field = sort switch { "title" => ItemSortBy.SortName, "dateCreated" => ItemSortBy.DateCreated, "runtime" => ItemSortBy.Runtime, "rating" => ItemSortBy.CommunityRating, _ => null };
|
||||
if (field != null) query.OrderBy = new[] { (field, descending ? SortOrder.Descending : SortOrder.Ascending), (ItemSortBy.Path, SortOrder.Ascending) };
|
||||
var ids = s.Library.GetInternalItemIds(query).Distinct().ToArray();
|
||||
if (ids.Length > 100000) throw new ToolOperationException("Mehr als 100000 Kandidaten. Bitte Bibliothek/Typ/Genre eingrenzen.");
|
||||
if (field == null) ids = descending ? ids.OrderByDescending(x => x).ToArray() : ids.OrderBy(x => x).ToArray();
|
||||
return ids;
|
||||
}
|
||||
internal BaseItem[] Load(long[] ids, DtoOptions options = null, User user = null)
|
||||
{
|
||||
if (ids.Length == 0) return Array.Empty<BaseItem>();
|
||||
if (ids.Length > 200) throw new ToolInputException("Interne Seitengröße überschritten.");
|
||||
var items = s.Library.GetItemsResult(new InternalItemsQuery
|
||||
{
|
||||
ItemIds = ids,
|
||||
Limit = ids.Length,
|
||||
User = user,
|
||||
GroupByPresentationUniqueKey = false,
|
||||
EnableTotalRecordCount = false,
|
||||
DtoOptions = options
|
||||
}).Items;
|
||||
var map = items.ToDictionary(x => x.InternalId);
|
||||
if (map.Count != ids.Length || ids.Any(id => !map.ContainsKey(id))) throw new ToolOperationException("Bestand während Abfrage geändert oder Zugriff eingeschränkt. Ab Seite 0 neu beginnen.");
|
||||
return ids.Select(id => map[id]).ToArray();
|
||||
}
|
||||
internal IEnumerable<BaseItem> All(long[] ids)
|
||||
{
|
||||
for (int i = 0; i < ids.Length; i += 200) foreach (var item in Load(ids.Skip(i).Take(200).ToArray())) yield return item;
|
||||
}
|
||||
internal static string Revision(long[] ids) => ToolSupport.Hash(string.Join(",", ids));
|
||||
internal static void CheckRevision(ToolArgs a, string revision)
|
||||
{
|
||||
if (a.Has("expectedRevision") && a.Text("expectedRevision") != revision) throw new ToolOperationException("Kandidatenbestand/Reihenfolge geändert. Bei start=0 neu beginnen.");
|
||||
}
|
||||
internal object Page(ToolArgs a, Func<BaseItem, BaseItemDto, Dictionary<string, object>> inspect, bool media = false, bool images = false)
|
||||
{
|
||||
var q = Scope(a); var ids = Ids(q, a.Text("sortBy", "id"), a.Bool("descending")); var revision = Revision(ids); CheckRevision(a, revision);
|
||||
int start = a.Int("start", 0), limit = a.Int("limit", 100);
|
||||
var options = Options(media, images); var items = Load(ids.Skip(start).Take(limit).ToArray(), options, q.User);
|
||||
var dto = media ? (items.Length == 0 ? Array.Empty<BaseItemDto>() : s.Dto.GetBaseItemDtos(items, options, q.User)) : null;
|
||||
if (media && (dto == null || dto.Length != items.Length)) throw new ToolOperationException("Unvollständige DTO-Antwort.");
|
||||
var rows = new List<Dictionary<string, object>>();
|
||||
for (int i = 0; i < items.Length; i++) { var row = inspect(items[i], dto?[i]); if (row != null) rows.Add(row); }
|
||||
bool more = (long)start + items.Length < ids.Length;
|
||||
return new
|
||||
{
|
||||
totalCandidates = ids.Length,
|
||||
totalMatches = (int?)null,
|
||||
scanned = items.Length,
|
||||
returned = rows.Count,
|
||||
start,
|
||||
limit,
|
||||
hasMore = more,
|
||||
nextStart = more ? (int?)(start + items.Length) : null,
|
||||
inventoryRevision = revision,
|
||||
items = rows
|
||||
};
|
||||
}
|
||||
public object Search(ToolArgs a) => Page(a, (item, dto) =>
|
||||
{
|
||||
if (a.Has("maxRuntimeMinutes") && (!item.RunTimeTicks.HasValue || item.RunTimeTicks.Value > (long)a.Int("maxRuntimeMinutes", 0) * TimeSpan.TicksPerMinute)) return null;
|
||||
if (a.Has("audioLanguage") && TrackState(dto, MediaStreamType.Audio, a.Text("audioLanguage")) != "present") return null;
|
||||
if (a.Has("subtitleLanguage") && TrackState(dto, MediaStreamType.Subtitle, a.Text("subtitleLanguage")) != "present") return null;
|
||||
return ToolSupport.Row(item);
|
||||
}, a.Has("audioLanguage") || a.Has("subtitleLanguage"));
|
||||
|
||||
public object Batch(ToolArgs a)
|
||||
{
|
||||
var requested = a.Strings("ids"); var ids = requested.Select(id => ToolSupport.Id(s.Library, id)).Distinct().ToArray();
|
||||
var include = a.Has("include") ? a.Strings("include") : new[] { "basic", "media", "images" };
|
||||
User user = null; if (include.Contains("userdata")) { if (!a.Has("userId")) throw new ToolInputException("userdata benötigt userId."); user = ToolSupport.User(s, a.Text("userId")); }
|
||||
var options = Options(include.Contains("media"), include.Contains("images"), user != null);
|
||||
// Explicit IDs: return missing IDs instead of falling back to the whole library.
|
||||
var found = s.Library.GetItemsResult(new InternalItemsQuery { ItemIds = ids, Limit = ids.Length, GroupByPresentationUniqueKey = false, EnableTotalRecordCount = false, DtoOptions = options, User = user }).Items;
|
||||
var dtos = found.Length == 0 ? Array.Empty<BaseItemDto>() : s.Dto.GetBaseItemDtos(found, options, user);
|
||||
if (dtos.Length != found.Length) throw new ToolOperationException("Unvollständige DTO-Antwort.");
|
||||
var result = new List<object>();
|
||||
for (int i = 0; i < found.Length; i++)
|
||||
{
|
||||
var row = include.Contains("basic") ? ToolSupport.Row(found[i]) : new Dictionary<string, object> { ["id"] = found[i].InternalId.ToString() };
|
||||
if (include.Contains("media")) row["mediaSources"] = Media(dtos[i]);
|
||||
if (include.Contains("images")) row["images"] = Images(found[i]);
|
||||
if (include.Contains("userdata")) row["userData"] = dtos[i].UserData;
|
||||
result.Add(row);
|
||||
}
|
||||
return new { requested = requested.Length, returned = result.Count, missingIds = ids.Except(found.Select(x => x.InternalId)).Select(x => x.ToString()).ToArray(), items = result };
|
||||
}
|
||||
public static object Media(BaseItemDto item) => item.MediaSources?.Select(source => new
|
||||
{
|
||||
id = source.Id,
|
||||
name = source.Name,
|
||||
path = ToolSupport.SafePath(source.Path),
|
||||
container = source.Container,
|
||||
sizeBytes = source.Size,
|
||||
runtimeTicks = source.RunTimeTicks,
|
||||
streams = source.MediaStreams?.Select(stream => new
|
||||
{
|
||||
type = stream.Type.ToString(),
|
||||
codec = stream.Codec,
|
||||
language = stream.Language,
|
||||
width = stream.Width,
|
||||
height = stream.Height,
|
||||
videoRange = stream.VideoRange,
|
||||
extendedVideoType = stream.ExtendedVideoType.ToString(),
|
||||
channels = stream.Channels,
|
||||
bitrate = stream.BitRate,
|
||||
isDefault = stream.IsDefault,
|
||||
isForced = stream.IsForced,
|
||||
isExternal = stream.IsExternal,
|
||||
isTextSubtitle = stream.IsTextSubtitleStream
|
||||
}).ToArray()
|
||||
}).ToArray();
|
||||
public static string Language(string value)
|
||||
{
|
||||
var language = value?.Trim().ToLowerInvariant();
|
||||
return language switch { "de" or "ger" or "deu" => "deu", "en" or "eng" => "eng", "fr" or "fre" or "fra" => "fra", _ => language };
|
||||
}
|
||||
public static string TrackState(BaseItemDto dto, MediaStreamType kind, string language)
|
||||
{
|
||||
if (dto == null) return "unknown";
|
||||
var lists = dto.MediaSources?.Length > 0 ? dto.MediaSources.Select(x => x.MediaStreams).ToArray() : null;
|
||||
var streams = lists == null ? dto.MediaStreams : lists.Where(x => x != null).SelectMany(x => x).ToArray();
|
||||
if (streams == null) return "unknown";
|
||||
var tracks = streams.Where(x => x.Type == kind).ToArray();
|
||||
if (tracks.Any(x => Language(x.Language) == Language(language))) return "present";
|
||||
if (tracks.Any(x => string.IsNullOrWhiteSpace(x.Language) || x.Language.Equals("und", StringComparison.OrdinalIgnoreCase)) || lists?.Any(x => x == null) == true) return "unknown";
|
||||
return "missing";
|
||||
}
|
||||
public object Tracks(ToolArgs a) => Page(a, (item, dto) =>
|
||||
{
|
||||
var row = ToolSupport.Row(item); row["language"] = Language(a.Text("language", "deu"));
|
||||
row["trackStatus"] = TrackState(dto, a.Text("kind", "audio") == "audio" ? MediaStreamType.Audio : MediaStreamType.Subtitle, a.Text("language", "deu"));
|
||||
row["burnedInSubtitleStatus"] = "unknown"; row["mediaSources"] = Media(dto); return row;
|
||||
}, true);
|
||||
(int? width, int? height) Dimensions(BaseItem item, ItemImageInfo image)
|
||||
{
|
||||
if (image == null) return (null, null);
|
||||
if (image.Width > 0 && image.Height > 0) return (image.Width, image.Height);
|
||||
if (image.IsLocalFile && s.Images != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var size = s.Images.GetImageSize(item, image).Item1;
|
||||
if (size.Width > 0 && size.Height > 0 && size.Width < int.MaxValue && size.Height < int.MaxValue) return ((int)size.Width, (int)size.Height);
|
||||
}
|
||||
catch { /* Unreadable image remains unknown; do not expose paths from exceptions. */ }
|
||||
}
|
||||
return (null, null);
|
||||
}
|
||||
public object Images(BaseItem item) => (item.ImageInfos ?? Array.Empty<ItemImageInfo>()).Where(x => x != null).Select(image =>
|
||||
{
|
||||
var size = Dimensions(item, image);
|
||||
return new
|
||||
{
|
||||
type = image.Type.ToString(),
|
||||
width = size.width,
|
||||
height = size.height,
|
||||
path = ToolSupport.SafePath(image.Path),
|
||||
isLocalFile = image.IsLocalFile,
|
||||
origin = "unknown",
|
||||
layout = !size.width.HasValue || !size.height.HasValue ? "unknown" : size.width > size.height ? "landscape" : size.width < size.height ? "portrait" : "square"
|
||||
};
|
||||
}).ToArray();
|
||||
public static string[] ImageReasons(BaseItem item, int? width = null, int? height = null)
|
||||
{
|
||||
var primary = item.ImageInfos?.FirstOrDefault(x => x?.Type == ImageType.Primary);
|
||||
if (primary == null) return new[] { "missing_primary" };
|
||||
var reasons = new List<string>();
|
||||
if ((width ?? primary.Width) <= 0 || (height ?? primary.Height) <= 0) reasons.Add("unknown_dimensions");
|
||||
else if ((width ?? primary.Width) > (height ?? primary.Height) && !(item is Episode)) reasons.Add("landscape_primary_needs_visual_review_not_proof_of_screenshot");
|
||||
return reasons.ToArray();
|
||||
}
|
||||
public object ImageAudit(ToolArgs a) => Page(a, (item, _) =>
|
||||
{
|
||||
var dimensions = Dimensions(item, item.ImageInfos?.FirstOrDefault(x => x?.Type == ImageType.Primary));
|
||||
var reasons = ImageReasons(item, dimensions.width, dimensions.height); if (a.Bool("onlyProblems", true) && reasons.Length == 0) return null;
|
||||
var row = ToolSupport.Row(item); row["images"] = Images(item); row["reviewReasons"] = reasons;
|
||||
row["hasPrimary"] = item.ImageInfos?.Any(x => x?.Type == ImageType.Primary) == true;
|
||||
row["origin"] = "unknown"; row["screenshotConfirmed"] = (bool?)null;
|
||||
row["nextStep"] = "Mit emby_image_review visuell prüfen. Auch ein Portrait ist kein Herkunftsnachweis.";
|
||||
return row;
|
||||
}, images: true);
|
||||
public object Metadata(ToolArgs a) => Page(a, (item, _) =>
|
||||
{
|
||||
var issues = new List<string>(); if (string.IsNullOrWhiteSpace(item.Name)) issues.Add("missing_title");
|
||||
if (item.ProviderIds == null || item.ProviderIds.Count == 0) issues.Add("missing_provider_ids");
|
||||
if (item.ImageInfos?.Any(x => x?.Type == ImageType.Primary) != true) issues.Add("missing_primary");
|
||||
if (!(item is Folder) && !item.RunTimeTicks.HasValue) issues.Add("unknown_runtime");
|
||||
if (item is Episode && (!item.ParentIndexNumber.HasValue || !item.IndexNumber.HasValue)) issues.Add("unknown_episode_numbering");
|
||||
if (issues.Count == 0) return null; var row = ToolSupport.Row(item); row["issues"] = issues; return row;
|
||||
}, images: true);
|
||||
public static string RatingStatus(string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return "missing";
|
||||
if (Regex.IsMatch(value.Trim(), @"^(FSK|DE)[ -]?(0|6|12|16|18)$", RegexOptions.IgnoreCase)) return "german";
|
||||
if (Regex.IsMatch(value.Trim(), @"^(US[-:]|UK[-:]|GB[-:]|AU[-:]|CA[-:]|FR[-:]|PG$|PG-13$|R$|G$|NC-17$|TV-|U$|12A$|R18$)", RegexOptions.IgnoreCase)) return "foreign";
|
||||
return "unknown";
|
||||
}
|
||||
public string[] GermanRatings() => s.Localization.GetParentalRatings("DE").Select(x => x.Name).Where(x => RatingStatus(x) == "german").Distinct().ToArray();
|
||||
public object Ratings(ToolArgs a)
|
||||
{
|
||||
var accepted = GermanRatings(); var page = Page(a, (item, _) =>
|
||||
{
|
||||
var status = RatingStatus(item.OfficialRating); var custom = string.IsNullOrWhiteSpace(item.CustomRating) ? null : item.CustomRating;
|
||||
var problem = status != "german" || !accepted.Contains(item.OfficialRating, StringComparer.Ordinal) || custom != null && (!string.Equals(custom, item.OfficialRating, StringComparison.Ordinal) || RatingStatus(custom) != "german");
|
||||
if (a.Bool("onlyProblems", true) && !problem) return null;
|
||||
var row = ToolSupport.Row(item); row["ratingStatus"] = status; row["officialRatingRecognized"] = accepted.Contains(item.OfficialRating, StringComparer.Ordinal); row["customRatingStatus"] = RatingStatus(custom);
|
||||
row["effectiveRating"] = custom ?? item.OfficialRating; row["effectiveRatingStatus"] = RatingStatus(custom ?? item.OfficialRating);
|
||||
row["customOverride"] = custom != null; row["inheritedRatingEvaluated"] = false; row["researchHint"] = "Titel/Jahr/Provider-ID UND konkrete Fassung/Medium prüfen. Keine automatische Umrechnung.";
|
||||
return row;
|
||||
});
|
||||
return new { acceptedGermanRatings = accepted, page };
|
||||
}
|
||||
public object Changes(ToolArgs a)
|
||||
{
|
||||
var since = a.Date("since").Value;
|
||||
return new
|
||||
{
|
||||
since,
|
||||
deletionsKnown = false,
|
||||
items = Page(a, (item, _) =>
|
||||
{
|
||||
if (item.DateCreated < since && item.DateLastSaved < since && item.DateModified < since) return null;
|
||||
var row = ToolSupport.Row(item); row["changeKind"] = item.DateCreated >= since ? "added" : "modified_or_saved"; return row;
|
||||
})
|
||||
};
|
||||
}
|
||||
public object Duplicates(ToolArgs a)
|
||||
{
|
||||
var ids = Ids(Scope(a)); var revision = Revision(ids); CheckRevision(a, revision);
|
||||
var groups = new Dictionary<string, List<Dictionary<string, object>>>(StringComparer.OrdinalIgnoreCase);
|
||||
for (int offset=0;offset<ids.Length;offset+=200)
|
||||
{
|
||||
var options=Options(media:true);var items=Load(ids.Skip(offset).Take(200).ToArray(),options);
|
||||
var dtos=s.Dto.GetBaseItemDtos(items,options,null);
|
||||
if(dtos==null||dtos.Length!=items.Length)throw new ToolOperationException("Unvollständige Versionsdaten.");
|
||||
for(int i=0;i<items.Length;i++)
|
||||
{
|
||||
var item=items[i];
|
||||
foreach (var provider in item.ProviderIds ?? new ProviderIdDictionary())
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(provider.Value)) continue;
|
||||
var key = item.GetType().Name + ":" + provider.Key + ":" + provider.Value;
|
||||
if (item is Episode) { if (!item.ParentIndexNumber.HasValue || !item.IndexNumber.HasValue) continue; key += ":" + item.SeriesId + ":" + item.ParentIndexNumber + ":" + item.IndexNumber; }
|
||||
if (!groups.TryGetValue(key, out var group)) groups[key] = group = new List<Dictionary<string, object>>();
|
||||
group.Add(ToolSupport.Row(item));
|
||||
}
|
||||
// Emby may group multiple files into ONE item; provider-ID duplicates alone miss these.
|
||||
if(dtos[i]?.MediaSources?.Length>1)
|
||||
{
|
||||
var versions=new List<Dictionary<string,object>>();
|
||||
foreach(var source in dtos[i].MediaSources)
|
||||
{
|
||||
var row=ToolSupport.Row(item);
|
||||
row["mediaSource"]=new{id=source.Id,name=source.Name,path=ToolSupport.SafePath(source.Path),container=source.Container,sizeBytes=source.Size,runtimeTicks=source.RunTimeTicks};
|
||||
versions.Add(row);
|
||||
}
|
||||
groups["media_versions:"+item.InternalId]=versions;
|
||||
}
|
||||
}
|
||||
}
|
||||
var candidates = groups.Where(g => g.Value.Count > 1).OrderBy(g => g.Key, StringComparer.Ordinal).ToArray();
|
||||
int start = a.Int("start", 0), limit = a.Int("limit", 100); var selected = candidates.Skip(start).Take(limit).Select(g => new { evidence = g.Key, confidence = g.Key.StartsWith("media_versions:",StringComparison.Ordinal)?"multiple_media_sources_not_file_equality":"same_provider_identity_not_file_equality", memberTotal = g.Value.Count, memberStart = a.Int("memberStart", 0), memberReturned = g.Value.Skip(a.Int("memberStart", 0)).Take(a.Int("memberLimit", 50)).Count(), memberHasMore = (long)a.Int("memberStart", 0) + a.Int("memberLimit", 50) < g.Value.Count, items = g.Value.Skip(a.Int("memberStart", 0)).Take(a.Int("memberLimit", 50)).ToArray() }).ToArray();
|
||||
return new
|
||||
{
|
||||
scanned = ids.Length,
|
||||
total = candidates.Length,
|
||||
returned = selected.Length,
|
||||
hasMore = (long)start + selected.Length < candidates.Length,
|
||||
nextStart = (long)start + selected.Length < candidates.Length ? (int?)(start + selected.Length) : null,
|
||||
inventoryRevision = revision,
|
||||
note = "Eine Item-Gruppe kann unter mehreren Provider-IDs auftauchen. Schnittfassungen nicht automatisch zusammenführen; mediaSources per batch_details vergleichen.",
|
||||
groups = selected
|
||||
};
|
||||
}
|
||||
public object MissingEpisodes(ToolArgs a)
|
||||
{
|
||||
var series = ToolSupport.Item(s.Library, a.Text("seriesId")) as Series ?? throw new ToolInputException("seriesId ist keine Series.");
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(45));
|
||||
var remote = s.Providers.GetAllEpisodes(series, s.Library.GetLibraryOptions(series), timeout.Token).GetAwaiter().GetResult();
|
||||
if (remote == null || remote.Length == 0) return new { status = "unknown", reason = "Konfigurierte Provider lieferten keine Referenzepisoden; daraus folgt keine Vollständigkeit." } as object;
|
||||
if (remote.Length > 100000) throw new ToolOperationException("Provider-Referenzliste zu groß.");
|
||||
var ids = Ids(new InternalItemsQuery { SeriesIds = new[] { series.InternalId }, IncludeItemTypes = new[] { "Episode" }, Recursive = true, IsVirtualItem = false, GroupByPresentationUniqueKey = false });
|
||||
var local = All(ids).OfType<Episode>().ToArray();
|
||||
int? season = a.Has("season") ? a.Int("season", 0) : null;
|
||||
var relevant = remote.Where(r => !season.HasValue || r.ParentIndexNumber == season).ToArray();
|
||||
var results = new List<object>(); int unknown = 0, present = 0, upcoming = 0, matchedByProvider = 0, matchedByNumber = 0;
|
||||
foreach (var r in relevant)
|
||||
{
|
||||
bool providerMatch = local.Any(l => r.ProviderIds != null && l.ProviderIds != null && r.ProviderIds.Any(p => l.ProviderIds.TryGetValue(p.Key, out var v) && v == p.Value && !string.IsNullOrWhiteSpace(v)));
|
||||
bool numberMatch = r.ParentIndexNumber.HasValue && r.IndexNumber.HasValue && local.Any(l => l.ParentIndexNumber == r.ParentIndexNumber && l.IndexNumber.HasValue && l.IndexNumber <= r.IndexNumber && (l.IndexNumberEnd ?? l.IndexNumber) >= r.IndexNumber);
|
||||
if (providerMatch || numberMatch) { present++; if (providerMatch) matchedByProvider++; else matchedByNumber++; continue; }
|
||||
if (r.PremiereDate > DateTimeOffset.UtcNow) { upcoming++; continue; }
|
||||
if (!r.ParentIndexNumber.HasValue || !r.IndexNumber.HasValue) { unknown++; continue; }
|
||||
results.Add(new
|
||||
{
|
||||
title = r.Name,
|
||||
seasonNumber = r.ParentIndexNumber,
|
||||
episodeNumber = r.IndexNumber,
|
||||
providerIds = r.ProviderIds,
|
||||
premiereDate = r.PremiereDate,
|
||||
provider = r.SearchProviderName,
|
||||
status = "missing_candidate",
|
||||
airDateKnown = r.PremiereDate.HasValue
|
||||
});
|
||||
}
|
||||
int start = a.Int("start", 0), limit = a.Int("limit", 100); var page = results.Skip(start).Take(limit).ToArray();
|
||||
return new
|
||||
{
|
||||
seriesId = series.InternalId.ToString(),
|
||||
referenceCount = relevant.Length,
|
||||
localCount = local.Length,
|
||||
presentCandidates = present,
|
||||
matchedByProvider,
|
||||
matchedByNumber,
|
||||
upcoming,
|
||||
unmatchableReference = unknown,
|
||||
localWithUnknownNumbers = local.Count(x => !x.ParentIndexNumber.HasValue || !x.IndexNumber.HasValue),
|
||||
total = results.Count,
|
||||
returned = page.Length,
|
||||
hasMore = (long)start + page.Length < results.Count,
|
||||
nextStart = (long)start + page.Length < results.Count ? (int?)(start + page.Length) : null,
|
||||
status = "provider_comparison_candidates",
|
||||
warning = "Providerlisten können unvollständig sein; Reihenfolge/Fassung und unbekannte lokale Nummerierung prüfen. Nicht indexierte Dateien wurden nicht gesucht.",
|
||||
items = page
|
||||
};
|
||||
}
|
||||
public object ImageReview(ToolArgs a)
|
||||
{
|
||||
if (a.Has("id") == a.Has("ids")) throw new ToolInputException("Genau eines von id oder ids angeben.");
|
||||
var ids = (a.Has("id") ? new[] { a.Text("id") } : a.Strings("ids")).Select(id => ToolSupport.Id(s.Library, id)).Distinct().ToArray();
|
||||
var items = Load(ids, Options(images: true)); var kind = Enum.Parse<ImageType>(a.Text("imageType", "Primary"));
|
||||
var content = new List<object>(); long totalBytes = 0;
|
||||
foreach (var item in items)
|
||||
{
|
||||
var image = (item.ImageInfos ?? Array.Empty<ItemImageInfo>()).Where(x => x?.Type == kind).Skip(a.Int("index", 0)).FirstOrDefault();
|
||||
string error = null; byte[] bytes = null;
|
||||
if (image == null) error = "requested_image_missing";
|
||||
else if (!image.IsLocalFile || string.IsNullOrWhiteSpace(image.Path)) error = "image_not_local_no_download_attempted";
|
||||
else try
|
||||
{
|
||||
using var memory = new LimitedImageStream();
|
||||
if (s.Images != null)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
||||
s.Images.ProcessImage(new MediaBrowser.Controller.Drawing.ImageProcessingOptions
|
||||
{
|
||||
Item = item,
|
||||
ItemId = item.InternalId,
|
||||
Image = image,
|
||||
ImageIndex = a.Int("index", 0),
|
||||
MaxWidth = 768,
|
||||
MaxHeight = 768,
|
||||
Quality = 75,
|
||||
RequiresAutoOrientation = true,
|
||||
SupportedOutputFormats = new[] { MediaBrowser.Model.Drawing.ImageFormat.Jpg }
|
||||
}, memory, timeout.Token).GetAwaiter().GetResult();
|
||||
}
|
||||
else { using var input = new FileStream(image.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); input.CopyTo(memory); }
|
||||
bytes = memory.ToArray();
|
||||
if (totalBytes + bytes.Length > 8 * 1024 * 1024) { error = "batch_image_budget_exceeded_retry_smaller_batch"; bytes = null; }
|
||||
}
|
||||
catch { error = "image_unreadable_or_preview_limit_exceeded"; }
|
||||
string mime = bytes == null ? null : bytes.Length >= 3 && bytes[0] == 255 && bytes[1] == 216 && bytes[2] == 255 ? "image/jpeg" :
|
||||
bytes.Length >= 8 && bytes[0] == 137 && bytes[1] == 80 && bytes[2] == 78 && bytes[3] == 71 ? "image/png" :
|
||||
bytes.Length >= 12 && System.Text.Encoding.ASCII.GetString(bytes, 0, 4) == "RIFF" && System.Text.Encoding.ASCII.GetString(bytes, 8, 4) == "WEBP" ? "image/webp" : null;
|
||||
if (bytes != null && mime == null) error = "unsupported_image_format";
|
||||
content.Add(new { type = "text", text = JsonSerializer.Serialize(new { id = item.InternalId.ToString(), title = item.Name, imageType = kind.ToString(), origin = "unknown", error, note = "Visuelle Einordnung ist keine verifizierte Herkunft." }) });
|
||||
if (bytes != null && mime != null) { totalBytes += bytes.Length; content.Add(new { type = "image", mimeType = mime, data = Convert.ToBase64String(bytes) }); }
|
||||
}
|
||||
return new McpContentResult { Content = content.ToArray() };
|
||||
}
|
||||
sealed class LimitedImageStream : MemoryStream
|
||||
{
|
||||
void Check(int count) { if (Position + count > 1024 * 1024) throw new IOException("Preview budget exceeded"); }
|
||||
public override void Write(byte[] buffer, int offset, int count) { Check(count); base.Write(buffer, offset, count); }
|
||||
public override void Write(ReadOnlySpan<byte> buffer) { Check(buffer.Length); base.Write(buffer); }
|
||||
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { Check(count); return base.WriteAsync(buffer, offset, count, token); }
|
||||
public override System.Threading.Tasks.ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken token = default) { Check(buffer.Length); return base.WriteAsync(buffer, token); }
|
||||
}
|
||||
|
||||
}
|
||||
public sealed class McpContentResult { public object[] Content { get; set; } }
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Entities.TV;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Providers;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Session;
|
||||
|
||||
namespace eMCPy.Mcp
|
||||
{
|
||||
public sealed class ManagementOperations
|
||||
{
|
||||
readonly EmbyServices s;
|
||||
readonly LibraryOperations library;
|
||||
static readonly object MutationLock = new object();
|
||||
public ManagementOperations(EmbyServices services) { s = services; library = new LibraryOperations(s); }
|
||||
public object Users() => new { users = s.Users.GetUserList(new MediaBrowser.Model.Querying.UserQuery()).Select(u => new { id = u.Id.ToString(), name = u.Name }).ToArray() };
|
||||
public object Diagnostics() => new
|
||||
{
|
||||
serverVersion = s.Host?.ApplicationVersion?.ToString(),
|
||||
pluginVersion = typeof(ManagementOperations).Assembly.GetName().Version?.ToString(3),
|
||||
startupComplete = s.Host?.IsStartupComplete,
|
||||
pendingRestart = s.Host?.HasPendingRestart,
|
||||
writesEnabled = s.Configuration().EnableWriteTools,
|
||||
authenticatedWritesAvailable = s.Configuration().EnableWriteTools && !string.IsNullOrWhiteSpace(s.Configuration().ApiKey),
|
||||
services = new { library = s.Library != null, dto = s.Dto != null, providers = s.Providers != null, sessions = s.Sessions != null, tasks = s.Tasks != null, ratings = s.Localization != null },
|
||||
refreshQueue = s.Providers?.GetRefreshQueue().Select(x => new { id = x.Item1.ToString(), recursive = x.Item2.Recursive, progress = s.Providers.GetRefreshProgress(x.Item1) }).ToArray(),
|
||||
scheduledTasks = s.Tasks?.ScheduledTasks?.Select(t => new { id = t.Id, name = t.Name, key = t.ScheduledTask?.Key, state = t.State.ToString(), progress = t.CurrentProgress, lastStatus = t.LastExecutionResult?.Status.ToString() }).ToArray()
|
||||
};
|
||||
public object Playback(ToolArgs a)
|
||||
{
|
||||
var sessions = s.Sessions.Sessions.Where(x => !a.Has("sessionId") || x.Id == a.Text("sessionId")).Where(x => x.NowPlayingItem != null).ToArray();
|
||||
return new
|
||||
{
|
||||
sessions = sessions.Select(x => new
|
||||
{
|
||||
sessionId = x.Id,
|
||||
device = x.DeviceName,
|
||||
client = x.Client,
|
||||
userId = x.UserId,
|
||||
itemId = x.NowPlayingItem?.Id,
|
||||
title = x.NowPlayingItem?.Name,
|
||||
paused = x.PlayState?.IsPaused,
|
||||
positionTicks = x.PlayState?.PositionTicks,
|
||||
playMethod = x.PlayState?.PlayMethod?.ToString(),
|
||||
source = x.PlayState?.MediaSource == null ? null : new { id = x.PlayState.MediaSource.Id, container = x.PlayState.MediaSource.Container, bitrate = x.PlayState.MediaSource.Bitrate },
|
||||
transcoding = x.TranscodingInfo == null ? null : new
|
||||
{
|
||||
reasons = x.TranscodingInfo.TranscodeReasons?.Select(r => r.ToString()).ToArray(),
|
||||
isVideoDirect = x.TranscodingInfo.IsVideoDirect,
|
||||
isAudioDirect = x.TranscodingInfo.IsAudioDirect,
|
||||
videoCodec = x.TranscodingInfo.VideoCodec,
|
||||
audioCodec = x.TranscodingInfo.AudioCodec,
|
||||
bitrate = x.TranscodingInfo.Bitrate,
|
||||
hardwareEncoder = x.TranscodingInfo.VideoEncoderIsHardware,
|
||||
encoder = x.TranscodingInfo.VideoEncoder,
|
||||
hardwareDecoder = x.TranscodingInfo.VideoDecoderIsHardware,
|
||||
decoder = x.TranscodingInfo.VideoDecoder
|
||||
},
|
||||
reasonStatus = x.TranscodingInfo?.TranscodeReasons?.Length > 0 ? "reported_by_emby" : "unknown"
|
||||
}).ToArray()
|
||||
};
|
||||
}
|
||||
void Journal(object entry)
|
||||
{
|
||||
Directory.CreateDirectory(s.StateDirectory);
|
||||
var path = Path.Combine(s.StateDirectory, "actions.jsonl");
|
||||
if (File.Exists(path) && new FileInfo(path).Length > 1024 * 1024) File.Move(path, path + ".previous", true);
|
||||
File.AppendAllText(path, JsonSerializer.Serialize(entry) + Environment.NewLine);
|
||||
}
|
||||
static bool HasCredentialParameter(string value)
|
||||
{
|
||||
return value.TrimStart('?', '#').Split('&').Any(part =>
|
||||
System.Text.RegularExpressions.Regex.IsMatch(Uri.UnescapeDataString(part.Split('=')[0]),
|
||||
@"^(api[-_]?key|access[-_]?token|token|password|secret|auth|authorization|signature|sig)$", System.Text.RegularExpressions.RegexOptions.IgnoreCase));
|
||||
}
|
||||
public object SetRating(ToolArgs a)
|
||||
{
|
||||
bool dry = a.Bool("dryRun", true); if (!dry) ToolSupport.RequireWrite(s, a);
|
||||
var rating = a.Text("rating"); if (!library.GermanRatings().Contains(rating, StringComparer.Ordinal)) throw new ToolInputException("rating ist kein vom Server unterstützter deutscher Wert.");
|
||||
if (!Uri.TryCreate(a.Text("sourceUrl"), UriKind.Absolute, out var source) || source.Scheme != "https" || !string.IsNullOrEmpty(source.UserInfo) || HasCredentialParameter(source.Query) || HasCredentialParameter(source.Fragment))
|
||||
throw new ToolInputException("Quellenbeleg muss eine HTTPS-URL ohne Zugangsdaten oder Token-Parameter sein.");
|
||||
lock (MutationLock)
|
||||
{
|
||||
var item = ToolSupport.Item(s.Library, a.Text("id"));
|
||||
if (!(item is MediaBrowser.Controller.Entities.Movies.Movie || item is Series || item is Season || item is Episode || item is Video)) throw new ToolInputException("FSK-Änderung nur für Movie/Series/Season/Episode/Video.");
|
||||
if (item.OfficialRating != a.Text("expectedOfficialRating") || item.CustomRating != a.Text("expectedCustomRating")) throw new ToolOperationException("Freigabewert inzwischen geändert; erneut auslesen.");
|
||||
var previous = item.OfficialRating; var custom = item.CustomRating; var locks = item.LockedFields;
|
||||
var newCustom = a.Bool("clearCustomRating") ? null : custom;
|
||||
var change = new
|
||||
{
|
||||
itemId = item.InternalId.ToString(),
|
||||
title = item.Name,
|
||||
year = item.ProductionYear,
|
||||
previousOfficialRating = previous,
|
||||
newOfficialRating = rating,
|
||||
previousCustomRating = custom,
|
||||
newCustomRating = newCustom,
|
||||
lockField = a.Bool("lockField"),
|
||||
sourceUrl = source.AbsoluteUri,
|
||||
evidence = a.Text("evidence"),
|
||||
evidenceStatus = "provided_by_caller_not_independently_verified",
|
||||
effectiveItemRating = newCustom ?? rating,
|
||||
warning = newCustom != null ? "CustomRating bleibt erhalten und kann OfficialRating übersteuern." : null
|
||||
};
|
||||
if (dry) return new { dryRun = true, change };
|
||||
var operationId = Guid.NewGuid().ToString();
|
||||
Journal(new { operationId, time = DateTimeOffset.UtcNow, action = "set_rating", status = "requested", change });
|
||||
try
|
||||
{
|
||||
item.OfficialRating = rating; item.CustomRating = newCustom;
|
||||
if (a.Bool("lockField")) item.LockedFields = (locks ?? Array.Empty<MetadataFields>()).Concat(new[] { MetadataFields.OfficialRating }).Distinct().ToArray();
|
||||
s.Library.UpdateItem(item, null, ItemUpdateType.MetadataEdit);
|
||||
}
|
||||
catch
|
||||
{
|
||||
item.OfficialRating = previous; item.CustomRating = custom; item.LockedFields = locks;
|
||||
Journal(new { operationId, time = DateTimeOffset.UtcNow, action = "set_rating", status = "save_failed_recheck_item" });
|
||||
throw new ToolOperationException("Speichern fehlgeschlagen. Aktuellen Emby-Wert vor erneutem Versuch prüfen.");
|
||||
}
|
||||
// After save, logging failure must never be disguised as a failed mutation/retried blindly.
|
||||
bool journalComplete = true; try { Journal(new { operationId, time = DateTimeOffset.UtcNow, action = "set_rating", status = "saved" }); } catch { journalComplete = false; }
|
||||
return new { dryRun = false, saved = true, operationId, journalComplete, change };
|
||||
}
|
||||
}
|
||||
public object Played(ToolArgs a)
|
||||
{
|
||||
bool dry = a.Bool("dryRun", true); if (!dry) ToolSupport.RequireWrite(s, a);
|
||||
lock (MutationLock)
|
||||
{
|
||||
var item = ToolSupport.Item(s.Library, a.Text("id")); if (item is Folder) throw new ToolInputException("Kein rekursives Markieren von Ordnern/Serien erlaubt.");
|
||||
var user = ToolSupport.User(s, a.Text("userId")); var data = s.UserData.GetUserData(user, item);
|
||||
if (data.Played != a.Bool("expectedPlayed")) throw new ToolOperationException("Gesehen-Status inzwischen geändert.");
|
||||
var target = a.Bool("played");
|
||||
if (!dry)
|
||||
{
|
||||
var original = data.Played; data.Played = target;
|
||||
try { s.UserData.SaveUserData(user, item, data, UserDataSaveReason.TogglePlayed, CancellationToken.None); } catch { data.Played = original; throw; }
|
||||
}
|
||||
return new { dryRun = dry, id = item.InternalId.ToString(), userId = user.Id.ToString(), previousPlayed = a.Bool("expectedPlayed"), played = target, note = "Ändert nur Played, keine erfundenen Wiedergabezeiten/PlayCounts." };
|
||||
}
|
||||
}
|
||||
public object Pause(ToolArgs a)
|
||||
{
|
||||
bool dry = a.Bool("dryRun", true); if (!dry) ToolSupport.RequireWrite(s, a);
|
||||
var session = s.Sessions.Sessions.FirstOrDefault(x => x.Id == a.Text("sessionId")) ?? throw new ToolInputException("Sitzung nicht gefunden.");
|
||||
if (session.NowPlayingItem == null || ToolSupport.Id(s.Library, session.NowPlayingItem.Id) != ToolSupport.Id(s.Library, a.Text("expectedItemId"))) throw new ToolOperationException("Sitzung spielt inzwischen ein anderes oder kein Item.");
|
||||
if (!session.SupportsRemoteControl) throw new ToolOperationException("Sitzung unterstützt keine Fernsteuerung.");
|
||||
if (!dry) { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)); s.Sessions.SendPlaystateCommand(null, session.Id, new PlaystateRequest { Command = PlaystateCommand.Pause }, timeout.Token).GetAwaiter().GetResult(); }
|
||||
return new { dryRun = dry, sessionId = session.Id, itemId = session.NowPlayingItem.Id, status = dry ? "preview" : "pause_command_sent_not_yet_confirmed" };
|
||||
}
|
||||
public object Refresh(ToolArgs a, bool scan)
|
||||
{
|
||||
bool dry = a.Bool("dryRun", true); if (!dry) ToolSupport.RequireWrite(s, a);
|
||||
var item = ToolSupport.Item(s.Library, a.Text(scan ? "libraryId" : "id"));
|
||||
if (scan)
|
||||
{
|
||||
var folders = s.Library.GetVirtualFolders();
|
||||
if (!folders.Any(f => ToolSupport.Id(s.Library, f.ItemId) == item.InternalId)) throw new ToolInputException("libraryId muss eine registrierte Bibliothek sein.");
|
||||
}
|
||||
else if (item is Folder && !(item is Series || item is Season)) throw new ToolInputException("Für Bibliotheksordner scan_library verwenden.");
|
||||
if (!dry)
|
||||
{
|
||||
var options = new MetadataRefreshOptions(s.FileSystem)
|
||||
{
|
||||
Recursive = scan,
|
||||
MetadataRefreshMode = scan ? MetadataRefreshMode.ValidationOnly : MetadataRefreshMode.Default,
|
||||
ImageRefreshMode = MetadataRefreshMode.Default,
|
||||
ReplaceAllMetadata = false,
|
||||
ReplaceAllImages = false,
|
||||
ReplaceThumbnailImages = false,
|
||||
EnableSubtitleDownloading = false,
|
||||
EnableThumbnailImageExtraction = false
|
||||
};
|
||||
s.Providers.QueueRefresh(item.InternalId, options, RefreshPriority.Low);
|
||||
}
|
||||
return new { dryRun = dry, id = item.InternalId.ToString(), recursive = scan, status = dry ? "preview" : "queued", complete = false };
|
||||
}
|
||||
public object Snapshot(ToolArgs a)
|
||||
{
|
||||
// Explicitly requested local inventory bookkeeping, not a media modification.
|
||||
lock (MutationLock)
|
||||
{
|
||||
var scope = library.Scope(a); scope.IncludeItemTypes = LibraryOperations.DefaultTypes.Concat(new[] { "Audio", "MusicAlbum", "MusicArtist", "Photo" }).ToArray(); var ids = library.Ids(scope); var id = ToolSupport.Id(s.Library, a.Text("libraryId"));
|
||||
var path = Path.Combine(s.StateDirectory, "snapshot-" + id + ".json");
|
||||
var current = library.All(ids).Select(x => new SnapshotRow { Id = x.InternalId, Title = x.Name, Modified = x.DateLastSaved }).ToArray();
|
||||
if (a.Text("operation") == "capture")
|
||||
{
|
||||
if (File.Exists(path) && !a.Bool("replace")) throw new ToolOperationException("Baseline existiert. Ersetzen benötigt replace=true.");
|
||||
Directory.CreateDirectory(s.StateDirectory);
|
||||
if (!File.Exists(path) && Directory.GetFiles(s.StateDirectory, "snapshot-*.json").Length >= 20) throw new ToolOperationException("Maximal 20 Bibliotheks-Baselines.");
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
File.WriteAllText(path + ".tmp", JsonSerializer.Serialize(new SnapshotData { CapturedAt = now, Rows = current })); File.Move(path + ".tmp", path, true);
|
||||
return new { capturedAt = now, count = current.Length, libraryId = id.ToString(), stored = true, note = "Baseline ersetzt nur auf expliziten Aufruf, keine Mediendatei-Sicherung." };
|
||||
}
|
||||
if (!File.Exists(path)) throw new ToolOperationException("Keine Baseline. Zuerst capture aufrufen.");
|
||||
if (new FileInfo(path).Length > 64 * 1024 * 1024) throw new ToolOperationException("Baseline zu groß.");
|
||||
var baseline = JsonSerializer.Deserialize<SnapshotData>(File.ReadAllText(path));
|
||||
if (baseline?.Rows == null) throw new ToolOperationException("Ungültige Baseline.");
|
||||
var before = baseline.Rows.ToDictionary(x => x.Id); var after = current.ToDictionary(x => x.Id);
|
||||
var changes = new List<object>();
|
||||
foreach (var row in current) if (!before.TryGetValue(row.Id, out var old)) changes.Add(new { id = row.Id.ToString(), title = row.Title, change = "added" }); else if (old.Modified != row.Modified || old.Title != row.Title) changes.Add(new { id = row.Id.ToString(), title = row.Title, change = "changed" });
|
||||
foreach (var row in baseline.Rows) if (!after.ContainsKey(row.Id)) changes.Add(new { id = row.Id.ToString(), title = row.Title, change = "removed_from_emby_index" });
|
||||
int start = a.Int("start", 0), limit = a.Int("limit", 100); var page = changes.Skip(start).Take(limit).ToArray();
|
||||
return new
|
||||
{
|
||||
baseline.CapturedAt,
|
||||
comparedAt = DateTimeOffset.UtcNow,
|
||||
total = changes.Count,
|
||||
returned = page.Length,
|
||||
hasMore = (long)start + page.Length < changes.Count,
|
||||
nextStart = (long)start + page.Length < changes.Count ? (int?)(start + page.Length) : null,
|
||||
baselineUnchanged = true,
|
||||
changes = page
|
||||
};
|
||||
}
|
||||
}
|
||||
public sealed class SnapshotRow { public long Id { get; set; } public string Title { get; set; } public DateTimeOffset Modified { get; set; } }
|
||||
public sealed class SnapshotData { public DateTimeOffset CapturedAt { get; set; } public SnapshotRow[] Rows { get; set; } }
|
||||
}
|
||||
}
|
||||
@@ -155,21 +155,34 @@ namespace eMCPy.Mcp
|
||||
result = ToolMissingMetadata(hasArgs ? args : default);
|
||||
break;
|
||||
default:
|
||||
return RpcError(id, -32602, "Unbekanntes Tool: " + name);
|
||||
if (!AdvancedSchemas.IsKnown(name))
|
||||
return RpcError(id, -32602, "Unbekanntes Tool: " + name);
|
||||
if (Plugin.Instance?.AdvancedServices == null) throw new InvalidOperationException("Emby-Dienste sind noch nicht bereit.");
|
||||
result = new AdvancedTools(Plugin.Instance.AdvancedServices).Execute(name, args);
|
||||
break;
|
||||
}
|
||||
|
||||
if (result is McpContentResult imageResult)
|
||||
return RpcResult(id, new {content=imageResult.Content,isError=false});
|
||||
return RpcResult(id, new
|
||||
{
|
||||
content = new[] { new { type = "text", text = name == "emby_series_inventory" ? JsonSerializer.Serialize(result) : _json.SerializeToString(result) } },
|
||||
content = new[] { new { type = "text", text = (name == "emby_series_inventory" || AdvancedSchemas.IsKnown(name)) ? JsonSerializer.Serialize(result) : _json.SerializeToString(result) } },
|
||||
isError = false
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("[eMCPy] Tool-Fehler: " + name, ex);
|
||||
string errorMessage;
|
||||
if (AdvancedSchemas.IsKnown(name))
|
||||
{
|
||||
var diagnosis = Guid.NewGuid().ToString("N").Substring(0,12);
|
||||
_logger.Error("[eMCPy] Tool-Fehler {0}, Diagnose {1}, Typ {2}", name, diagnosis, ex.GetType().Name);
|
||||
errorMessage = ex is ToolInputException || ex is ToolOperationException ? ex.Message : "Emby-Abfrage fehlgeschlagen. Diagnose: " + diagnosis;
|
||||
}
|
||||
else { _logger.ErrorException("[eMCPy] Tool-Fehler: " + name, ex); errorMessage = ex.Message; }
|
||||
return RpcResult(id, new
|
||||
{
|
||||
content = new[] { new { type = "text", text = "Fehler: " + ex.Message } },
|
||||
content = new[] { new { type = "text", text = "Fehler: " + errorMessage } },
|
||||
isError = true
|
||||
});
|
||||
}
|
||||
@@ -197,7 +210,7 @@ namespace eMCPy.Mcp
|
||||
|
||||
private List<object> GetToolDefinitions()
|
||||
{
|
||||
return new List<object>
|
||||
var definitions = new List<object>
|
||||
{
|
||||
SeriesInventory.Definition,
|
||||
new
|
||||
@@ -414,6 +427,8 @@ namespace eMCPy.Mcp
|
||||
}
|
||||
}
|
||||
};
|
||||
definitions.AddRange(AdvancedSchemas.Definitions());
|
||||
return definitions;
|
||||
}
|
||||
|
||||
// ---------- Helper ----------
|
||||
@@ -555,7 +570,7 @@ namespace eMCPy.Mcp
|
||||
return new
|
||||
{
|
||||
serverName = "Emby",
|
||||
embyVersion = "4.9.5.0",
|
||||
embyVersion = Plugin.Instance?.ServerAppHost?.ApplicationVersion?.ToString(),
|
||||
pluginName = "eMCPy",
|
||||
pluginVersion = GetVersion(),
|
||||
mcpEnabled = cfg?.EnableMcpServer ?? false,
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using MediaBrowser.Controller;
|
||||
using MediaBrowser.Controller.Dto;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Providers;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Tasks;
|
||||
|
||||
namespace eMCPy.Mcp
|
||||
{
|
||||
public sealed class ToolInputException : ArgumentException { public ToolInputException(string message) : base(message) { } }
|
||||
public sealed class ToolOperationException : InvalidOperationException { public ToolOperationException(string message) : base(message) { } }
|
||||
public sealed class EmbyServices
|
||||
{
|
||||
public ILibraryManager Library;
|
||||
public IDtoService Dto;
|
||||
public IUserManager Users;
|
||||
public IUserDataManager UserData;
|
||||
public ISessionManager Sessions;
|
||||
public IProviderManager Providers;
|
||||
public ITaskManager Tasks;
|
||||
public ILocalizationManager Localization;
|
||||
public IFileSystem FileSystem;
|
||||
public MediaBrowser.Controller.Drawing.IImageProcessor Images;
|
||||
public IServerApplicationHost Host;
|
||||
public Func<PluginConfiguration> Configuration;
|
||||
public string StateDirectory;
|
||||
}
|
||||
|
||||
public sealed class ToolArgs
|
||||
{
|
||||
public JsonElement Json { get; }
|
||||
public ToolArgs(JsonElement json) { Json = json; }
|
||||
public bool Has(string key) => Json.ValueKind == JsonValueKind.Object && Json.TryGetProperty(key, out _);
|
||||
public string Text(string key, string fallback = null) => Has(key) && Json.GetProperty(key).ValueKind != JsonValueKind.Null ? Json.GetProperty(key).GetString() : fallback;
|
||||
public int Int(string key, int fallback) => Has(key) ? Json.GetProperty(key).GetInt32() : fallback;
|
||||
public bool Bool(string key, bool fallback = false) => Has(key) ? Json.GetProperty(key).GetBoolean() : fallback;
|
||||
public string[] Strings(string key) => Has(key) ? Json.GetProperty(key).EnumerateArray().Select(x => x.GetString()).ToArray() : Array.Empty<string>();
|
||||
public DateTimeOffset? Date(string key)
|
||||
{
|
||||
if (!Has(key)) return null;
|
||||
var text = Text(key);
|
||||
if (text == null || !(text.EndsWith("Z", StringComparison.OrdinalIgnoreCase) || System.Text.RegularExpressions.Regex.IsMatch(text, @"[+-]\d{2}:\d{2}$")) ||
|
||||
!DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var value))
|
||||
throw new ToolInputException(key + " benötigt einen ISO-Zeitstempel mit Zeitzone.");
|
||||
return value.ToUniversalTime();
|
||||
}
|
||||
}
|
||||
|
||||
public static class ToolSupport
|
||||
{
|
||||
public static long Id(ILibraryManager library, string id)
|
||||
{
|
||||
if (long.TryParse(id, NumberStyles.None, CultureInfo.InvariantCulture, out var number) && number > 0) return number;
|
||||
if (Guid.TryParse(id, out var guid) && guid != Guid.Empty)
|
||||
{
|
||||
var internalId = library.GetInternalId(guid);
|
||||
if (internalId > 0) return internalId;
|
||||
}
|
||||
throw new ToolInputException("Ungültige oder unbekannte Emby-ID.");
|
||||
}
|
||||
public static BaseItem Item(ILibraryManager library, string id) => library.GetItemById(Id(library, id)) ?? throw new ToolInputException("Item nicht gefunden.");
|
||||
public static User User(EmbyServices s, string id) => s.Users.GetUserById(id) ?? throw new ToolInputException("Benutzer nicht gefunden.");
|
||||
public static string Hash(string value)
|
||||
{
|
||||
using var h = SHA256.Create();
|
||||
return Convert.ToHexString(h.ComputeHash(Encoding.UTF8.GetBytes(value))).ToLowerInvariant();
|
||||
}
|
||||
public static string SafePath(string path)
|
||||
{
|
||||
// Media URLs may carry credentials; never return userinfo, query strings or fragments.
|
||||
if (path != null && Uri.TryCreate(path, UriKind.Absolute, out var uri) && !uri.IsFile)
|
||||
return new UriBuilder(uri) { UserName = "", Password = "", Query = "", Fragment = "" }.Uri.GetLeftPart(UriPartial.Path);
|
||||
return path;
|
||||
}
|
||||
public static Dictionary<string, object> Row(BaseItem item) => new Dictionary<string, object>
|
||||
{
|
||||
["id"] = item.InternalId.ToString(CultureInfo.InvariantCulture),
|
||||
["guid"] = item.Id.ToString(),
|
||||
["title"] = item.Name,
|
||||
["originalTitle"] = item.OriginalTitle,
|
||||
["type"] = item.GetType().Name,
|
||||
["year"] = item.ProductionYear,
|
||||
["providerIds"] = item.ProviderIds?.ToDictionary(x => x.Key, x => x.Value),
|
||||
["path"] = SafePath(item.Path),
|
||||
["runtimeTicks"] = item.RunTimeTicks,
|
||||
["officialRating"] = item.OfficialRating,
|
||||
["customRating"] = item.CustomRating,
|
||||
["dateCreated"] = item.DateCreated,
|
||||
["dateModified"] = item.DateModified,
|
||||
["dateLastSaved"] = item.DateLastSaved == default ? (DateTimeOffset?)null : item.DateLastSaved,
|
||||
["isVirtualItem"] = item.IsVirtualItem
|
||||
};
|
||||
public static void RequireWrite(EmbyServices s, ToolArgs a)
|
||||
{
|
||||
var config = s.Configuration();
|
||||
if (!config.EnableWriteTools || string.IsNullOrWhiteSpace(config.ApiKey))
|
||||
throw new ToolOperationException("Schreibwerkzeuge sind deaktiviert oder der MCP-API-Key fehlt. Im Emby-Plugin freischalten.");
|
||||
if (!a.Bool("confirm")) throw new ToolInputException("Für diese Einzelaktion ist confirm=true erforderlich.");
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -28,12 +28,15 @@ namespace eMCPy
|
||||
public MediaBrowser.Controller.Dto.IDtoService DtoService { get; set; }
|
||||
public IUserManager UserManager { get; set; }
|
||||
public IServerApplicationHost ServerAppHost { get; set; }
|
||||
public EmbyServices AdvancedServices { get; set; }
|
||||
public string StateDirectory { get; private set; }
|
||||
|
||||
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer,
|
||||
ILogManager logManager, IJsonSerializer jsonSerializer)
|
||||
: base(applicationPaths, xmlSerializer)
|
||||
{
|
||||
Instance = this;
|
||||
StateDirectory = Path.Combine(applicationPaths.DataPath, "emcpy");
|
||||
_logger = logManager.GetLogger(GetType().Name);
|
||||
_jsonSerializer = jsonSerializer;
|
||||
}
|
||||
@@ -57,9 +60,16 @@ namespace eMCPy
|
||||
/// </summary>
|
||||
public override void UpdateConfiguration(BasePluginConfiguration configuration)
|
||||
{
|
||||
var next = (PluginConfiguration)configuration;
|
||||
bool restart = Configuration.EnableMcpServer != next.EnableMcpServer || Configuration.McpPort != next.McpPort ||
|
||||
Configuration.ListenAddress != next.ListenAddress || Configuration.ApiKey != next.ApiKey;
|
||||
base.UpdateConfiguration(configuration);
|
||||
_logger.Info("[eMCPy] Configuration updated – MCP-Server wird neu gestartet.");
|
||||
RestartMcpServer();
|
||||
if (restart)
|
||||
{
|
||||
_logger.Info("[eMCPy] Listener-Konfiguration geändert – MCP-Server wird neu gestartet.");
|
||||
RestartMcpServer();
|
||||
}
|
||||
else _logger.Info("[eMCPy] Einstellungen gespeichert, kein Listener-Neustart erforderlich.");
|
||||
}
|
||||
|
||||
private void StartMcpServer()
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace eMCPy
|
||||
{
|
||||
public class PluginConfiguration : BasePluginConfiguration
|
||||
{
|
||||
public bool EnableWriteTools { get; set; } = false;
|
||||
public bool EnableMcpServer { get; set; } = true;
|
||||
public int McpPort { get; set; } = 8097;
|
||||
public string ListenAddress { get; set; } = "0.0.0.0";
|
||||
|
||||
@@ -11,7 +11,10 @@ namespace eMCPy
|
||||
/// </summary>
|
||||
public class ServiceRegistrar : IServerEntryPoint
|
||||
{
|
||||
public ServiceRegistrar(ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager, IServerApplicationHost serverAppHost, MediaBrowser.Controller.Dto.IDtoService dtoService)
|
||||
public ServiceRegistrar(ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager, IServerApplicationHost serverAppHost, MediaBrowser.Controller.Dto.IDtoService dtoService,
|
||||
MediaBrowser.Controller.Library.IUserDataManager userDataManager, MediaBrowser.Controller.Providers.IProviderManager providerManager,
|
||||
MediaBrowser.Model.Tasks.ITaskManager taskManager, MediaBrowser.Model.Globalization.ILocalizationManager localizationManager,
|
||||
MediaBrowser.Model.IO.IFileSystem fileSystem, MediaBrowser.Controller.Drawing.IImageProcessor imageProcessor)
|
||||
{
|
||||
if (Plugin.Instance != null)
|
||||
{
|
||||
@@ -20,6 +23,22 @@ namespace eMCPy
|
||||
Plugin.Instance.DtoService = dtoService;
|
||||
Plugin.Instance.UserManager = userManager;
|
||||
Plugin.Instance.ServerAppHost = serverAppHost;
|
||||
Plugin.Instance.AdvancedServices = new Mcp.EmbyServices
|
||||
{
|
||||
Library = libraryManager,
|
||||
Dto = dtoService,
|
||||
Users = userManager,
|
||||
UserData = userDataManager,
|
||||
Sessions = sessionManager,
|
||||
Providers = providerManager,
|
||||
Tasks = taskManager,
|
||||
Localization = localizationManager,
|
||||
FileSystem = fileSystem,
|
||||
Images = imageProcessor,
|
||||
Host = serverAppHost,
|
||||
Configuration = () => Plugin.Instance.Configuration,
|
||||
StateDirectory = Plugin.Instance.StateDirectory
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<AssemblyName>eMCPy</AssemblyName>
|
||||
<RootNamespace>eMCPy</RootNamespace>
|
||||
<Version>1.3.0</Version>
|
||||
<AssemblyVersion>1.3.0</AssemblyVersion>
|
||||
<FileVersion>1.3.0</FileVersion>
|
||||
<Version>1.4.0</Version>
|
||||
<AssemblyVersion>1.4.0</AssemblyVersion>
|
||||
<FileVersion>1.4.0</FileVersion>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
<NoWarn>CS1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using eMCPy;
|
||||
using eMCPy.Mcp;
|
||||
using MediaBrowser.Controller.Dto;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Entities.Movies;
|
||||
using MediaBrowser.Controller.Entities.TV;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Providers;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Providers;
|
||||
using MediaBrowser.Model.Querying;
|
||||
using MediaBrowser.Model.Tasks;
|
||||
|
||||
public static class AdvancedTests
|
||||
{
|
||||
public static void Run()
|
||||
{
|
||||
int assertions=0;
|
||||
void Check(bool ok,string msg){if(!ok)throw new Exception(msg);assertions++;}
|
||||
void Fails(Action f,string msg){bool failure=false;try{f();}catch(ArgumentException){failure=true;}catch(InvalidOperationException){failure=true;}Check(failure,msg);}
|
||||
var cfg=new PluginConfiguration();var state=Path.Combine(Path.GetTempPath(),"emcpy-tests-"+Guid.NewGuid());
|
||||
var folder=new CollectionFolder{InternalId=900,Id=Guid.NewGuid(),Name="Documentaries"};
|
||||
var series=new Series{InternalId=800,Id=Guid.NewGuid(),Name="Series"};
|
||||
var user=new User{InternalId=700,Id=Guid.NewGuid(),Name="Explicit user"};
|
||||
var movie=new Movie{InternalId=1,Id=Guid.NewGuid(),Name="Test documentary",ProductionYear=2020,OfficialRating="PG-13",RunTimeTicks=90*TimeSpan.TicksPerMinute,
|
||||
DateCreated=DateTimeOffset.Parse("2026-10-01T12:00:00Z"),DateLastSaved=DateTimeOffset.Parse("2026-10-02T12:00:00Z"),ProviderIds=new ProviderIdDictionary{{"Tmdb","100"}},ImageInfos=new[]{new ItemImageInfo{Type=ImageType.Primary,Width=1920,Height=1080}}};
|
||||
var movie2=new Movie{InternalId=2,Id=Guid.NewGuid(),Name="Other cut",OfficialRating="DE-12",ProviderIds=new ProviderIdDictionary{{"Tmdb","100"}},ImageInfos=new[]{new ItemImageInfo{Type=ImageType.Primary,Width=600,Height=900}}};
|
||||
var episode=new Episode{InternalId=3,Id=Guid.NewGuid(),Name="Double episode",ParentIndexNumber=1,IndexNumber=1,IndexNumberEnd=2};
|
||||
var rows=new List<BaseItem>{movie,movie2,episode};
|
||||
int detailCalls=0,batchCalls=0,updates=0,refreshes=0,userSaves=0;bool failSave=false;bool requireImages=false;
|
||||
var userdata=new UserItemData{Played=false};
|
||||
var services=new EmbyServices{Configuration=()=>cfg,StateDirectory=state};
|
||||
services.Library=Fake<ILibraryManager>.Make((method,args)=>{
|
||||
switch(method.Name){
|
||||
case "GetItemById":detailCalls++;return new BaseItem[]{folder,series}.Concat(rows).FirstOrDefault(x=>x.InternalId==(long)args[0]);
|
||||
case "GetInternalId":return new BaseItem[]{folder,series}.Concat(rows).FirstOrDefault(x=>x.Id==(Guid)args[0])?.InternalId??0;
|
||||
case "GetInternalItemIds":var q=(InternalItemsQuery)args[0];if(q.IsPlayed.HasValue)Check(q.User==user,"Played scope uses explicit user");return rows.Where(x=>q.SeriesIds?.Length>0?x is Episode:true).Select(x=>x.InternalId).ToArray();
|
||||
case "GetItemsResult":var query=(InternalItemsQuery)args[0];if(requireImages)Check(query.DtoOptions.EnableImages,"Image info must be requested");Check(query.ItemIds.Length<=200,"Bounded batch");return new QueryResult<BaseItem>{Items=rows.Where(x=>query.ItemIds.Contains(x.InternalId)).ToArray()};
|
||||
case "UpdateItem":updates++;if(failSave)throw new InvalidOperationException("synthetic save failure");return null;
|
||||
case "GetLibraryOptions":return new MediaBrowser.Model.Configuration.LibraryOptions();
|
||||
case "GetVirtualFolders":return new List<VirtualFolderInfo>{new VirtualFolderInfo{ItemId="900",Name="Documentaries"}};
|
||||
default:throw new Exception("Unexpected library call "+method.Name);
|
||||
}
|
||||
});
|
||||
services.Dto=Fake<IDtoService>.Make((method,args)=>{
|
||||
Check(method.Name=="GetBaseItemDtos","No per-item DTO calls");batchCalls++;
|
||||
return ((BaseItem[])args[0]).Select(x=>new BaseItemDto{Id=x.InternalId.ToString(),MediaSources=new[]{new MediaSourceInfo{Id="source",Path="https://username:secret@media.example/movie.mkv?token=secret",Container="mkv",MediaStreams=new List<MediaStream>{new MediaStream{Type=MediaStreamType.Audio,Language=x.InternalId==1?"ger":null},new MediaStream{Type=MediaStreamType.Video,Width=1920,Height=1080,ColorTransfer="smpte2084"}}}}}).ToArray();
|
||||
});
|
||||
services.Users=Fake<IUserManager>.Make((method,args)=>method.Name=="GetUserById"?user:method.Name=="GetUserList"?new[]{user}:throw new Exception(method.Name));
|
||||
services.UserData=Fake<IUserDataManager>.Make((method,args)=>{if(method.Name=="GetUserData")return userdata;if(method.Name=="SaveUserData"){userSaves++;return null;}throw new Exception(method.Name);});
|
||||
services.Localization=Fake<ILocalizationManager>.Make((method,args)=>new[]{new ParentalRating{Name="FSK-12",Value=7},new ParentalRating{Name="DE-12",Value=7}});
|
||||
services.Providers=Fake<IProviderManager>.Make((method,args)=>{
|
||||
if(method.Name=="GetAllEpisodes")return Task.FromResult(new[]{new RemoteSearchResult{Name="one",ParentIndexNumber=1,IndexNumber=1},new RemoteSearchResult{Name="two",ParentIndexNumber=1,IndexNumber=2},new RemoteSearchResult{Name="three",ParentIndexNumber=1,IndexNumber=3},new RemoteSearchResult{Name="unnumbered"},new RemoteSearchResult{Name="future",ParentIndexNumber=1,IndexNumber=4,PremiereDate=DateTimeOffset.UtcNow.AddDays(5)}});
|
||||
if(method.Name=="QueueRefresh"){refreshes++;var options=(MetadataRefreshOptions)args[1];Check(!options.ReplaceAllImages&&!options.ReplaceAllMetadata,"No destructive refresh defaults");return null;}
|
||||
if(method.Name=="GetRefreshQueue")return new List<Tuple<long,MetadataRefreshOptions>>();
|
||||
throw new Exception(method.Name);
|
||||
});
|
||||
services.FileSystem=Fake<IFileSystem>.Make((method,args)=>throw new Exception("Unexpected filesystem access: "+method.Name));
|
||||
services.Sessions=Fake<ISessionManager>.Make((method,args)=>method.Name=="get_Sessions"?new MediaBrowser.Controller.Session.SessionInfo[0]:throw new Exception(method.Name));
|
||||
services.Tasks=Fake<ITaskManager>.Make((method,args)=>Array.Empty<IScheduledTaskWorker>());
|
||||
var tools=new AdvancedTools(services);
|
||||
JsonElement Run(string name,object args)=>JsonSerializer.SerializeToElement(tools.Execute(name,JsonSerializer.SerializeToElement(args)));
|
||||
try {
|
||||
Check(!cfg.EnableWriteTools,"Writes disabled by default");
|
||||
var search=Run("emby_search_advanced",new{audioLanguage="de",maxRuntimeMinutes=100});
|
||||
Check(search.GetProperty("returned").GetInt32()==1,"Combined filters");
|
||||
Check(detailCalls==0&&batchCalls==1,"Search is bulk, no details");
|
||||
Fails(()=>Run("emby_search_advanced",new{played=false}),"Played needs explicit user");
|
||||
Run("emby_search_advanced",new{played=false,userId=user.Id.ToString()});
|
||||
var page=Run("emby_search_advanced",new{start=1,limit=1,maxRuntimeMinutes=20});
|
||||
Check(page.GetProperty("returned").GetInt32()==0&&page.GetProperty("hasMore").GetBoolean()&&page.GetProperty("nextStart").GetInt32()==2,"Empty filtered page advances candidates");
|
||||
Fails(()=>Run("emby_search_advanced",new{limit=201}),"Limit enforced");
|
||||
Fails(()=>Run("emby_search_advanced",new{unexpected=true}),"Unknown argument rejected");
|
||||
Fails(()=>Run("emby_search_advanced",new{types=new[]{"Bogus"}}),"Enum enforced");
|
||||
Fails(()=>Run("emby_search_advanced",new{start=-1}),"Negative offset rejected");
|
||||
Fails(()=>Run("emby_search_advanced",new{expectedRevision="old"}),"Revision enforced");
|
||||
Fails(()=>Run("emby_search_advanced",new{libraryId="not-an-id"}),"Invalid scope never scans root");
|
||||
var batch=Run("emby_batch_details",new{ids=new[]{"1","999"}});
|
||||
Check(batch.GetProperty("returned").GetInt32()==1&&batch.GetProperty("missingIds")[0].GetString()=="999","Batch missing IDs explicit");
|
||||
Check(!batch.GetRawText().Contains("secret")&&!batch.GetRawText().Contains("username"),"Media URLs redacted");
|
||||
Fails(()=>Run("emby_batch_details",new{ids=new[]{"1"},include=new[]{"userdata"}}),"Userdata requires user");
|
||||
Check(LibraryOperations.TrackState(new BaseItemDto(),MediaStreamType.Subtitle,"deu")=="unknown","No metadata not missing tracks");
|
||||
Check(LibraryOperations.TrackState(new BaseItemDto{MediaSources=Array.Empty<MediaSourceInfo>()},MediaStreamType.Audio,"deu")=="unknown","Empty sources unknown");
|
||||
var tracks=Run("emby_track_audit",new{});Check(tracks.GetProperty("items")[1].GetProperty("trackStatus").GetString()=="unknown","Unlabelled track unknown");
|
||||
Check(tracks.GetProperty("items")[0].GetProperty("burnedInSubtitleStatus").GetString()=="unknown","Never infer burned-in subtitles");
|
||||
requireImages=true;var images=Run("emby_image_audit",new{});requireImages=false;
|
||||
Check(images.GetProperty("items")[0].GetProperty("screenshotConfirmed").ValueKind==JsonValueKind.Null,"Landscape is not proof of screenshot");
|
||||
Check(images.GetProperty("items")[0].GetProperty("origin").GetString()=="unknown","Image provenance honest");
|
||||
Check(LibraryOperations.ImageReasons(movie2).Length==0,"Portrait not marked screenshot");
|
||||
Check(Run("emby_image_audit",new{onlyProblems=false}).GetProperty("returned").GetInt32()==3,"Can inspect all images");
|
||||
var audit=Run("emby_rating_audit",new{});Check(audit.GetProperty("page").GetProperty("items")[0].GetProperty("ratingStatus").GetString()=="foreign","Foreign rating reported");
|
||||
Check(LibraryOperations.RatingStatus("12")=="unknown","Bare age not assumed German");
|
||||
Check(LibraryOperations.RatingStatus("DE-12")=="german"&&LibraryOperations.RatingStatus("FSK-12")=="german","German values accepted");
|
||||
var dup=Run("emby_duplicate_candidates",new{limit=1,memberLimit=1});Check(dup.GetProperty("groups")[0].GetProperty("memberHasMore").GetBoolean(),"Duplicate group members bounded and paged");
|
||||
var savedDto=services.Dto;
|
||||
services.Dto=Fake<IDtoService>.Make((m,a)=>((BaseItem[])a[0]).Select(x=>new BaseItemDto{Id=x.InternalId.ToString(),MediaSources=new[]{new MediaSourceInfo{Id="cut-a"},new MediaSourceInfo{Id="cut-b"}}}).ToArray());
|
||||
var versions=Run("emby_duplicate_candidates",new{});Check(versions.GetProperty("groups").EnumerateArray().Any(g=>g.GetProperty("confidence").GetString()=="multiple_media_sources_not_file_equality"),"Grouped media versions detected even within a single item");
|
||||
services.Dto=savedDto;
|
||||
var missing=Run("emby_missing_episodes",new{seriesId="800"});
|
||||
Check(missing.GetProperty("presentCandidates").GetInt32()==2&&missing.GetProperty("total").GetInt32()==1&&missing.GetProperty("upcoming").GetInt32()==1&&missing.GetProperty("unmatchableReference").GetInt32()==1,"Multipart/future/unmatchable episode handling");
|
||||
var changes=Run("emby_library_changes",new{since="2026-10-02T00:00:00Z"});Check(changes.GetProperty("items").GetProperty("items")[0].GetProperty("changeKind").GetString()=="modified_or_saved","Changes by saved date");
|
||||
Fails(()=>Run("emby_library_changes",new{since="2026-10-02"}),"Timestamp needs timezone");
|
||||
var ratingArgs=new Dictionary<string,object>{{"id","1"},{"rating","FSK-12"},{"expectedOfficialRating","PG-13"},{"expectedCustomRating",null},{"sourceUrl","https://www.fsk.de/example"},{"evidence","Synthetic test: title/year/cut verified by fixture"}};
|
||||
ratingArgs["sourceUrl"]="https://www.fsk.de/asp/fskkarte.asp?pvid=123#freigabe";
|
||||
var preview=Run("emby_set_rating",ratingArgs);Check(preview.GetProperty("dryRun").GetBoolean()&&updates==0&&movie.OfficialRating=="PG-13","Default dry run changes nothing");
|
||||
ratingArgs["dryRun"]=false;ratingArgs["confirm"]=true;
|
||||
Fails(()=>Run("emby_set_rating",ratingArgs),"Writes disabled");cfg.EnableWriteTools=true;
|
||||
Fails(()=>Run("emby_set_rating",ratingArgs),"Writes require API key");cfg.ApiKey="synthetic-test-key";
|
||||
ratingArgs["confirm"]=false;Fails(()=>Run("emby_set_rating",ratingArgs),"Explicit confirm required");ratingArgs["confirm"]=true;
|
||||
ratingArgs["expectedOfficialRating"]="R";Fails(()=>Run("emby_set_rating",ratingArgs),"Stale rating rejected");ratingArgs["expectedOfficialRating"]="PG-13";
|
||||
ratingArgs["rating"]="12";Fails(()=>Run("emby_set_rating",ratingArgs),"Only server German rating accepted");ratingArgs["rating"]="FSK-12";
|
||||
ratingArgs["sourceUrl"]="https://example.org/?token=secret";Fails(()=>Run("emby_set_rating",ratingArgs),"No credential-bearing evidence URL");ratingArgs["sourceUrl"]="https://www.fsk.de/example";
|
||||
Run("emby_set_rating",ratingArgs);Check(updates==1&&movie.OfficialRating=="FSK-12","Only intended rating saved");
|
||||
Check(!File.ReadAllText(Path.Combine(state,"actions.jsonl")).Contains(cfg.ApiKey),"Audit has no API key");
|
||||
ratingArgs["expectedOfficialRating"]="FSK-12";ratingArgs["rating"]="DE-12";failSave=true;
|
||||
Fails(()=>Run("emby_set_rating",ratingArgs),"Save failure surfaced");Check(movie.OfficialRating=="FSK-12","In-memory value restored on save failure");failSave=false;
|
||||
movie.CustomRating="R";movie.LockedFields=new[]{MetadataFields.Genres};
|
||||
ratingArgs["expectedCustomRating"]="R";ratingArgs["dryRun"]=true;
|
||||
var customPreview=Run("emby_set_rating",ratingArgs);Check(customPreview.GetProperty("change").GetProperty("newCustomRating").GetString()=="R","Custom rating preserved by default");
|
||||
ratingArgs["clearCustomRating"]=true;ratingArgs["lockField"]=true;ratingArgs["dryRun"]=false;
|
||||
Run("emby_set_rating",ratingArgs);Check(movie.CustomRating==null&&movie.LockedFields.Contains(MetadataFields.Genres)&&movie.LockedFields.Contains(MetadataFields.OfficialRating),"Explicit custom clear and rating lock preserve other locks");
|
||||
Run("emby_set_played",new{id="1",userId=user.Id.ToString(),played=true,expectedPlayed=false});Check(userSaves==0,"Played preview readonly");
|
||||
Run("emby_set_played",new{id="1",userId=user.Id.ToString(),played=true,expectedPlayed=false,dryRun=false,confirm=true});Check(userSaves==1&&userdata.Played,"Explicit user status updated in mock");
|
||||
Fails(()=>Run("emby_set_played",new{id="800",userId=user.Id.ToString(),played=true,expectedPlayed=false}),"No recursive series played marking");
|
||||
Run("emby_refresh_item",new{id="1"});Check(refreshes==0,"Refresh preview");
|
||||
Run("emby_refresh_item",new{id="1",dryRun=false,confirm=true});Check(refreshes==1,"Refresh queued in mock");
|
||||
Run("emby_scan_library",new{libraryId="900",dryRun=false,confirm=true});Check(refreshes==2,"Target library queued in mock");
|
||||
int pauseCommands=0;
|
||||
var session=new SessionInfo(services.Sessions,Fake<MediaBrowser.Model.Logging.ILogger>.Make((m,a)=>null)){Id="session",Capabilities=new MediaBrowser.Model.Session.ClientCapabilities{SupportsMediaControl=true},
|
||||
SessionControllers=new[]{Fake<ISessionController>.Make((m,a)=>m.ReturnType==typeof(bool)?true:m.ReturnType==typeof(int)?0:Task.CompletedTask)}};
|
||||
session.RegisterPlaySession(new MediaBrowser.Model.Session.PlaybackProgressInfo{PlaySessionId="play",ItemId="1",Item=new BaseItemDto{Id="1",Name="Documentary"}});
|
||||
services.Sessions=Fake<ISessionManager>.Make((m,a)=>{if(m.Name=="get_Sessions")return new[]{session};if(m.Name=="SendPlaystateCommand"){pauseCommands++;Check(((MediaBrowser.Model.Session.PlaystateRequest)a[2]).Command==MediaBrowser.Model.Session.PlaystateCommand.Pause,"Only Pause command");return Task.CompletedTask;}throw new Exception(m.Name);});
|
||||
Run("emby_pause_session",new{sessionId="session",expectedItemId="1"});Check(pauseCommands==0,"Pause preview is readonly");
|
||||
Fails(()=>Run("emby_pause_session",new{sessionId="session",expectedItemId="2",dryRun=false,confirm=true}),"Stale playback item protected");
|
||||
Run("emby_pause_session",new{sessionId="session",expectedItemId="1",dryRun=false,confirm=true});Check(pauseCommands==1,"Pause mock command sent once");
|
||||
Check(Run("emby_playback_diagnostics",new{}).GetProperty("sessions")[0].GetProperty("reasonStatus").GetString()=="unknown","No invented transcode reason");
|
||||
cfg.EnableWriteTools=false;
|
||||
foreach(var pair in new[]{("emby_pause_session",new Dictionary<string,object>{{"sessionId","session"},{"expectedItemId","1"}}),("emby_refresh_item",new Dictionary<string,object>{{"id","1"}}),("emby_scan_library",new Dictionary<string,object>{{"libraryId","900"}})}){
|
||||
pair.Item2["dryRun"]=false;pair.Item2["confirm"]=true;Fails(()=>Run(pair.Item1,pair.Item2),"Write gate before action "+pair.Item1);
|
||||
}
|
||||
var snapshot=Run("emby_inventory_snapshot",new{libraryId="900",operation="capture"});Check(snapshot.GetProperty("count").GetInt32()==3,"Snapshot capture");
|
||||
Fails(()=>Run("emby_inventory_snapshot",new{libraryId="900",operation="capture"}),"No accidental baseline replacement");
|
||||
rows.Remove(movie2);var compare=Run("emby_inventory_snapshot",new{libraryId="900",operation="compare"});Check(compare.GetProperty("changes")[0].GetProperty("change").GetString()=="removed_from_emby_index","Deletion means index removal only");
|
||||
Check(Run("emby_inventory_snapshot",new{libraryId="900",operation="compare"}).GetProperty("total").GetInt32()==1,"Comparison does not mutate baseline");
|
||||
var png=Path.Combine(state,"image.png");File.WriteAllBytes(png,Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII="));
|
||||
movie.ImageInfos=new[]{new ItemImageInfo{Type=ImageType.Primary,Path=png,Width=1,Height=1}};
|
||||
Check(movie.ImageInfos[0].IsLocalFile,"Fixture local image");
|
||||
services.Images=Fake<MediaBrowser.Controller.Drawing.IImageProcessor>.Make((m,a)=>{
|
||||
if(m.Name=="GetImageSize")return(new MediaBrowser.Model.Drawing.ImageSize(1920,1080),(MediaBrowser.Model.Drawing.ImageOrientation?)null);
|
||||
if(m.Name=="ProcessImage") {var options=(MediaBrowser.Controller.Drawing.ImageProcessingOptions)a[0];Check(options.MaxWidth==768&&options.MaxHeight==768,"Bounded thumbnails");var data=File.ReadAllBytes(png);((Stream)a[1]).Write(data);return Task.CompletedTask;}
|
||||
throw new Exception(m.Name);
|
||||
});
|
||||
movie.ImageInfos[0].Width=0;movie.ImageInfos[0].Height=0;
|
||||
var probed=Run("emby_image_audit",new{onlyProblems=false});Check(probed.GetProperty("items")[0].GetProperty("images")[0].GetProperty("width").GetInt32()==1920,"Missing dimensions probed by SDK");
|
||||
var image=tools.Execute("emby_image_review",JsonSerializer.SerializeToElement(new{id="1"})) as McpContentResult;
|
||||
Check(JsonSerializer.SerializeToElement(image.Content[1]).GetProperty("mimeType").GetString()=="image/png","MCP image payload");
|
||||
var batchImages=tools.Execute("emby_image_review",JsonSerializer.SerializeToElement(new{ids=new[]{"1","3"}})) as McpContentResult;
|
||||
Check(batchImages.Content.Length==3,"Batch images include per-item missing result");
|
||||
Fails(()=>Run("emby_image_review",new{}),"Image ID required");
|
||||
Fails(()=>Run("emby_image_review",new{id="1",ids=new[]{"1"}}),"Ambiguous image IDs rejected");
|
||||
Run("emby_playback_diagnostics",new{});Run("emby_server_diagnostics",new{});Run("emby_users",new{});Run("emby_metadata_audit",new{});
|
||||
Console.WriteLine($"PASS advanced: {assertions} assertions; only test doubles used for mutations.");
|
||||
} finally {if(Directory.Exists(state))Directory.Delete(state,true);}
|
||||
}
|
||||
}
|
||||
@@ -93,14 +93,15 @@ foreach(var field in new[]{"seriesId","title","seasonNumber","episodeNumber","pr
|
||||
var registry = new McpToolRegistry(null,null);
|
||||
var schema=JsonSerializer.SerializeToElement(registry.HandleRequest("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}"));
|
||||
var tools=schema.GetProperty("result").GetProperty("tools");
|
||||
Check(tools.GetArrayLength()==18,"Existing 17 tools retained plus inventory");
|
||||
Check(tools.GetArrayLength()==18+AdvancedSchemas.Definitions().Count,"Existing tools retained plus advanced tools");
|
||||
var inventory=tools.EnumerateArray().Single(t=>t.GetProperty("name").GetString()=="emby_series_inventory");
|
||||
Check(inventory.GetProperty("inputSchema").GetProperty("required")[0].GetString()=="seriesId","Required schema parameter");
|
||||
foreach(var t in tools.EnumerateArray()) if(t.GetProperty("inputSchema").GetProperty("properties").TryGetProperty("type",out var type)) Check(type.GetProperty("description").GetString().Contains("Episode") && type.GetProperty("description").GetString().Contains("Season"),"Type schema complete");
|
||||
rows.Clear();
|
||||
var emptySeries=Run(new {seriesId="100"});
|
||||
Check(emptySeries.GetProperty("total").GetInt32()==0 && emptySeries.GetProperty("returned").GetInt32()==0 && !emptySeries.GetProperty("hasMore").GetBoolean(), "Empty series");
|
||||
Check(typeof(SeriesInventory).Assembly.GetName().Version.ToString(3)=="1.3.0", "Release version");
|
||||
Check(typeof(SeriesInventory).Assembly.GetName().Version.ToString(3)=="1.4.0", "Release version");
|
||||
AdvancedTests.Run();
|
||||
Console.WriteLine($"PASS: {passed} assertions; 35 episodes in 5 pages, no per-episode detail lookup.");
|
||||
|
||||
public class Fake<T> : DispatchProxy where T:class
|
||||
|
||||
Reference in new issue
Block a user