From 8cbb5788639607982d3609b9e756fabbce4a7f31 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:20:58 +0200 Subject: [PATCH 01/28] chore: .gitignore (bin/obj/dist) --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4e6a2f6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +bin/ +obj/ +dist/ +*.user +.vs/ From 06d79c9c06972496ed15bd080451f8e7ee935239 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:20:58 +0200 Subject: [PATCH 02/28] feat: eMPCby.csproj (net6.0, MediaBrowser.Server.Core 4.9.1.90) --- src/eMPCby/eMPCby.csproj | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/eMPCby/eMPCby.csproj diff --git a/src/eMPCby/eMPCby.csproj b/src/eMPCby/eMPCby.csproj new file mode 100644 index 0000000..59eedd0 --- /dev/null +++ b/src/eMPCby/eMPCby.csproj @@ -0,0 +1,14 @@ + + + net6.0 + eMPCby + eMPCby + 1.0.0 + 1.0.0 + false + CS1591 + + + + + From 8fbf2a78b772df19a2ce5704066d4285bff4e01d Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:20:59 +0200 Subject: [PATCH 03/28] feat: PluginConfiguration (Port, ListenAddress, ApiKey) --- src/eMPCby/PluginConfiguration.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 src/eMPCby/PluginConfiguration.cs diff --git a/src/eMPCby/PluginConfiguration.cs b/src/eMPCby/PluginConfiguration.cs new file mode 100644 index 0000000..302b454 --- /dev/null +++ b/src/eMPCby/PluginConfiguration.cs @@ -0,0 +1,12 @@ +using MediaBrowser.Model.Plugins; + +namespace eMPCby +{ + public class PluginConfiguration : BasePluginConfiguration + { + public bool EnableMcpServer { get; set; } = true; + public int McpPort { get; set; } = 8097; + public string ListenAddress { get; set; } = "0.0.0.0"; + public string ApiKey { get; set; } = string.Empty; // leer = offen (nur LAN) + } +} From 6523573057b0071b61fd01cf2d66dc98a5efc528 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:20:59 +0200 Subject: [PATCH 04/28] feat: Plugin (BasePlugin + IServerEntryPoint, startet MCP-Server in Run()) --- src/eMPCby/Plugin.cs | 63 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/eMPCby/Plugin.cs diff --git a/src/eMPCby/Plugin.cs b/src/eMPCby/Plugin.cs new file mode 100644 index 0000000..b1cde7c --- /dev/null +++ b/src/eMPCby/Plugin.cs @@ -0,0 +1,63 @@ +using System; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Plugins; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; +using eMPCby.Mcp; + +namespace eMPCby +{ + public class Plugin : BasePlugin, IServerEntryPoint + { + private readonly ILogger _logger; + private readonly IJsonSerializer _jsonSerializer; + private McpHttpServer _mcpServer; + + public static Plugin Instance { get; private set; } + + // DI-Brücke: werden von ServiceRegistrar (zweites IServerEntryPoint) gesetzt + public ISessionManager SessionManager { get; set; } + public ILibraryManager LibraryManager { get; set; } + public IUserManager UserManager { get; set; } + + public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer, + ILogManager logManager, IJsonSerializer jsonSerializer) + : base(applicationPaths, xmlSerializer) + { + Instance = this; + _logger = logManager.GetLogger(GetType().Name); + _jsonSerializer = jsonSerializer; + } + + public override string Name => "eMPCby"; + + public override string Description => + "MCP-Server (Model Context Protocol) für Emby – Emby-Funktionen als MCP-Tools für AI-Agenten."; + + // Feste Plugin-GUID – NIE ändern (Config-Zuordnung in Emby) + public override Guid Id => new Guid("095db6d6-5ecc-4ec3-85ea-7756dd6d958c"); + + public void Run() + { + var cfg = Configuration; + if (!cfg.EnableMcpServer) + { + _logger.Info("[eMPCby] MCP-Server ist deaktiviert."); + return; + } + + _mcpServer = new McpHttpServer(_logger, _jsonSerializer, cfg.McpPort, cfg.ListenAddress, cfg.ApiKey); + var status = _mcpServer.Start(); + _logger.Info("[eMPCby] MCP-Server Status: {0}", status); + } + + public void Dispose() + { + _mcpServer?.Stop(); + _mcpServer = null; + } + } +} From fbd037876cdd990ea87da4113d4126744a6b3dc8 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:21:00 +0200 Subject: [PATCH 05/28] =?UTF-8?q?feat:=20ServiceRegistrar=20(DI-Br=C3=BCck?= =?UTF-8?q?e=20f=C3=BCr=20Session/Library/UserManager)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/eMPCby/ServiceRegistrar.cs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/eMPCby/ServiceRegistrar.cs diff --git a/src/eMPCby/ServiceRegistrar.cs b/src/eMPCby/ServiceRegistrar.cs new file mode 100644 index 0000000..7baaf6a --- /dev/null +++ b/src/eMPCby/ServiceRegistrar.cs @@ -0,0 +1,27 @@ +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Session; + +namespace eMPCby +{ + /// + /// Zweites IServerEntryPoint: Emby injiziert die Dienste per Konstruktor und + /// legt sie auf Plugin.Instance ab, damit die McpToolRegistry darauf zugreifen kann. + /// + public class ServiceRegistrar : IServerEntryPoint + { + public ServiceRegistrar(ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager) + { + if (Plugin.Instance != null) + { + Plugin.Instance.SessionManager = sessionManager; + Plugin.Instance.LibraryManager = libraryManager; + Plugin.Instance.UserManager = userManager; + } + } + + public void Run() { } + + public void Dispose() { } + } +} From 8198bfb7e7acb09dc5b0e666038afb3d7b13b17c Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:22:46 +0200 Subject: [PATCH 06/28] feat: McpHttpServer (HttpListener auf /mcp, API-Key-Check, JSON-RPC-Dispatch) --- src/eMPCby/Mcp/McpHttpServer.cs | 154 ++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 src/eMPCby/Mcp/McpHttpServer.cs diff --git a/src/eMPCby/Mcp/McpHttpServer.cs b/src/eMPCby/Mcp/McpHttpServer.cs new file mode 100644 index 0000000..48babaf --- /dev/null +++ b/src/eMPCby/Mcp/McpHttpServer.cs @@ -0,0 +1,154 @@ +using System; +using System.IO; +using System.Net; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; + +namespace eMPCby.Mcp +{ + /// + /// Eigenständiger HTTP-Listener (Muster: WatchParty ExternalWebServer), der das + /// MCP-Protokoll (JSON-RPC 2.0) auf /mcp bedient. Läuft neben dem Emby-Port. + /// + public class McpHttpServer + { + private readonly ILogger _logger; + private readonly IJsonSerializer _json; + private readonly int _port; + private readonly string _listenAddress; + private readonly string _apiKey; + private readonly HttpListener _listener; + private readonly CancellationTokenSource _cts = new CancellationTokenSource(); + private readonly McpToolRegistry _tools; + + public McpHttpServer(ILogger logger, IJsonSerializer json, int port, string listenAddress, string apiKey) + { + _logger = logger; + _json = json; + _port = port; + _listenAddress = string.IsNullOrEmpty(listenAddress) ? "0.0.0.0" : listenAddress; + _apiKey = apiKey ?? string.Empty; + _listener = new HttpListener(); + // "*" bindet an alle Interfaces (Linux: ohne Root-Problem) + _listener.Prefixes.Add($"http://*:{_port}/"); + _tools = new McpToolRegistry(_logger, _json); + } + + public string Start() + { + try + { + _listener.Start(); + _logger.Info("[eMPCby] MCP-Server lauscht auf http://{0}:{1}/mcp", _listenAddress, _port); + Task.Run(() => ListenAsync(_cts.Token)); + return $"Lauscht auf {_listenAddress}:{_port}"; + } + catch (Exception ex) + { + _logger.ErrorException("[eMPCby] MCP-Server konnte nicht starten", ex); + return "Fehler: " + ex.Message; + } + } + + public void Stop() + { + if (!_listener.IsListening) return; + _cts.Cancel(); + _listener.Stop(); + _listener.Close(); + _logger.Info("[eMPCby] MCP-Server gestoppt."); + } + + private async Task ListenAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested && _listener.IsListening) + { + HttpListenerContext ctx; + try + { + ctx = await _listener.GetContextAsync().ConfigureAwait(false); + } + catch + { + break; // Listener gestoppt + } + _ = Task.Run(() => HandleAsync(ctx)); + } + } + + private async Task HandleAsync(HttpListenerContext ctx) + { + try + { + var req = ctx.Request; + var resp = ctx.Response; + resp.ContentType = "application/json"; + + if (req.HttpMethod != "POST" || + !req.Url.AbsolutePath.StartsWith("/mcp", StringComparison.OrdinalIgnoreCase)) + { + resp.StatusCode = 404; + await WriteJsonAsync(resp, new { error = "Nicht gefunden. Nutze POST /mcp" }); + return; + } + + // API-Key-Check (Header "X-Api-Key" oder "Authorization: Bearer ***") + if (!string.IsNullOrEmpty(_apiKey)) + { + var key = req.Headers["X-Api-Key"]; + if (string.IsNullOrEmpty(key)) + { + var auth = req.Headers["Authorization"]; + if (auth != null && auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + key = auth.Substring(7); + } + if (key != _apiKey) + { + resp.StatusCode = 401; + await WriteJsonAsync(resp, new { error = "Ungültiger API-Key" }); + return; + } + } + + using var reader = new StreamReader(req.InputStream, req.ContentEncoding); + var body = await reader.ReadToEndAsync(); + var result = _tools.HandleRequest(body); + + if (result == null) + { + // Notification (z. B. notifications/initialized) → 202, kein Body + resp.StatusCode = 202; + resp.Close(); + return; + } + + await WriteJsonAsync(resp, result); + } + catch (Exception ex) + { + _logger.ErrorException("[eMPCby] Fehler bei MCP-Request", ex); + try + { + ctx.Response.StatusCode = 500; + await WriteJsonAsync(ctx.Response, new { error = ex.Message }); + } + catch + { + // Response bereits geschlossen + } + } + } + + private async Task WriteJsonAsync(HttpListenerResponse resp, object obj) + { + var json = _json.SerializeToString(obj); + var bytes = Encoding.UTF8.GetBytes(json); + resp.ContentLength64 = bytes.Length; + await resp.OutputStream.WriteAsync(bytes, 0, bytes.Length); + resp.Close(); + } + } +} From be541dd83e7c44ddba8d4a7a03ba88a2e9f984a0 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:22:47 +0200 Subject: [PATCH 07/28] feat: McpToolRegistry (4 Tools: server_info, search, now_playing, get_item) --- src/eMPCby/Mcp/McpToolRegistry.cs | 307 ++++++++++++++++++++++++++++++ 1 file changed, 307 insertions(+) create mode 100644 src/eMPCby/Mcp/McpToolRegistry.cs diff --git a/src/eMPCby/Mcp/McpToolRegistry.cs b/src/eMPCby/Mcp/McpToolRegistry.cs new file mode 100644 index 0000000..9fa7f58 --- /dev/null +++ b/src/eMPCby/Mcp/McpToolRegistry.cs @@ -0,0 +1,307 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; + +namespace eMPCby.Mcp +{ + /// + /// MCP-Tool-Registry: parst JSON-RPC 2.0 Requests (initialize, tools/list, tools/call) + /// und implementiert die Emby-Tools direkt über die injizierten Emby-Dienste. + /// Request-Parsing läuft über System.Text.Json (robust gegenüber Emby's Newtonsoft-Serializer). + /// + public class McpToolRegistry + { + private readonly ILogger _logger; + private readonly IJsonSerializer _json; + + public McpToolRegistry(ILogger logger, IJsonSerializer json) + { + _logger = logger; + _json = json; + } + + private ISessionManager Sessions => Plugin.Instance?.SessionManager; + private ILibraryManager Library => Plugin.Instance?.LibraryManager; + private IUserManager Users => Plugin.Instance?.UserManager; + + // ---------- JSON-RPC 2.0 Handler ---------- + + public object HandleRequest(string body) + { + JsonElement root; + try + { + using (var doc = JsonDocument.Parse(body)) + { + root = doc.RootElement.Clone(); + } + } + catch (Exception ex) + { + return RpcError(default, -32700, "Parse error: " + ex.Message); + } + + if (root.ValueKind != JsonValueKind.Object) + return RpcError(default, -32700, "Parse error: Request ist kein JSON-Objekt"); + + var id = root.TryGetProperty("id", out var idEl) ? idEl.Clone() : default; + var method = root.TryGetProperty("method", out var mEl) && mEl.ValueKind == JsonValueKind.String + ? mEl.GetString() : null; + var hasParams = root.TryGetProperty("params", out var pEl) && pEl.ValueKind == JsonValueKind.Object; + + switch (method) + { + case "initialize": + return RpcResult(id, new + { + protocolVersion = "2024-11-05", + serverInfo = new { name = "eMPCby", version = "1.0.0" }, + capabilities = new { tools = new { listChanged = false } } + }); + + case "notifications/initialized": + return null; // Notification → keine Antwort + + case "tools/list": + return RpcResult(id, new { tools = GetToolDefinitions() }); + + case "tools/call": + return HandleToolCall(id, hasParams ? pEl : default); + + default: + return RpcError(id, -32601, "Methode nicht gefunden: " + method); + } + } + + private object HandleToolCall(JsonElement id, JsonElement p) + { + var name = p.ValueKind == JsonValueKind.Object && p.TryGetProperty("name", out var nEl) + && nEl.ValueKind == JsonValueKind.String ? nEl.GetString() : null; + var args = p.ValueKind == JsonValueKind.Object && p.TryGetProperty("arguments", out var aEl) + && aEl.ValueKind == JsonValueKind.Object ? aEl : default; + var hasArgs = args.ValueKind == JsonValueKind.Object; + + try + { + object result; + switch (name) + { + case "emby_server_info": + result = ToolServerInfo(); + break; + case "emby_search": + result = ToolSearch(hasArgs ? args : default); + break; + case "emby_now_playing": + result = ToolNowPlaying(); + break; + case "emby_get_item": + result = ToolGetItem(hasArgs ? args : default); + break; + default: + return RpcError(id, -32602, "Unbekanntes Tool: " + name); + } + + return RpcResult(id, new + { + content = new[] { new { type = "text", text = _json.SerializeToString(result) } }, + isError = false + }); + } + catch (Exception ex) + { + _logger.ErrorException("[eMPCby] Tool-Fehler: " + name, ex); + return RpcResult(id, new + { + content = new[] { new { type = "text", text = "Fehler: " + ex.Message } }, + isError = true + }); + } + } + + private static string ArgString(JsonElement args, string key) + { + if (args.ValueKind == JsonValueKind.Object && args.TryGetProperty(key, out var v) + && v.ValueKind == JsonValueKind.String) + return v.GetString(); + return null; + } + + // ---------- Tool-Definitionen ---------- + + private List GetToolDefinitions() + { + return new List + { + new + { + name = "emby_server_info", + description = "Liefert Basis-Infos zum Emby-Server (Name, Plugin-Status, Benutzeranzahl).", + inputSchema = new { type = "object", properties = new Dictionary() } + }, + new + { + name = "emby_search", + description = "Durchsucht die Emby-Mediathek nach Filmen, Serien oder Musik.", + inputSchema = new + { + type = "object", + properties = new + { + query = new { type = "string", description = "Suchbegriff (Titel, actor, Genre …)" }, + type = new { type = "string", description = "Optional: Movie, Series, Music – leer = alle Typen" } + }, + required = new[] { "query" } + } + }, + new + { + name = "emby_now_playing", + description = "Listet alle aktuell abspielenden Sessions (wer sieht gerade was).", + inputSchema = new { type = "object", properties = new Dictionary() } + }, + new + { + name = "emby_get_item", + description = "Holt Details zu einem einzelnen Item per Item-ID (GUID).", + inputSchema = new + { + type = "object", + properties = new + { + id = new { type = "string", description = "Item-ID als GUID" } + }, + required = new[] { "id" } + } + } + }; + } + + // ---------- Tool-Implementierungen ---------- + + private object ToolServerInfo() + { + var cfg = Plugin.Instance?.Configuration; + return new + { + server = "Emby", + plugin = "eMPCby", + mcpEnabled = cfg?.EnableMcpServer ?? false, + mcpPort = cfg?.McpPort ?? 0, + userCount = Users?.GetUserCount(new MediaBrowser.Model.Querying.UserQuery()) ?? 0 + }; + } + + private object ToolSearch(JsonElement args) + { + var query = ArgString(args, "query"); + if (string.IsNullOrWhiteSpace(query)) + return new { error = "Parameter 'query' fehlt" }; + + if (Library == null) + return new { error = "LibraryManager noch nicht verfügbar (Server startet?)" }; + + var type = ArgString(args, "type"); + + var results = new List(); + var queryResult = Library.GetItemsResult(new MediaBrowser.Controller.Entities.InternalItemsQuery + { + SearchTerm = query, + Limit = 20 + }); + foreach (var item in queryResult.Items) + { + if (!string.IsNullOrEmpty(type) && + !string.Equals(item.MediaType, type, StringComparison.OrdinalIgnoreCase)) + continue; + + results.Add(new + { + id = item.Id.ToString(), + name = item.Name, + type = item.MediaType, + path = item.Path + }); + } + + return new { query, type, count = results.Count, results }; + } + + private object ToolNowPlaying() + { + if (Sessions == null) + return new { error = "SessionManager noch nicht verfügbar (Server startet?)" }; + + var list = Sessions.Sessions + .Where(s => s.NowPlayingItem != null) + .Select(s => new + { + session = s.Id, + user = s.UserName, + client = s.Client, + device = s.DeviceName, + item = s.NowPlayingItem.Name, + itemType = s.NowPlayingItem.Type, + itemId = s.NowPlayingItem.Id, + positionSeconds = s.PlayState != null ? (long)(s.PlayState.PositionTicks / TimeSpan.TicksPerSecond) : 0, + paused = s.PlayState?.IsPaused ?? false + }) + .ToList(); + + return new { count = list.Count, nowPlaying = list }; + } + + private object ToolGetItem(JsonElement args) + { + var id = ArgString(args, "id"); + if (string.IsNullOrWhiteSpace(id)) + return new { error = "Parameter 'id' fehlt" }; + if (Library == null) + return new { error = "LibraryManager noch nicht verfügbar (Server startet?)" }; + + if (!Guid.TryParse(id, out var guid)) + return new { error = "Ungültige GUID: " + id }; + + var item = Library.GetItemById(guid); + if (item == null) + return new { found = false, id }; + + return new + { + found = true, + id = item.Id.ToString(), + name = item.Name, + type = item.MediaType, + path = item.Path + }; + } + + // ---------- JSON-RPC-Helfer ---------- + + /// Wandelt einen JsonElement in einen plain C#-Wert um (für saubere Newtonsoft-Serialisierung). + private static object Plain(JsonElement el) + { + switch (el.ValueKind) + { + case JsonValueKind.String: return el.GetString(); + case JsonValueKind.Number: + return el.TryGetInt64(out var l) ? l : el.GetDouble(); + case JsonValueKind.True: return true; + case JsonValueKind.False: return false; + case JsonValueKind.Null: + case JsonValueKind.Undefined: return null; + default: return el.GetRawText(); + } + } + + private object RpcResult(JsonElement id, object result) => new { jsonrpc = "2.0", id = Plain(id), result }; + + private object RpcError(JsonElement id, int code, string message) => + new { jsonrpc = "2.0", id = Plain(id), error = new { code, message } }; + } +} From 493b9f4d1905bfa1d70da10b9009551535b587cc Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:23:18 +0200 Subject: [PATCH 08/28] docs: README auf Ist-Stand (implementiert + live verifiziert) --- README.md | 77 +------------------------------------------------------ 1 file changed, 1 insertion(+), 76 deletions(-) diff --git a/README.md b/README.md index 9c2f6f6..f8549b5 100644 --- a/README.md +++ b/README.md @@ -1,78 +1,3 @@ # eMPCby – emby MCP -**eMPCby** ist ein Plugin für **Emby Server**, das einen **MCP-Server** (Model Context Protocol) direkt in den Emby-Server einbettet. AI-Agenten (Claude, Hermes, …) können so über MCP auf die Emby-Bibliothek, das Playback und die Server-Administration zugreifen – ohne separate API-Brücke. - -## Status - -🚧 Projekt-Setup – Architektur & Recherche abgeschlossen, Implementierung folgt. - -## Konzept - -``` -AI-Agent (MCP-Client) - │ MCP (JSON-RPC 2.0, HTTP) - ▼ -eMPCby-Plugin (läuft IN Emby Server) - │ direkte DI-Abhängigkeiten (kein HTTP-Roundtrip) - ▼ -Emby-Server (Bibliothek, Playback, User, Tasks, …) -``` - -### Geplante MCP-Tools (Auswahl) - -| Tool | Beschreibung | -|---|---| -| `emby_search` | Medien in der Bibliothek suchen (Titel, Jahr, Typ) | -| `emby_get_item` | Details zu einem Item (ID) | -| `emby_playback` | Wiedergabe-Infos / Stream-URLs | -| `emby_now_playing` | Aktuelle Wiedergabe-Sessionen | -| `emby_library_stats` | Bibliotheks-Übersicht & Statistiken | -| `emby_server_info` | Server-Version, Status, Health | -| `emby_scheduled_tasks` | Geplante Tasks auflisten/ausführen | - -## Emby-Plugin-Grundlagen (Recherche) - -### Wie Emby-Plugins funktionieren - -- **C#-Assembly (.NET Standard 2.0)**, referenziert auf das NuGet-Paket `MediaBrowser.Server.Core` (aktuell stabil: **4.9.1.90**). -- **`Plugin`-Klasse** : `BasePlugin` – Name, Beschreibung, fester GUID-`Id` (nie änderbar), Version. -- **`PluginConfiguration`** : `BasePluginConfiguration` – wird automatisch als XML unter `plugins/configurations//` gespeichert. -- **`IServerEntryPoint`** – Initialisierung beim Serverstart; die Klasse lebt für die Server-Lebensdauer (ideal für den MCP-Listener). Emby entdeckt alle Typen mit diesen Interfaces **automatisch** (Automatic Type Discovery), kein manuelles Wiring. -- **`IRestfulService`** – eigene API-Endpunkte unter `/emby/...`. -- **`IScheduledTask`** – Dashboard-Task, **`IPluginConfigurationPage`** – HTML-Config-Seite im Dashboard. -- **Dependency Injection**: Der Konstruktor des EntryPoints kann beliebige Emby-Dienste anfordern (`IFileSystem`, `IHttpClient`, `INetworkManager`, `IServerManager`, `IMediaLibraryManager`, `IUserManager`, …). - -### Build & Deploy - -1. .NET Standard 2.0 Class Library, `PackageReference MediaBrowser.Server.Core`. -2. Build → DLL in das Emby-Plugin-Verzeichnis kopieren: - - Windows: `%AppData%\Emby-Server\programdata\plugins\` - - Docker/Unraid: `/emby/plugins/` (Host-Mount: `/mnt/user/appdata/Emby/plugins/`) -3. Emby-Server neu starten → Plugin erscheint im Dashboard unter *Plugins*. - -### MCP-Integration (Architektur-Entscheidung) - -Das Plugin startet im `IServerEntryPoint` einen eigenen **HTTP-Listener** (konfigurierbarer Port, z. B. 8097) und spricht dort das **MCP-Protokoll** (JSON-RPC 2.0). Tools werden gegen die injizierten Emby-Dienste implementiert – direkter Zugriff, kein API-Token-Roundtrip über HTTP. - -**Authentifizierung:** Der MCP-Port ist nur für das lokale Netz gedacht; optionaler statischer API-Key im Plugin-Config (Dashboard-Config-Seite). - -## Ziel-System - -- Emby Server **4.9.5.0** (Docker `emby/embyserver:latest` auf Unraid) -- Plugin-Ordner: `/mnt/user/appdata/Emby/plugins/` -- Bestehende Plugins dort: Fanart, IMVDb, MovieDb, OMDb, Tvdb, XmlTV, Webhooks, … - -## Roadmap - -- [x] Recherche: Emby-Plugin-System, SDK, NuGet -- [x] Repository anlegen -- [ ] Projektgerüst (csproj, Plugin.cs, PluginConfiguration.cs, PluginEntryPoint.cs) -- [ ] MCP-Listener (JSON-RPC 2.0, HTTP) -- [ ] Erste Tools: `emby_server_info`, `emby_search`, `emby_now_playing` -- [ ] Dashboard-Config-Seite (Port, API-Key) -- [ ] Build-Pipeline (GitHub Actions / lokal) + Deploy-Skript für Unraid -- [ ] Test mit MCP-Client (Hermes) - -## Lizenz - -MIT +**eMPCby** ist ein Plugin für **Emby Server**, das einen **MCP-Server** (Model Context Protocol) direkt in den Emby-Server einbettet. AI-Agenten (Claude, Hermes, …) können so über...[truncated] \ No newline at end of file From 9c4b5255e871543722cc03a2e8dbd548cfcb34f1 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:46:18 +0200 Subject: [PATCH 09/28] refactor: eMCPy.csproj (Umbenennung) --- src/eMCPy/eMCPy.csproj | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 src/eMCPy/eMCPy.csproj diff --git a/src/eMCPy/eMCPy.csproj b/src/eMCPy/eMCPy.csproj new file mode 100644 index 0000000..96eee74 --- /dev/null +++ b/src/eMCPy/eMCPy.csproj @@ -0,0 +1,6 @@ + + + net6.0 + eMCPy + eMCPy + Date: Mon, 7 Sep 2026 17:46:19 +0200 Subject: [PATCH 10/28] refactor: PluginConfiguration (Namespace eMCPy) --- src/eMCPy/PluginConfiguration.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 src/eMCPy/PluginConfiguration.cs diff --git a/src/eMCPy/PluginConfiguration.cs b/src/eMCPy/PluginConfiguration.cs new file mode 100644 index 0000000..e119a68 --- /dev/null +++ b/src/eMCPy/PluginConfiguration.cs @@ -0,0 +1,12 @@ +using MediaBrowser.Model.Plugins; + +namespace eMCPy +{ + public class PluginConfiguration : BasePluginConfiguration + { + public bool EnableMcpServer { get; set; } = true; + public int McpPort { get; set; } = 8097; + public string ListenAddress { get; set; } = "0.0.0.0"; + public string ApiKey { get; set; } = string.Empty; // leer = offen (nur LAN) + } +} From e289897e5d5c8f4d25817dd5046425145183a04c Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:46:19 +0200 Subject: [PATCH 11/28] refactor: Plugin (Namespace eMCPy, Name eMCPy) --- src/eMCPy/Plugin.cs | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 src/eMCPy/Plugin.cs diff --git a/src/eMCPy/Plugin.cs b/src/eMCPy/Plugin.cs new file mode 100644 index 0000000..0921763 --- /dev/null +++ b/src/eMCPy/Plugin.cs @@ -0,0 +1,6 @@ +using System; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Plugins; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Se...[truncated] \ No newline at end of file From 327c52f6833e456eda680519ce0f08055418d650 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:46:19 +0200 Subject: [PATCH 12/28] refactor: ServiceRegistrar (Namespace eMCPy) --- src/eMCPy/ServiceRegistrar.cs | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 src/eMCPy/ServiceRegistrar.cs diff --git a/src/eMCPy/ServiceRegistrar.cs b/src/eMCPy/ServiceRegistrar.cs new file mode 100644 index 0000000..bdcd903 --- /dev/null +++ b/src/eMCPy/ServiceRegistrar.cs @@ -0,0 +1,8 @@ +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Session; + +namespace eMCPy +{ + /// + /// Zweites IServerEntryPoint: Emby injiz...[truncated] \ No newline at end of file From 01b6c11e53e30623cf53bf776ff95393d764cfea Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:46:31 +0200 Subject: [PATCH 13/28] refactor: McpHttpServer (Namespace eMCPy) --- src/eMCPy/Mcp/McpHttpServer.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 src/eMCPy/Mcp/McpHttpServer.cs diff --git a/src/eMCPy/Mcp/McpHttpServer.cs b/src/eMCPy/Mcp/McpHttpServer.cs new file mode 100644 index 0000000..769c939 --- /dev/null +++ b/src/eMCPy/Mcp/McpHttpServer.cs @@ -0,0 +1,10 @@ +using System; +using System.IO; +using System.Net; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; + +nam...[truncated] \ No newline at end of file From 8e967a8958b7898401a3cc0c99da824cf2489362 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:46:32 +0200 Subject: [PATCH 14/28] refactor: McpToolRegistry (Namespace eMCPy, Name eMCPy) --- src/eMCPy/Mcp/McpToolRegistry.cs | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 src/eMCPy/Mcp/McpToolRegistry.cs diff --git a/src/eMCPy/Mcp/McpToolRegistry.cs b/src/eMCPy/Mcp/McpToolRegistry.cs new file mode 100644 index 0000000..fdbcd3c --- /dev/null +++ b/src/eMCPy/Mcp/McpToolRegistry.cs @@ -0,0 +1,7 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Loggin...[truncated] \ No newline at end of file From 6b484bd2d23e314dacf8ce48894479a546af63d8 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:46:57 +0200 Subject: [PATCH 15/28] refactor: alte eMPCby-Pfade entfernen --- src/eMPCby/eMPCby.csproj | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 src/eMPCby/eMPCby.csproj diff --git a/src/eMPCby/eMPCby.csproj b/src/eMPCby/eMPCby.csproj deleted file mode 100644 index 59eedd0..0000000 --- a/src/eMPCby/eMPCby.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - net6.0 - eMPCby - eMPCby - 1.0.0 - 1.0.0 - false - CS1591 - - - - - From 8a5921faf4ca9dbd507fd89cd329d11d09520c07 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:46:57 +0200 Subject: [PATCH 16/28] refactor: alte eMPCby-Pfade entfernen --- src/eMPCby/Plugin.cs | 63 -------------------------------------------- 1 file changed, 63 deletions(-) delete mode 100644 src/eMPCby/Plugin.cs diff --git a/src/eMPCby/Plugin.cs b/src/eMPCby/Plugin.cs deleted file mode 100644 index b1cde7c..0000000 --- a/src/eMPCby/Plugin.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Plugins; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Serialization; -using eMPCby.Mcp; - -namespace eMPCby -{ - public class Plugin : BasePlugin, IServerEntryPoint - { - private readonly ILogger _logger; - private readonly IJsonSerializer _jsonSerializer; - private McpHttpServer _mcpServer; - - public static Plugin Instance { get; private set; } - - // DI-Brücke: werden von ServiceRegistrar (zweites IServerEntryPoint) gesetzt - public ISessionManager SessionManager { get; set; } - public ILibraryManager LibraryManager { get; set; } - public IUserManager UserManager { get; set; } - - public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer, - ILogManager logManager, IJsonSerializer jsonSerializer) - : base(applicationPaths, xmlSerializer) - { - Instance = this; - _logger = logManager.GetLogger(GetType().Name); - _jsonSerializer = jsonSerializer; - } - - public override string Name => "eMPCby"; - - public override string Description => - "MCP-Server (Model Context Protocol) für Emby – Emby-Funktionen als MCP-Tools für AI-Agenten."; - - // Feste Plugin-GUID – NIE ändern (Config-Zuordnung in Emby) - public override Guid Id => new Guid("095db6d6-5ecc-4ec3-85ea-7756dd6d958c"); - - public void Run() - { - var cfg = Configuration; - if (!cfg.EnableMcpServer) - { - _logger.Info("[eMPCby] MCP-Server ist deaktiviert."); - return; - } - - _mcpServer = new McpHttpServer(_logger, _jsonSerializer, cfg.McpPort, cfg.ListenAddress, cfg.ApiKey); - var status = _mcpServer.Start(); - _logger.Info("[eMPCby] MCP-Server Status: {0}", status); - } - - public void Dispose() - { - _mcpServer?.Stop(); - _mcpServer = null; - } - } -} From 509b1651d6ef7607a65847b8a696bc49ad5dbb37 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:46:58 +0200 Subject: [PATCH 17/28] refactor: alte eMPCby-Pfade entfernen --- src/eMPCby/Mcp/McpHttpServer.cs | 154 -------------------------------- 1 file changed, 154 deletions(-) delete mode 100644 src/eMPCby/Mcp/McpHttpServer.cs diff --git a/src/eMPCby/Mcp/McpHttpServer.cs b/src/eMPCby/Mcp/McpHttpServer.cs deleted file mode 100644 index 48babaf..0000000 --- a/src/eMPCby/Mcp/McpHttpServer.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.IO; -using System.Net; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Serialization; - -namespace eMPCby.Mcp -{ - /// - /// Eigenständiger HTTP-Listener (Muster: WatchParty ExternalWebServer), der das - /// MCP-Protokoll (JSON-RPC 2.0) auf /mcp bedient. Läuft neben dem Emby-Port. - /// - public class McpHttpServer - { - private readonly ILogger _logger; - private readonly IJsonSerializer _json; - private readonly int _port; - private readonly string _listenAddress; - private readonly string _apiKey; - private readonly HttpListener _listener; - private readonly CancellationTokenSource _cts = new CancellationTokenSource(); - private readonly McpToolRegistry _tools; - - public McpHttpServer(ILogger logger, IJsonSerializer json, int port, string listenAddress, string apiKey) - { - _logger = logger; - _json = json; - _port = port; - _listenAddress = string.IsNullOrEmpty(listenAddress) ? "0.0.0.0" : listenAddress; - _apiKey = apiKey ?? string.Empty; - _listener = new HttpListener(); - // "*" bindet an alle Interfaces (Linux: ohne Root-Problem) - _listener.Prefixes.Add($"http://*:{_port}/"); - _tools = new McpToolRegistry(_logger, _json); - } - - public string Start() - { - try - { - _listener.Start(); - _logger.Info("[eMPCby] MCP-Server lauscht auf http://{0}:{1}/mcp", _listenAddress, _port); - Task.Run(() => ListenAsync(_cts.Token)); - return $"Lauscht auf {_listenAddress}:{_port}"; - } - catch (Exception ex) - { - _logger.ErrorException("[eMPCby] MCP-Server konnte nicht starten", ex); - return "Fehler: " + ex.Message; - } - } - - public void Stop() - { - if (!_listener.IsListening) return; - _cts.Cancel(); - _listener.Stop(); - _listener.Close(); - _logger.Info("[eMPCby] MCP-Server gestoppt."); - } - - private async Task ListenAsync(CancellationToken ct) - { - while (!ct.IsCancellationRequested && _listener.IsListening) - { - HttpListenerContext ctx; - try - { - ctx = await _listener.GetContextAsync().ConfigureAwait(false); - } - catch - { - break; // Listener gestoppt - } - _ = Task.Run(() => HandleAsync(ctx)); - } - } - - private async Task HandleAsync(HttpListenerContext ctx) - { - try - { - var req = ctx.Request; - var resp = ctx.Response; - resp.ContentType = "application/json"; - - if (req.HttpMethod != "POST" || - !req.Url.AbsolutePath.StartsWith("/mcp", StringComparison.OrdinalIgnoreCase)) - { - resp.StatusCode = 404; - await WriteJsonAsync(resp, new { error = "Nicht gefunden. Nutze POST /mcp" }); - return; - } - - // API-Key-Check (Header "X-Api-Key" oder "Authorization: Bearer ***") - if (!string.IsNullOrEmpty(_apiKey)) - { - var key = req.Headers["X-Api-Key"]; - if (string.IsNullOrEmpty(key)) - { - var auth = req.Headers["Authorization"]; - if (auth != null && auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) - key = auth.Substring(7); - } - if (key != _apiKey) - { - resp.StatusCode = 401; - await WriteJsonAsync(resp, new { error = "Ungültiger API-Key" }); - return; - } - } - - using var reader = new StreamReader(req.InputStream, req.ContentEncoding); - var body = await reader.ReadToEndAsync(); - var result = _tools.HandleRequest(body); - - if (result == null) - { - // Notification (z. B. notifications/initialized) → 202, kein Body - resp.StatusCode = 202; - resp.Close(); - return; - } - - await WriteJsonAsync(resp, result); - } - catch (Exception ex) - { - _logger.ErrorException("[eMPCby] Fehler bei MCP-Request", ex); - try - { - ctx.Response.StatusCode = 500; - await WriteJsonAsync(ctx.Response, new { error = ex.Message }); - } - catch - { - // Response bereits geschlossen - } - } - } - - private async Task WriteJsonAsync(HttpListenerResponse resp, object obj) - { - var json = _json.SerializeToString(obj); - var bytes = Encoding.UTF8.GetBytes(json); - resp.ContentLength64 = bytes.Length; - await resp.OutputStream.WriteAsync(bytes, 0, bytes.Length); - resp.Close(); - } - } -} From 072d1723c910cfb813d3609ecb4dffe411ea8f67 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:46:58 +0200 Subject: [PATCH 18/28] refactor: alte eMPCby-Pfade entfernen --- src/eMPCby/Mcp/McpToolRegistry.cs | 307 ------------------------------ 1 file changed, 307 deletions(-) delete mode 100644 src/eMPCby/Mcp/McpToolRegistry.cs diff --git a/src/eMPCby/Mcp/McpToolRegistry.cs b/src/eMPCby/Mcp/McpToolRegistry.cs deleted file mode 100644 index 9fa7f58..0000000 --- a/src/eMPCby/Mcp/McpToolRegistry.cs +++ /dev/null @@ -1,307 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.Json; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Serialization; - -namespace eMPCby.Mcp -{ - /// - /// MCP-Tool-Registry: parst JSON-RPC 2.0 Requests (initialize, tools/list, tools/call) - /// und implementiert die Emby-Tools direkt über die injizierten Emby-Dienste. - /// Request-Parsing läuft über System.Text.Json (robust gegenüber Emby's Newtonsoft-Serializer). - /// - public class McpToolRegistry - { - private readonly ILogger _logger; - private readonly IJsonSerializer _json; - - public McpToolRegistry(ILogger logger, IJsonSerializer json) - { - _logger = logger; - _json = json; - } - - private ISessionManager Sessions => Plugin.Instance?.SessionManager; - private ILibraryManager Library => Plugin.Instance?.LibraryManager; - private IUserManager Users => Plugin.Instance?.UserManager; - - // ---------- JSON-RPC 2.0 Handler ---------- - - public object HandleRequest(string body) - { - JsonElement root; - try - { - using (var doc = JsonDocument.Parse(body)) - { - root = doc.RootElement.Clone(); - } - } - catch (Exception ex) - { - return RpcError(default, -32700, "Parse error: " + ex.Message); - } - - if (root.ValueKind != JsonValueKind.Object) - return RpcError(default, -32700, "Parse error: Request ist kein JSON-Objekt"); - - var id = root.TryGetProperty("id", out var idEl) ? idEl.Clone() : default; - var method = root.TryGetProperty("method", out var mEl) && mEl.ValueKind == JsonValueKind.String - ? mEl.GetString() : null; - var hasParams = root.TryGetProperty("params", out var pEl) && pEl.ValueKind == JsonValueKind.Object; - - switch (method) - { - case "initialize": - return RpcResult(id, new - { - protocolVersion = "2024-11-05", - serverInfo = new { name = "eMPCby", version = "1.0.0" }, - capabilities = new { tools = new { listChanged = false } } - }); - - case "notifications/initialized": - return null; // Notification → keine Antwort - - case "tools/list": - return RpcResult(id, new { tools = GetToolDefinitions() }); - - case "tools/call": - return HandleToolCall(id, hasParams ? pEl : default); - - default: - return RpcError(id, -32601, "Methode nicht gefunden: " + method); - } - } - - private object HandleToolCall(JsonElement id, JsonElement p) - { - var name = p.ValueKind == JsonValueKind.Object && p.TryGetProperty("name", out var nEl) - && nEl.ValueKind == JsonValueKind.String ? nEl.GetString() : null; - var args = p.ValueKind == JsonValueKind.Object && p.TryGetProperty("arguments", out var aEl) - && aEl.ValueKind == JsonValueKind.Object ? aEl : default; - var hasArgs = args.ValueKind == JsonValueKind.Object; - - try - { - object result; - switch (name) - { - case "emby_server_info": - result = ToolServerInfo(); - break; - case "emby_search": - result = ToolSearch(hasArgs ? args : default); - break; - case "emby_now_playing": - result = ToolNowPlaying(); - break; - case "emby_get_item": - result = ToolGetItem(hasArgs ? args : default); - break; - default: - return RpcError(id, -32602, "Unbekanntes Tool: " + name); - } - - return RpcResult(id, new - { - content = new[] { new { type = "text", text = _json.SerializeToString(result) } }, - isError = false - }); - } - catch (Exception ex) - { - _logger.ErrorException("[eMPCby] Tool-Fehler: " + name, ex); - return RpcResult(id, new - { - content = new[] { new { type = "text", text = "Fehler: " + ex.Message } }, - isError = true - }); - } - } - - private static string ArgString(JsonElement args, string key) - { - if (args.ValueKind == JsonValueKind.Object && args.TryGetProperty(key, out var v) - && v.ValueKind == JsonValueKind.String) - return v.GetString(); - return null; - } - - // ---------- Tool-Definitionen ---------- - - private List GetToolDefinitions() - { - return new List - { - new - { - name = "emby_server_info", - description = "Liefert Basis-Infos zum Emby-Server (Name, Plugin-Status, Benutzeranzahl).", - inputSchema = new { type = "object", properties = new Dictionary() } - }, - new - { - name = "emby_search", - description = "Durchsucht die Emby-Mediathek nach Filmen, Serien oder Musik.", - inputSchema = new - { - type = "object", - properties = new - { - query = new { type = "string", description = "Suchbegriff (Titel, actor, Genre …)" }, - type = new { type = "string", description = "Optional: Movie, Series, Music – leer = alle Typen" } - }, - required = new[] { "query" } - } - }, - new - { - name = "emby_now_playing", - description = "Listet alle aktuell abspielenden Sessions (wer sieht gerade was).", - inputSchema = new { type = "object", properties = new Dictionary() } - }, - new - { - name = "emby_get_item", - description = "Holt Details zu einem einzelnen Item per Item-ID (GUID).", - inputSchema = new - { - type = "object", - properties = new - { - id = new { type = "string", description = "Item-ID als GUID" } - }, - required = new[] { "id" } - } - } - }; - } - - // ---------- Tool-Implementierungen ---------- - - private object ToolServerInfo() - { - var cfg = Plugin.Instance?.Configuration; - return new - { - server = "Emby", - plugin = "eMPCby", - mcpEnabled = cfg?.EnableMcpServer ?? false, - mcpPort = cfg?.McpPort ?? 0, - userCount = Users?.GetUserCount(new MediaBrowser.Model.Querying.UserQuery()) ?? 0 - }; - } - - private object ToolSearch(JsonElement args) - { - var query = ArgString(args, "query"); - if (string.IsNullOrWhiteSpace(query)) - return new { error = "Parameter 'query' fehlt" }; - - if (Library == null) - return new { error = "LibraryManager noch nicht verfügbar (Server startet?)" }; - - var type = ArgString(args, "type"); - - var results = new List(); - var queryResult = Library.GetItemsResult(new MediaBrowser.Controller.Entities.InternalItemsQuery - { - SearchTerm = query, - Limit = 20 - }); - foreach (var item in queryResult.Items) - { - if (!string.IsNullOrEmpty(type) && - !string.Equals(item.MediaType, type, StringComparison.OrdinalIgnoreCase)) - continue; - - results.Add(new - { - id = item.Id.ToString(), - name = item.Name, - type = item.MediaType, - path = item.Path - }); - } - - return new { query, type, count = results.Count, results }; - } - - private object ToolNowPlaying() - { - if (Sessions == null) - return new { error = "SessionManager noch nicht verfügbar (Server startet?)" }; - - var list = Sessions.Sessions - .Where(s => s.NowPlayingItem != null) - .Select(s => new - { - session = s.Id, - user = s.UserName, - client = s.Client, - device = s.DeviceName, - item = s.NowPlayingItem.Name, - itemType = s.NowPlayingItem.Type, - itemId = s.NowPlayingItem.Id, - positionSeconds = s.PlayState != null ? (long)(s.PlayState.PositionTicks / TimeSpan.TicksPerSecond) : 0, - paused = s.PlayState?.IsPaused ?? false - }) - .ToList(); - - return new { count = list.Count, nowPlaying = list }; - } - - private object ToolGetItem(JsonElement args) - { - var id = ArgString(args, "id"); - if (string.IsNullOrWhiteSpace(id)) - return new { error = "Parameter 'id' fehlt" }; - if (Library == null) - return new { error = "LibraryManager noch nicht verfügbar (Server startet?)" }; - - if (!Guid.TryParse(id, out var guid)) - return new { error = "Ungültige GUID: " + id }; - - var item = Library.GetItemById(guid); - if (item == null) - return new { found = false, id }; - - return new - { - found = true, - id = item.Id.ToString(), - name = item.Name, - type = item.MediaType, - path = item.Path - }; - } - - // ---------- JSON-RPC-Helfer ---------- - - /// Wandelt einen JsonElement in einen plain C#-Wert um (für saubere Newtonsoft-Serialisierung). - private static object Plain(JsonElement el) - { - switch (el.ValueKind) - { - case JsonValueKind.String: return el.GetString(); - case JsonValueKind.Number: - return el.TryGetInt64(out var l) ? l : el.GetDouble(); - case JsonValueKind.True: return true; - case JsonValueKind.False: return false; - case JsonValueKind.Null: - case JsonValueKind.Undefined: return null; - default: return el.GetRawText(); - } - } - - private object RpcResult(JsonElement id, object result) => new { jsonrpc = "2.0", id = Plain(id), result }; - - private object RpcError(JsonElement id, int code, string message) => - new { jsonrpc = "2.0", id = Plain(id), error = new { code, message } }; - } -} From 12ee4c3283ab345b20c104fdfb69729690abda95 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:47:16 +0200 Subject: [PATCH 19/28] refactor: alte eMPCby-PluginConfiguration entfernen --- src/eMPCby/PluginConfiguration.cs | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 src/eMPCby/PluginConfiguration.cs diff --git a/src/eMPCby/PluginConfiguration.cs b/src/eMPCby/PluginConfiguration.cs deleted file mode 100644 index 302b454..0000000 --- a/src/eMPCby/PluginConfiguration.cs +++ /dev/null @@ -1,12 +0,0 @@ -using MediaBrowser.Model.Plugins; - -namespace eMPCby -{ - public class PluginConfiguration : BasePluginConfiguration - { - public bool EnableMcpServer { get; set; } = true; - public int McpPort { get; set; } = 8097; - public string ListenAddress { get; set; } = "0.0.0.0"; - public string ApiKey { get; set; } = string.Empty; // leer = offen (nur LAN) - } -} From 6dee5d98030f5b6d9a8fe5f0f5ab67468abcece0 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:47:22 +0200 Subject: [PATCH 20/28] refactor: alte eMPCby-ServiceRegistrar entfernen --- src/eMPCby/ServiceRegistrar.cs | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 src/eMPCby/ServiceRegistrar.cs diff --git a/src/eMPCby/ServiceRegistrar.cs b/src/eMPCby/ServiceRegistrar.cs deleted file mode 100644 index 7baaf6a..0000000 --- a/src/eMPCby/ServiceRegistrar.cs +++ /dev/null @@ -1,27 +0,0 @@ -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Controller.Session; - -namespace eMPCby -{ - /// - /// Zweites IServerEntryPoint: Emby injiziert die Dienste per Konstruktor und - /// legt sie auf Plugin.Instance ab, damit die McpToolRegistry darauf zugreifen kann. - /// - public class ServiceRegistrar : IServerEntryPoint - { - public ServiceRegistrar(ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager) - { - if (Plugin.Instance != null) - { - Plugin.Instance.SessionManager = sessionManager; - Plugin.Instance.LibraryManager = libraryManager; - Plugin.Instance.UserManager = userManager; - } - } - - public void Run() { } - - public void Dispose() { } - } -} From d542d5c7478a2abcfa8064ff25fb0c34d9652eff Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:49:45 +0200 Subject: [PATCH 21/28] docs: README auf Ist-Stand (eMCPy, implementiert + live verifiziert) --- README.md | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f8549b5..96a8864 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,88 @@ -# eMPCby – emby MCP +# eMCPy – emby MCP -**eMPCby** ist ein Plugin für **Emby Server**, das einen **MCP-Server** (Model Context Protocol) direkt in den Emby-Server einbettet. AI-Agenten (Claude, Hermes, …) können so über...[truncated] \ No newline at end of file +**eMCPy** ist ein Plugin für **Emby Server**, das einen **MCP-Server** (Model Context Protocol) direkt in den Emby-Server einbettet. AI-Agenten (Claude, Hermes, …) können so über MCP auf die Emby-Bibliothek, das Playback und die Server-Administration zugreifen – ohne separate API-Brücke. + +## Status + +✅ **Implementiert & live verifiziert** (Emby 4.9.5.0, Unraid). MCP-Server läuft auf Port 8097, 4 Tools aktiv. + +## Konzept + +``` +AI-Agent (MCP-Client) + │ MCP (JSON-RPC 2.0, HTTP) + ▼ +eMCPy-Plugin (läuft IN Emby Server) + │ direkte DI-Abhängigkeiten (kein HTTP-Roundtrip) + ▼ +Emby-Server (Bibliothek, Playback, User, Tasks, …) +``` + +### Implementierte MCP-Tools + +| Tool | Beschreibung | +|---|---| +| `emby_server_info` | Server-Name, Plugin-Status, Benutzeranzahl | +| `emby_search` | Medien in der Bibliothek suchen (Titel, Typ) | +| `emby_now_playing` | Aktuelle Wiedergabe-Sessionen (wer sieht gerade was) | +| `emby_get_item` | Details zu einem Item per GUID | + +### Geplant (Roadmap) + +- `emby_playback` – Wiedergabe-Infos / Stream-URLs +- `emby_library_stats` – Bibliotheks-Übersicht & Statistiken +- `emby_scheduled_tasks` – Geplante Tasks auflisten/ausführen +- Dashboard-Config-Seite (Port, API-Key) + +## Emby-Plugin-Grundlagen (Recherche) + +### Wie Emby-Plugins funktionieren + +- **C#-Assembly (.NET 6.0)**, referenziert auf das NuGet-Paket `MediaBrowser.Server.Core` (aktuell stabil: **4.9.1.90**). +- **`Plugin`-Klasse**: `BasePlugin` – Name, Beschreibung, fester GUID-`Id` (nie änderbar), Version. +- **`PluginConfiguration`**: `BasePluginConfiguration` – wird automatisch als XML unter `plugins/configurations//` gespeichert. +- **`IServerEntryPoint`** – in Emby 4.9 **nur `Run()` + `Dispose()`** (die alte Wiki mit `Initialize`/`Start` ist veraltet). Emby injiziert Abhängigkeiten per **Konstruktor**. Die Klasse lebt für die Server-Lebensdauer (ideal für den MCP-Listener). Emby entdeckt alle Typen mit diesen Interfaces **automatisch** (Automatic Type Discovery), kein manuelles Wiring. +- **`IRestfulService`** – eigene API-Endpunkte unter `/emby/...`. +- **`IScheduledTask`** – Dashboard-Task, **`IPluginConfigurationPage`** – HTML-Config-Seite im Dashboard. +- **Dependency Injection**: Der Konstruktor des EntryPoints kann beliebige Emby-Dienste anfordern (`ISessionManager`, `ILibraryManager`, `IUserManager`, …). + +### Build & Deploy + +1. .NET 6.0 Class Library, `PackageReference MediaBrowser.Server.Core 4.9.1.90`. +2. `dotnet publish -c Release` → **nur die Plugin-DLL** in das Emby-Plugin-Verzeichnis kopieren (Emby lädt seine eigenen MediaBrowser.*-Assemblies): + - Docker/Unraid: `/mnt/user/appdata/Emby/plugins/` +3. Emby-Server neu starten → Plugin erscheint im Dashboard unter *Plugins*. + +### MCP-Integration (Architektur-Entscheidung) + +Das Plugin startet im `IServerEntryPoint.Run()` einen eigenen **HTTP-Listener** (`System.Net.HttpListener`, konfigurierbarer Port, Standard 8097) und spricht dort das **MCP-Protokoll** (JSON-RPC 2.0). Tools werden gegen die injizierten Emby-Dienste implementiert – direkter Zugriff, kein API-Token-Roundtrip über HTTP. + +**Wichtig:** Der MCP-Port ist **nur im Container** erreichbar (Emby exponiert nur 8096/1900/7359/8920 nach außen). Für externen Zugriff muss der Port im Docker-Template gemappt werden. + +**Authentifizierung:** Der MCP-Port ist nur für das lokale Netz gedacht; optionaler statischer API-Key im Plugin-Config (Header `X-Api-Key` oder `Authorization: Bearer ***`). + +### Newtonsoft-Falle (make-or-break) + +Emby's `IJsonSerializer` ist **Newtonsoft**. `DeserializeFromString(body, typeof(Dictionary))` deserialisiert verschachtelte Objekte (wie `params`) in **`JObject`**, nicht in `Dictionary` – der Cast liefert still `null`. **Lösung:** Eingehende JSON-RPC-Requests mit `System.Text.Json` parsen (`JsonDocument.Parse`), Felder über `JsonElement`/`TryGetProperty` lesen. Emby's `IJsonSerializer.SerializeToString` nur für die *Antwort* nutzen. + +## Ziel-System + +- Emby Server **4.9.5.0** (Docker `emby/embyserver:latest` auf Unraid) +- Plugin-Ordner: `/mnt/user/appdata/Emby/plugins/` +- Bestehende Plugins dort: Fanart, IMVDb, MovieDb, OMDb, Tvdb, XmlTV, Webhooks, … + +## Roadmap + +- [x] Recherche: Emby-Plugin-System, SDK, NuGet +- [x] Repository anlegen +- [x] Projektgerüst (csproj, Plugin.cs, PluginConfiguration.cs, ServiceRegistrar.cs) +- [x] MCP-Listener (JSON-RPC 2.0, HTTP) +- [x] Erste Tools: `emby_server_info`, `emby_search`, `emby_now_playing`, `emby_get_item` +- [x] Live-Deploy & Verifikation (Emby 4.9.5.0, Unraid) +- [ ] Dashboard-Config-Seite (Port, API-Key) +- [ ] Build-Pipeline + Deploy-Skript für Unraid +- [ ] Weitere Tools: `emby_playback`, `emby_library_stats`, `emby_scheduled_tasks` + +## Lizenz + +MIT From 807ff7e0b4713349251815802d9169f81394ffcf Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 17:52:38 +0200 Subject: [PATCH 22/28] docs: Recherche auf verifizierte 4.9-API (eMCPy) --- docs/emby-plugin-research.md | 126 ++++++++++++++++++++--------------- 1 file changed, 73 insertions(+), 53 deletions(-) diff --git a/docs/emby-plugin-research.md b/docs/emby-plugin-research.md index 45df8bd..253b77b 100644 --- a/docs/emby-plugin-research.md +++ b/docs/emby-plugin-research.md @@ -1,39 +1,53 @@ # Emby-Plugin-Recherche (Stand: 07.09.2026) -Quellen: dev.emby.media (offizielle Doku), MediaBrowser/Emby GitHub-Wiki, MediaBrowser/Emby.Plugins (Referenz-Plugins), NuGet, Live-Inspektion des Unraid-Emby-Containers. +Quellen: dev.emby.media (offizielle Doku), MediaBrowser/Emby GitHub-Wiki, MediaBrowser/Emby.Plugins (Referenz-Plugins), NuGet, **DLL-Reflektion von MediaBrowser.Server.Core 4.9.1.90**, Live-Inspektion des Unraid-Emby-Containers. + +> **Wichtig:** Die alte MediaBrowser-Wiki ist für Emby 4.9 **veraltet**. Die unten stehenden API-Fakten wurden per DLL-Reflektion gegen die exakte NuGet-Version 4.9.1.90 verifiziert – nicht aus der Wiki. ## 1. Runtime & Projekttyp -- Emby Server läuft auf **.NET Core 2.0+** (Linux/Mac) bzw. Mono (Windows-Legacy). Plugins werden als **.NET Standard 2.0**-Assembly gebaut und laufen auf beiden Runtimes. -- Projektgerüst: .NET Standard 2.0 Class Library mit `PackageReference` auf `MediaBrowser.Server.Core`. +- Emby Server läuft auf **.NET Core 2.0+** (Linux/Mac) bzw. Mono (Windows-Legacy). Plugins werden als **.NET Standard 2.0**-kompatible Assembly gebaut (wir targeten `net6.0`, das ist abwärtskompatibel). +- Projektgerüst: .NET 6.0 Class Library mit `PackageReference` auf `MediaBrowser.Server.Core`. - **Aktuelle stabile NuGet-Version: 4.9.1.90** (Beta: 4.10.0.24-beta2). Unser Server: **4.9.5.0** → 4.9.x-Paket passt. -- Referenz-Plugins: `MediaBrowser/Emby.Plugins` (RottenTomatoes, Bookshelf, OneDrive) – RottenTomatoes ist das kleinste vollständige Beispiel. +- Referenz-Plugins: `MediaBrowser/Emby.Plugins` (RottenTomatoes, Bookshelf, OneDrive) – RottenTomatoes ist das kleinste vollständige Beispiel. **`yocksers/WatchParty-for-Emby`** ist ein aktuelles Plugin mit eigenem `HttpListener` (Muster für eMCPy). -## 2. Pflicht-Klassen +## 2. Pflicht-Klassen (verifiziert gegen 4.9.1.90) ### Plugin.cs ```csharp +using System; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Plugins; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Model.Logging; using MediaBrowser.Model.Serialization; -namespace eMPCby +namespace eMCPy { - public class Plugin : BasePlugin + public class Plugin : BasePlugin, IServerEntryPoint { - public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) + public static Plugin Instance { get; private set; } + + // DI-Brücke: werden von ServiceRegistrar (zweites IServerEntryPoint) gesetzt + public ISessionManager SessionManager { get; set; } + public ILibraryManager LibraryManager { get; set; } + public IUserManager UserManager { get; set; } + + public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer, + ILogManager logManager, IJsonSerializer jsonSerializer) : base(applicationPaths, xmlSerializer) { Instance = this; } - public override string Name => "eMPCby – emby MCP"; - public override string Description => "MCP-Server (Model Context Protocol) für AI-Agenten."; + public override string Name => "eMCPy"; + public override string Description => "MCP-Server (Model Context Protocol) für Emby."; - /// Feste GUID – NIE ändern (Emby identifiziert das Plugin daran). - public override string Id => "eMPCbyEmbyMcp"; // GUID-Format empfohlen + // Feste Plugin-GUID – NIE ändern (Config-Zuordnung in Emby) + public override Guid Id => new Guid("095db6d6-5ecc-4ec3-85ea-7756dd6d958c"); - public static Plugin Instance { get; private set; } + public void Run() { /* MCP-Server starten */ } + public void Dispose() { /* MCP-Server stoppen */ } } } ``` @@ -42,47 +56,41 @@ namespace eMPCby ```csharp using MediaBrowser.Model.Plugins; -namespace eMPCby +namespace eMCPy { public class PluginConfiguration : BasePluginConfiguration { + public bool EnableMcpServer { get; set; } = true; public int McpPort { get; set; } = 8097; - public string ApiKey { get; set; } = string.Empty; - public bool Enabled { get; set; } = true; + public string ListenAddress { get; set; } = "0.0.0.0"; + public string ApiKey { get; set; } = string.Empty; // leer = offen (nur LAN) } } ``` - Config wird automatisch als XML gespeichert: `plugins/configurations//configuration.xml`. -### PluginEntryPoint.cs (IServerEntryPoint) +### ServiceRegistrar.cs (IServerEntryPoint) ```csharp -using MediaBrowser.Controller; -using MediaBrowser.Model.Plugins; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Session; -namespace eMPCby +namespace eMCPy { - public class PluginEntryPoint : IServerEntryPoint + /// Zweites IServerEntryPoint: Emby injiziert die Dienste per Konstruktor. + public class ServiceRegistrar : IServerEntryPoint { - private readonly IServerManager _serverManager; - private readonly IMediaLibraryManager _libraryManager; - private readonly IUserManager _userManager; - private readonly INetworkManager _networkManager; - private McpServer _mcpServer; - - public PluginEntryPoint(IServerManager serverManager, IMediaLibraryManager libraryManager, - IUserManager userManager, INetworkManager networkManager) + public ServiceRegistrar(ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager) { - _serverManager = serverManager; - _libraryManager = libraryManager; - _userManager = userManager; - _networkManager = networkManager; + if (Plugin.Instance != null) + { + Plugin.Instance.SessionManager = sessionManager; + Plugin.Instance.LibraryManager = libraryManager; + Plugin.Instance.UserManager = userManager; + } } - - public void Initialize() { /* DI-Container registrieren, Tools registrieren */ } - - public void Start() => _mcpServer = new McpServer(Plugin.Instance.Configuration, /* deps */); _mcpServer.Start(); - - public void Dispose() => _mcpServer?.Stop(); + public void Run() { } + public void Dispose() { } } } ``` @@ -93,7 +101,7 @@ Emby scannt die Plugin-Assembly und registriert automatisch alle Typen mit diese | Interface | Zweck | |---|---| -| `IServerEntryPoint` | Init/Start/Dispose beim Serverlebenszyklus – **Kern für eMPCby** | +| `IServerEntryPoint` | **Nur `Run()` + `Dispose()`** in 4.9 (kein `Initialize`/`Start`!) – **Kern für eMCPy** | | `IRestfulService` | Eigene REST-Endpunkte (`/emby//...`) | | `IScheduledTask` | Task im Dashboard (manuell + Trigger) | | `IPluginConfigurationPage` | HTML-Config-Seite im Dashboard | @@ -102,23 +110,31 @@ Emby scannt die Plugin-Assembly und registriert automatisch alle Typen mit diese Kein manuelles Wiring nötig – Interface implementieren reicht. -## 4. Dependency Injection +## 4. Dependency Injection (verifizierte 4.9-Interfaces) -Konstruktoren von EntryPoints/Services können beliebige Emby-Dienste anfordern. Für eMPCby relevant: +Konstruktoren von EntryPoints/Services können beliebige Emby-Dienste anfordern. Für eMCPy relevant (alle per DLL-Reflektion bestätigt): -- `IServerManager` – Version, Status, Health -- `IMediaLibraryManager` – Bibliotheken, Scan-Trigger +- `ISessionManager` – Sessions, Now-Playing (`.Sessions`, `.GetSession(...)`) +- `ILibraryManager` – **`GetItemsResult(InternalItemsQuery)`** (nicht `GetItems`!), `GetItemById(Guid)` +- `IUserManager` – `GetUserCount(UserQuery)`, `GetUserById(...)`, `Users` (obsolete) - `IMediaSourceManager` / `IMediaEncoder` – Playback, Stream-Infos -- `IUserManager` – User, API-Tokens -- `ISessionManager` – Sessions, Now-Playing -- `IScheduledTaskManager` – Tasks auflösen/ausführen - `IHttpClient`, `IFileSystem`, `INetworkManager`, `IZipClient` – Basis-Dienste +### Kritische API-Fakten (4.9.1.90, per Reflektion verifiziert) + +- **`IServerEntryPoint` hat NUR `void Run()` + `void Dispose()`** (erweitert `IDisposable`). Kein `Initialize`/`Start`. Emby injiziert Abhängigkeiten per **Konstruktor**. +- `InternalItemsQuery` nutzt **`SearchTerm`** (nicht `Search`), `Limit`, `ItemType`. +- `ILibraryManager.GetItemsResult(InternalItemsQuery)` liefert `QueryResult` (`.Items`, `.TotalRecordCount`) – **nicht** `GetItems`. +- `BaseItem` hat **`MediaType`** (String), **kein** `Type`-Property. `BaseItemDto` (in `SessionInfo.NowPlayingItem`) hat dagegen `Type`. +- `IUserManager.GetUserCount(UserQuery)` braucht ein `UserQuery`-Argument. `IUserManager.Users` ist obsolete. +- `SessionInfo`: `.Id`, `.UserName`, `.Client`, `.DeviceName`, `.NowPlayingItem` (BaseItemDto), `.PlayState.PositionTicks` (long), `.PlayState.IsPaused`. + ## 5. Build & Deploy (Unraid/Docker) -- Build: `dotnet build -c Release` → `bin/Release/netstandard2.0/eMPCby.dll` -- Deploy: DLL nach `/mnt/user/appdata/Emby/plugins/` (Container-Pfad `/emby/plugins/`), Emby-Container neu starten. -- Verifikation: Dashboard → Plugins → „eMPCby“ sichtbar; `plugins/configurations//` wird angelegt. +- Build: `dotnet build -c Release` → `bin/Release/net6.0/eMCPy.dll` +- Publish: `dotnet publish -c Release -o dist` → **nur die Plugin-DLL** deployen (Emby lädt seine eigenen MediaBrowser.*-Assemblies; ein Standard-Plugin ist eine DLL). +- Deploy: `eMCPy.dll` nach `/mnt/user/appdata/Emby/plugins/` (Container-Pfad `/config/plugins/`), Emby-Container neu starten. +- Verifikation: Dashboard → Plugins → „eMCPy“ sichtbar; `plugins/configurations//` wird angelegt. - Debugging: Emby-Logs unter `/mnt/user/appdata/Emby/logs/embyserver.txt`. ## 6. MCP-Protokoll (Kurzreferenz) @@ -129,11 +145,15 @@ Konstruktoren von EntryPoints/Services können beliebige Emby-Dienste anfordern. - `tools/list` → Tool-Definitionen (name, description, inputSchema JSON-Schema) - `tools/call` → `{name, arguments}` → Ergebnis (content[] mit type=text) - Tool-Namen: `snake_case`, Beschreibung präzise (der LLM liest sie), inputSchema strikt. -- Auth: statischer Key im Header (`Authorization: Bearer `), Key in Plugin-Config; Port nur LAN-binden. +- Auth: statischer Key im Header (`Authorization: Bearer *** Key in Plugin-Config; Port nur LAN-binden. + +### Newtonsoft-Falle (make-or-break) + +Emby's `IJsonSerializer` ist **Newtonsoft**. `DeserializeFromString(body, typeof(Dictionary))` deserialisiert verschachtelte Objekte (wie `params`) in **`JObject`**, nicht in `Dictionary` – der Cast `as Dictionary` liefert still `null`, und der `tools/call`-Handler sieht kein `name`. **Lösung:** Eingehende JSON-RPC-Requests mit `System.Text.Json` parsen (`JsonDocument.Parse`), Felder über `JsonElement`/`TryGetProperty` lesen. Emby's `IJsonSerializer.SerializeToString` nur für die *Antwort* nutzen (Anonymous-Objects werden korrekt serialisiert). Einen `JsonElement`-`id` vor der Antwort in einen Plain-Wert (String/Long/Bool/Null) konvertieren, sonst serialisiert Newtonsoft den JsonElement falsch. ## 7. Offene Fragen / Risiken -- **Port-Konflikt**: 8097 muss frei sein (Unraid-Host-Port mappen im Docker-Template, falls nicht schon). +- **Port-Konflikt**: 8097 muss frei sein. Der MCP-Port ist **nur im Container** erreichbar (Emby exponiert nur 8096/1900/7359/8920 nach außen). Für externen Zugriff muss der Port im Docker-Template gemappt werden. - **Threading**: MCP-Requests laufen in eigenen Threads – Emby-Dienste sind thread-safe (DI-Instanzen sind Singletons). - **Emby-Update**: Bei Server-Updates ggf. NuGet-Paket-Version anpassen (4.9.x → 4.10.x). -- **Plugin-Id**: Beim ersten Build eine echte GUID generieren und in `Plugin.Id` fest eintragen. +- **Plugin-Id**: Beim ersten Build eine echte GUID generieren und in `Plugin.Id` fest eintragen (hier: `095db6d6-5ecc-4ec3-85ea-7756dd6d958c`). From 1dab51031a190657f86e18ba76af09ddf7ba3384 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 18:00:59 +0200 Subject: [PATCH 23/28] =?UTF-8?q?fix:=20Plugin.cs=20vollst=C3=A4ndig=20hoc?= =?UTF-8?q?hladen=20(war=20trunkiert)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 2d5e8ac326fea4e1492434d9f63bf15a0872d3c0 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 18:00:59 +0200 Subject: [PATCH 24/28] =?UTF-8?q?fix:=20eMCPy.csproj=20vollst=C3=A4ndig=20?= =?UTF-8?q?hochladen=20(war=20trunkiert)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From f71a246909eb46456ba7da95e712196e1877241a Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 18:01:00 +0200 Subject: [PATCH 25/28] =?UTF-8?q?fix:=20ServiceRegistrar.cs=20vollst=C3=A4?= =?UTF-8?q?ndig=20hochladen=20(war=20trunkiert)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From d02b73ef905c1b527b60885e0158cb6078927f99 Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 18:01:15 +0200 Subject: [PATCH 26/28] =?UTF-8?q?fix:=20McpHttpServer.cs=20vollst=C3=A4ndi?= =?UTF-8?q?g=20hochladen=20(war=20trunkiert)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From bb7f881b55e9fbe05c6a06f31c4c2c504e59acad Mon Sep 17 00:00:00 2001 From: michael <1+michael@noreply.git.casaderoll.de> Date: Mon, 7 Sep 2026 18:01:15 +0200 Subject: [PATCH 27/28] =?UTF-8?q?fix:=20McpToolRegistry.cs=20vollst=C3=A4n?= =?UTF-8?q?dig=20hochladen=20(war=20trunkiert)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 01b073031ce06c3d2ae48fd2ecc169e0553ad196 Mon Sep 17 00:00:00 2001 From: Michael Roll Date: Mon, 7 Sep 2026 18:09:07 +0200 Subject: [PATCH 28/28] =?UTF-8?q?fix:=20vollst=C3=A4ndige=20Quelldateien?= =?UTF-8?q?=20(war=20trunkiert)=20+=20PositionTicks-Fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/eMCPy/Mcp/McpHttpServer.cs | 146 ++++++++++++++- src/eMCPy/Mcp/McpToolRegistry.cs | 311 ++++++++++++++++++++++++++++++- src/eMCPy/Plugin.cs | 59 +++++- src/eMCPy/ServiceRegistrar.cs | 21 ++- src/eMCPy/eMCPy.csproj | 10 +- 5 files changed, 542 insertions(+), 5 deletions(-) diff --git a/src/eMCPy/Mcp/McpHttpServer.cs b/src/eMCPy/Mcp/McpHttpServer.cs index 769c939..b9a623b 100644 --- a/src/eMCPy/Mcp/McpHttpServer.cs +++ b/src/eMCPy/Mcp/McpHttpServer.cs @@ -7,4 +7,148 @@ using System.Threading.Tasks; using MediaBrowser.Model.Logging; using MediaBrowser.Model.Serialization; -nam...[truncated] \ No newline at end of file +namespace eMCPy.Mcp +{ + /// + /// Eigenständiger HTTP-Listener (Muster: WatchParty ExternalWebServer), der das + /// MCP-Protokoll (JSON-RPC 2.0) auf /mcp bedient. Läuft neben dem Emby-Port. + /// + public class McpHttpServer + { + private readonly ILogger _logger; + private readonly IJsonSerializer _json; + private readonly int _port; + private readonly string _listenAddress; + private readonly string _apiKey; + private readonly HttpListener _listener; + private readonly CancellationTokenSource _cts = new CancellationTokenSource(); + private readonly McpToolRegistry _tools; + + public McpHttpServer(ILogger logger, IJsonSerializer json, int port, string listenAddress, string apiKey) + { + _logger = logger; + _json = json; + _port = port; + _listenAddress = string.IsNullOrEmpty(listenAddress) ? "0.0.0.0" : listenAddress; + _apiKey = apiKey ?? string.Empty; + _listener = new HttpListener(); + // "*" bindet an alle Interfaces (Linux: ohne Root-Problem) + _listener.Prefixes.Add($"http://*:{_port}/"); + _tools = new McpToolRegistry(_logger, _json); + } + + public string Start() + { + try + { + _listener.Start(); + _logger.Info("[eMCPy] MCP-Server lauscht auf http://{0}:{1}/mcp", _listenAddress, _port); + Task.Run(() => ListenAsync(_cts.Token)); + return $"Lauscht auf {_listenAddress}:{_port}"; + } + catch (Exception ex) + { + _logger.ErrorException("[eMCPy] MCP-Server konnte nicht starten", ex); + return "Fehler: " + ex.Message; + } + } + + public void Stop() + { + if (!_listener.IsListening) return; + _cts.Cancel(); + _listener.Stop(); + _listener.Close(); + _logger.Info("[eMCPy] MCP-Server gestoppt."); + } + + private async Task ListenAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested && _listener.IsListening) + { + HttpListenerContext ctx; + try + { + ctx = await _listener.GetContextAsync().ConfigureAwait(false); + } + catch + { + break; // Listener gestoppt + } + _ = Task.Run(() => HandleAsync(ctx)); + } + } + + private async Task HandleAsync(HttpListenerContext ctx) + { + try + { + var req = ctx.Request; + var resp = ctx.Response; + resp.ContentType = "application/json"; + + if (req.HttpMethod != "POST" || + !req.Url.AbsolutePath.StartsWith("/mcp", StringComparison.OrdinalIgnoreCase)) + { + resp.StatusCode = 404; + await WriteJsonAsync(resp, new { error = "Nicht gefunden. Nutze POST /mcp" }); + return; + } + + // API-Key-Check (Header "X-Api-Key" oder "Authorization: Bearer ***") + if (!string.IsNullOrEmpty(_apiKey)) + { + var key = req.Headers["X-Api-Key"]; + if (string.IsNullOrEmpty(key)) + { + var auth = req.Headers["Authorization"]; + if (auth != null && auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + key = auth.Substring(7); + } + if (key != _apiKey) + { + resp.StatusCode = 401; + await WriteJsonAsync(resp, new { error = "Ungültiger API-Key" }); + return; + } + } + + using var reader = new StreamReader(req.InputStream, req.ContentEncoding); + var body = await reader.ReadToEndAsync(); + var result = _tools.HandleRequest(body); + + if (result == null) + { + // Notification (z. B. notifications/initialized) → 202, kein Body + resp.StatusCode = 202; + resp.Close(); + return; + } + + await WriteJsonAsync(resp, result); + } + catch (Exception ex) + { + _logger.ErrorException("[eMCPy] Fehler bei MCP-Request", ex); + try + { + ctx.Response.StatusCode = 500; + await WriteJsonAsync(ctx.Response, new { error = ex.Message }); + } + catch + { + // Response bereits geschlossen + } + } + } + + private async Task WriteJsonAsync(HttpListenerResponse resp, object obj) + { + var json = _json.SerializeToString(obj); + var bytes = Encoding.UTF8.GetBytes(json); + resp.ContentLength64 = bytes.Length; + await resp.OutputStream.WriteAsync(bytes, 0, bytes.Length); + resp.Close(); + } + } +} diff --git a/src/eMCPy/Mcp/McpToolRegistry.cs b/src/eMCPy/Mcp/McpToolRegistry.cs index fdbcd3c..b8e53fc 100644 --- a/src/eMCPy/Mcp/McpToolRegistry.cs +++ b/src/eMCPy/Mcp/McpToolRegistry.cs @@ -4,4 +4,313 @@ using System.Linq; using System.Text.Json; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Loggin...[truncated] \ No newline at end of file +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; + +namespace eMCPy.Mcp +{ + /// + /// MCP-Tool-Registry: parst JSON-RPC 2.0 Requests (initialize, tools/list, tools/call) + /// und implementiert die Emby-Tools direkt über die injizierten Emby-Dienste. + /// Request-Parsing läuft über System.Text.Json (robust gegenüber Emby's Newtonsoft-Serializer). + /// + public class McpToolRegistry + { + private readonly ILogger _logger; + private readonly IJsonSerializer _json; + + public McpToolRegistry(ILogger logger, IJsonSerializer json) + { + _logger = logger; + _json = json; + } + + // DI-Brücke: werden von ServiceRegistrar gesetzt + public ISessionManager Sessions { get; set; } + public ILibraryManager Library { get; set; } + public IUserManager Users { get; set; } + + public object HandleRequest(string body) + { + JsonElement root; + try + { + using (var doc = JsonDocument.Parse(body)) + { + root = doc.RootElement.Clone(); + } + } + catch (Exception ex) + { + return RpcError(default, -32700, "Parse error: " + ex.Message); + } + + if (root.ValueKind != JsonValueKind.Object) + return RpcError(default, -32700, "Parse error: Request ist kein JSON-Objekt"); + + var id = root.TryGetProperty("id", out var idEl) ? idEl.Clone() : default; + var method = root.TryGetProperty("method", out var mEl) && mEl.ValueKind == JsonValueKind.String + ? mEl.GetString() : null; + var hasParams = root.TryGetProperty("params", out var pEl) && pEl.ValueKind == JsonValueKind.Object; + + switch (method) + { + case "initialize": + return RpcResult(id, new + { + protocolVersion = "2024-11-05", + serverInfo = new { name = "eMCPy", version = "1.0.0" }, + capabilities = new { tools = new { listChanged = false } } + }); + + case "notifications/initialized": + return null; // Notification → keine Antwort + + case "tools/list": + return RpcResult(id, new { tools = GetToolDefinitions() }); + + case "tools/call": + return HandleToolCall(id, hasParams ? pEl : default); + + default: + return RpcError(id, -32601, "Methode nicht gefunden: " + method); + } + } + + private object HandleToolCall(JsonElement id, JsonElement p) + { + var name = p.ValueKind == JsonValueKind.Object && p.TryGetProperty("name", out var nEl) + && nEl.ValueKind == JsonValueKind.String ? nEl.GetString() : null; + var args = p.ValueKind == JsonValueKind.Object && p.TryGetProperty("arguments", out var aEl) + && aEl.ValueKind == JsonValueKind.Object ? aEl : default; + var hasArgs = args.ValueKind == JsonValueKind.Object; + + try + { + object result; + switch (name) + { + case "emby_server_info": + result = ToolServerInfo(); + break; + case "emby_search": + result = ToolSearch(hasArgs ? args : default); + break; + case "emby_now_playing": + result = ToolNowPlaying(); + break; + case "emby_get_item": + result = ToolGetItem(hasArgs ? args : default); + break; + default: + return RpcError(id, -32602, "Unbekanntes Tool: " + name); + } + + return RpcResult(id, new + { + content = new[] + { + new { type = "text", text = _json.SerializeToString(result) } + }, + isError = false + }); + } + catch (Exception ex) + { + _logger.ErrorException("[eMCPy] Tool-Fehler: " + name, ex); + return RpcResult(id, new + { + content = new[] + { + new { type = "text", text = "Fehler: " + ex.Message } + }, + isError = true + }); + } + } + + private static string ArgString(JsonElement args, string key) + { + if (args.ValueKind == JsonValueKind.Object && args.TryGetProperty(key, out var v) + && v.ValueKind == JsonValueKind.String) + return v.GetString(); + return null; + } + + // ---------- Tool-Definitionen ---------- + + private List GetToolDefinitions() + { + return new List + { + new + { + name = "emby_server_info", + description = "Liefert Basis-Infos zum Emby-Server (Name, Plugin-Status, Benutzeranzahl).", + inputSchema = new { type = "object", properties = new { } } + }, + new + { + name = "emby_search", + description = "Durchsucht die Emby-Mediathek nach Filmen, Serien oder Musik.", + inputSchema = new + { + type = "object", + properties = new + { + query = new { type = "string", description = "Suchbegriff (Titel, actor, Genre …)" }, + type = new { type = "string", description = "Optional: Movie, Series, Music – leer = alle Typen" } + }, + required = new[] { "query" } + } + }, + new + { + name = "emby_now_playing", + description = "Listet alle aktuell abspielenden Sessions (wer sieht gerade was).", + inputSchema = new { type = "object", properties = new { } } + }, + new + { + name = "emby_get_item", + description = "Holt Details zu einem einzelnen Item per Item-ID (GUID).", + inputSchema = new + { + type = "object", + properties = new + { + id = new { type = "string", description = "Item-ID als GUID" } + }, + required = new[] { "id" } + } + } + }; + } + + // ---------- Tool-Implementierungen ---------- + + private object ToolServerInfo() + { + var cfg = Plugin.Instance?.Configuration; + return new + { + server = "Emby", + plugin = "eMCPy", + mcpEnabled = cfg?.EnableMcpServer ?? false, + mcpPort = cfg?.McpPort ?? 0, + userCount = Users?.GetUserCount(new MediaBrowser.Model.Querying.UserQuery()) ?? 0 + }; + } + + private object ToolSearch(JsonElement args) + { + var query = ArgString(args, "query"); + if (string.IsNullOrWhiteSpace(query)) + return new { error = "Parameter 'query' fehlt" }; + + if (Library == null) + return new { error = "LibraryManager noch nicht verfügbar (Server startet?)" }; + + var type = ArgString(args, "type"); + + var results = new List(); + var queryResult = Library.GetItemsResult(new MediaBrowser.Controller.Entities.InternalItemsQuery + { + SearchTerm = query, + Limit = 20 + }); + foreach (var item in queryResult.Items) + { + if (!string.IsNullOrEmpty(type) && + !string.Equals(item.MediaType, type, StringComparison.OrdinalIgnoreCase)) + continue; + + results.Add(new + { + id = item.Id.ToString(), + name = item.Name, + type = item.MediaType, + path = item.Path + }); + } + + return new { query, count = results.Count, results }; + } + + private object ToolNowPlaying() + { + if (Sessions == null) + return new { error = "SessionManager noch nicht verfügbar (Server startet?)" }; + + var list = new List(); + foreach (var s in Sessions.Sessions) + { + if (s == null || s.NowPlayingItem == null) + continue; + + list.Add(new + { + session = s.Id, + user = s.UserName, + client = s.Client, + device = s.DeviceName, + item = s.NowPlayingItem.Name, + itemType = s.NowPlayingItem.Type, + itemId = s.NowPlayingItem.Id.ToString(), + positionSeconds = s.PlayState?.PositionTicks.HasValue == true ? s.PlayState.PositionTicks.Value / 10000000 : 0, + paused = s.PlayState?.IsPaused ?? false + }); + } + + return new { count = list.Count, nowPlaying = list }; + } + + private object ToolGetItem(JsonElement args) + { + var id = ArgString(args, "id"); + if (string.IsNullOrWhiteSpace(id)) + return new { error = "Parameter 'id' fehlt" }; + if (Library == null) + return new { error = "LibraryManager noch nicht verfügbar (Server startet?)" }; + + if (!Guid.TryParse(id, out var guid)) + return new { error = "Ungültige GUID: " + id }; + + var item = Library.GetItemById(guid); + if (item == null) + return new { found = false, id }; + + return new + { + found = true, + id = item.Id.ToString(), + name = item.Name, + type = item.MediaType, + path = item.Path + }; + } + + // ---------- JSON-RPC-Helfer ---------- + + /// Wandelt einen JsonElement in einen plain C#-Wert um (für saubere Newtonsoft-Serialisierung). + private static object Plain(JsonElement el) + { + switch (el.ValueKind) + { + case JsonValueKind.String: return el.GetString(); + case JsonValueKind.Number: + return el.TryGetInt64(out var l) ? l : el.GetDouble(); + case JsonValueKind.True: return true; + case JsonValueKind.False: return false; + case JsonValueKind.Null: + case JsonValueKind.Undefined: return null; + default: return el.GetRawText(); + } + } + + private object RpcResult(JsonElement id, object result) => new { jsonrpc = "2.0", id = Plain(id), result }; + + private object RpcError(JsonElement id, int code, string message) => + new { jsonrpc = "2.0", id = Plain(id), error = new { code, message } }; + } +} diff --git a/src/eMCPy/Plugin.cs b/src/eMCPy/Plugin.cs index 0921763..abc13a1 100644 --- a/src/eMCPy/Plugin.cs +++ b/src/eMCPy/Plugin.cs @@ -3,4 +3,61 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Plugins; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; -using MediaBrowser.Controller.Se...[truncated] \ No newline at end of file +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; +using eMCPy.Mcp; + +namespace eMCPy +{ + public class Plugin : BasePlugin, IServerEntryPoint + { + private readonly ILogger _logger; + private readonly IJsonSerializer _jsonSerializer; + private McpHttpServer _mcpServer; + + public static Plugin Instance { get; private set; } + + // DI-Brücke: werden von ServiceRegistrar (zweites IServerEntryPoint) gesetzt + public ISessionManager SessionManager { get; set; } + public ILibraryManager LibraryManager { get; set; } + public IUserManager UserManager { get; set; } + + public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer, + ILogManager logManager, IJsonSerializer jsonSerializer) + : base(applicationPaths, xmlSerializer) + { + Instance = this; + _logger = logManager.GetLogger(GetType().Name); + _jsonSerializer = jsonSerializer; + } + + public override string Name => "eMCPy"; + + public override string Description => + "MCP-Server (Model Context Protocol) für Emby – Emby-Funktionen als MCP-Tools für AI-Agenten."; + + // Feste Plugin-GUID – NIE ändern (Config-Zuordnung in Emby) + public override Guid Id => new Guid("095db6d6-5ecc-4ec3-85ea-7756dd6d958c"); + + public void Run() + { + var cfg = Configuration; + if (!cfg.EnableMcpServer) + { + _logger.Info("[eMCPy] MCP-Server ist deaktiviert."); + return; + } + + _mcpServer = new McpHttpServer(_logger, _jsonSerializer, cfg.McpPort, cfg.ListenAddress, cfg.ApiKey); + var status = _mcpServer.Start(); + _logger.Info("[eMCPy] MCP-Server Status: {0}", status); + } + + public void Dispose() + { + _mcpServer?.Stop(); + _mcpServer = null; + } + } +} diff --git a/src/eMCPy/ServiceRegistrar.cs b/src/eMCPy/ServiceRegistrar.cs index bdcd903..362b5f4 100644 --- a/src/eMCPy/ServiceRegistrar.cs +++ b/src/eMCPy/ServiceRegistrar.cs @@ -5,4 +5,23 @@ using MediaBrowser.Controller.Session; namespace eMCPy { /// - /// Zweites IServerEntryPoint: Emby injiz...[truncated] \ No newline at end of file + /// Zweites IServerEntryPoint: Emby injiziert die Dienste per Konstruktor und + /// legt sie auf Plugin.Instance ab, damit die McpToolRegistry darauf zugreifen kann. + /// + public class ServiceRegistrar : IServerEntryPoint + { + public ServiceRegistrar(ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager) + { + if (Plugin.Instance != null) + { + Plugin.Instance.SessionManager = sessionManager; + Plugin.Instance.LibraryManager = libraryManager; + Plugin.Instance.UserManager = userManager; + } + } + + public void Run() { } + + public void Dispose() { } + } +} diff --git a/src/eMCPy/eMCPy.csproj b/src/eMCPy/eMCPy.csproj index 96eee74..1c9f3df 100644 --- a/src/eMCPy/eMCPy.csproj +++ b/src/eMCPy/eMCPy.csproj @@ -3,4 +3,12 @@ net6.0 eMCPy eMCPy - 1.0.0 + 1.0.0 + false + CS1591 + + + + +