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