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 } }; + } +}