From 303791c3cbaec1f9c2317ca4c754caa7e81c7abb Mon Sep 17 00:00:00 2001 From: Michael Roll Date: Tue, 8 Sep 2026 07:25:14 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20Dashboard-Config-Seite=20(Port,=20Liste?= =?UTF-8?q?n-Adresse,=20API-Key)=20+=20CORS=20f=C3=BCr=20Browser-Zugriff?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/eMCPy/Configuration/configPage.html | 66 ++++++++++++ src/eMCPy/Configuration/configPage.js | 127 ++++++++++++++++++++++++ src/eMCPy/Mcp/McpHttpServer.cs | 34 +++++++ src/eMCPy/Plugin.cs | 48 ++++++++- src/eMCPy/eMCPy.csproj | 4 + 5 files changed, 278 insertions(+), 1 deletion(-) create mode 100644 src/eMCPy/Configuration/configPage.html create mode 100644 src/eMCPy/Configuration/configPage.js diff --git a/src/eMCPy/Configuration/configPage.html b/src/eMCPy/Configuration/configPage.html new file mode 100644 index 0000000..f767b9e --- /dev/null +++ b/src/eMCPy/Configuration/configPage.html @@ -0,0 +1,66 @@ +
+ +
+
+

eMCPy Configuration

+

MCP-Server (Model Context Protocol) für AI-Agenten. Läuft eingebettet in Emby auf einem eigenen Port.

+ +
+
+

MCP-Server

+ +
+ +
+ Startet den HTTP-Listener mit dem MCP-Protokoll (JSON-RPC 2.0) beim Serverstart. +
+
+ +
+ + +
+ TCP-Port des MCP-Endpunkts (Standard: 8097). Muss auf dem Host frei sein und ggf. im Docker-Template gemappt werden. +
+
+ +
+ + +
+ 0.0.0.0 = alle Interfaces (empfohlen für Docker), 127.0.0.1 = nur lokal. +
+
+ +
+ + +
+ Optional. Leer = offen (nur im LAN verwenden!). Bei gesetztem Key müssen Clients den Header X-Api-Key oder Authorization: Bearer <Key> senden. +
+
+ +
+ Status wird geladen … +
+ +
+ +
+
+
+
+
+
diff --git a/src/eMCPy/Configuration/configPage.js b/src/eMCPy/Configuration/configPage.js new file mode 100644 index 0000000..09a12e9 --- /dev/null +++ b/src/eMCPy/Configuration/configPage.js @@ -0,0 +1,127 @@ +define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) { + 'use strict'; + + const pluginId = "095db6d6-5ecc-4ec3-85ea-7756dd6d958c"; + + function getPluginConfiguration() { + return ApiClient.getPluginConfiguration(pluginId); + } + + function updatePluginConfiguration(config) { + return ApiClient.updatePluginConfiguration(pluginId, config); + } + + return class extends BaseView { + constructor(view, params) { + super(view, params); + + view.querySelector('#emcpyConfigForm').addEventListener('submit', (e) => { + e.preventDefault(); + this.saveConfig(view); + return false; + }); + } + + init(options) { + super.init(options); + this.loadData(this.view); + } + + loadData(view) { + loading.show(); + getPluginConfiguration().then(config => { + view.querySelector('#enableMcpServer').checked = config.EnableMcpServer !== false; + view.querySelector('#mcpPort').value = config.McpPort || 8097; + view.querySelector('#listenAddress').value = config.ListenAddress || '0.0.0.0'; + view.querySelector('#apiKey').value = config.ApiKey || ''; + this.checkServerStatus(view, config); + loading.hide(); + }).catch(() => { + loading.hide(); + toast({ type: 'error', text: 'Konfiguration konnte nicht geladen werden.' }); + }); + } + + saveConfig(view) { + loading.show(); + const port = parseInt(view.querySelector('#mcpPort').value, 10); + if (isNaN(port) || port < 1024 || port > 65535) { + loading.hide(); + toast({ type: 'error', text: 'Port muss zwischen 1024 und 65535 liegen.' }); + return; + } + + getPluginConfiguration().then(config => { + config.EnableMcpServer = view.querySelector('#enableMcpServer').checked; + config.McpPort = port; + config.ListenAddress = view.querySelector('#listenAddress').value.trim() || '0.0.0.0'; + config.ApiKey = view.querySelector('#apiKey').value.trim(); + + updatePluginConfiguration(config).then(result => { + loading.hide(); + Dashboard.processPluginConfigurationUpdateResult(result); + toast({ type: 'success', text: 'Gespeichert. MCP-Server wird neu gestartet.' }); + setTimeout(() => this.checkServerStatus(view, config), 2000); + }).catch(() => { + loading.hide(); + toast({ type: 'error', text: 'Speichern fehlgeschlagen.' }); + }); + }); + } + + checkServerStatus(view, config) { + const el = view.querySelector('#serverStatus'); + const port = config.McpPort || 8097; + const enabled = config.EnableMcpServer !== false; + + if (!enabled) { + el.className = 'emcpy-status err'; + el.textContent = 'MCP-Server ist deaktiviert.'; + return; + } + + el.className = 'emcpy-status pending'; + el.textContent = 'Verbinde mit MCP-Server auf Port ' + port + ' …'; + + let hostname = 'localhost'; + try { + hostname = new URL(ApiClient.serverAddress()).hostname; + } catch (e) { /* fallback */ } + + const url = 'http://' + hostname + ':' + port + '/mcp'; + const body = JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'emcpy-dashboard', version: '1.0' } } + }); + + const headers = { 'Content-Type': 'application/json' }; + if (config.ApiKey) { + headers['X-Api-Key'] = config.ApiKey; + } + + fetch(url, { method: 'POST', headers: headers, body: body, cache: 'no-store' }) + .then(r => { + if (r.status === 401) throw new Error('401'); + return r.json(); + }) + .then(data => { + const name = data.result && data.result.serverInfo ? data.result.serverInfo.name : 'MCP-Server'; + el.className = 'emcpy-status ok'; + el.innerHTML = '✓ Läuft – ' + name + ' auf Port ' + port + + ' (Endpunkt)'; + }) + .catch(err => { + el.className = 'emcpy-status err'; + el.textContent = '✗ Nicht erreichbar auf Port ' + port + + (err.message === '401' ? ' (API-Key ungültig)' : ' – Port im Docker-Template gemappt?'); + }); + } + + onResume(options) { + super.onResume(options); + this.loadData(this.view); + } + }; +}); diff --git a/src/eMCPy/Mcp/McpHttpServer.cs b/src/eMCPy/Mcp/McpHttpServer.cs index 274efdc..8c0ef11 100644 --- a/src/eMCPy/Mcp/McpHttpServer.cs +++ b/src/eMCPy/Mcp/McpHttpServer.cs @@ -87,6 +87,18 @@ namespace eMCPy.Mcp var resp = ctx.Response; resp.ContentType = "application/json"; + // CORS: Dashboard (:8096) ruft den MCP-Port (:8097) cross-origin auf. + // Ohne diese Header blockt der Browser den Request. + ApplyCors(resp, req); + + // CORS-Preflight (Browser schickt OPTIONS vor POST) + if (req.HttpMethod == "OPTIONS") + { + resp.StatusCode = 204; + resp.Close(); + return; + } + if (req.HttpMethod != "POST" || !req.Url.AbsolutePath.StartsWith("/mcp", StringComparison.OrdinalIgnoreCase)) { @@ -142,6 +154,28 @@ namespace eMCPy.Mcp } } + /// + /// Setzt CORS-Header, damit das Emby-Dashboard (Browser) den MCP-Port + /// cross-origin aufrufen kann. Origin wird zurückgespiegelt (LAN-Plugin, + /// kein öffentlicher Service). + /// + private void ApplyCors(HttpListenerResponse resp, HttpListenerRequest req) + { + var origin = req.Headers["Origin"]; + if (!string.IsNullOrEmpty(origin)) + { + resp.AddHeader("Access-Control-Allow-Origin", origin); + resp.AddHeader("Access-Control-Allow-Credentials", "true"); + } + else + { + resp.AddHeader("Access-Control-Allow-Origin", "*"); + } + resp.AddHeader("Access-Control-Allow-Methods", "POST, OPTIONS"); + resp.AddHeader("Access-Control-Allow-Headers", "Content-Type, X-Api-Key, Authorization"); + resp.AddHeader("Access-Control-Max-Age", "86400"); + } + private async Task WriteJsonAsync(HttpListenerResponse resp, object obj) { var json = _json.SerializeToString(obj); diff --git a/src/eMCPy/Plugin.cs b/src/eMCPy/Plugin.cs index abc13a1..a57d7aa 100644 --- a/src/eMCPy/Plugin.cs +++ b/src/eMCPy/Plugin.cs @@ -1,16 +1,19 @@ using System; +using System.Collections.Generic; +using System.IO; 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.Plugins; using MediaBrowser.Model.Serialization; using eMCPy.Mcp; namespace eMCPy { - public class Plugin : BasePlugin, IServerEntryPoint + public class Plugin : BasePlugin, IServerEntryPoint, IHasWebPages { private readonly ILogger _logger; private readonly IJsonSerializer _jsonSerializer; @@ -41,6 +44,22 @@ namespace eMCPy public override Guid Id => new Guid("095db6d6-5ecc-4ec3-85ea-7756dd6d958c"); public void Run() + { + StartMcpServer(); + } + + /// + /// Wird von Emby aufgerufen, wenn die Config im Dashboard gespeichert wird. + /// Startet den MCP-Server neu, falls sich Port/Adresse/Key/Enabled geändert hat. + /// + public override void UpdateConfiguration(BasePluginConfiguration configuration) + { + base.UpdateConfiguration(configuration); + _logger.Info("[eMCPy] Configuration updated – MCP-Server wird neu gestartet."); + RestartMcpServer(); + } + + private void StartMcpServer() { var cfg = Configuration; if (!cfg.EnableMcpServer) @@ -54,6 +73,33 @@ namespace eMCPy _logger.Info("[eMCPy] MCP-Server Status: {0}", status); } + private void RestartMcpServer() + { + _mcpServer?.Stop(); + _mcpServer = null; + StartMcpServer(); + } + + /// + /// Registriert die Dashboard-Config-Seite (HTML + JS als Embedded Resources). + /// + public IEnumerable GetPages() + { + return new[] + { + new PluginPageInfo + { + Name = "emcpyconfig", + EmbeddedResourcePath = GetType().Namespace + ".Configuration.configPage.html" + }, + new PluginPageInfo + { + Name = "configPagejs", + EmbeddedResourcePath = GetType().Namespace + ".Configuration.configPage.js" + } + }; + } + public void Dispose() { _mcpServer?.Stop(); diff --git a/src/eMCPy/eMCPy.csproj b/src/eMCPy/eMCPy.csproj index 1c9f3df..4ed08c0 100644 --- a/src/eMCPy/eMCPy.csproj +++ b/src/eMCPy/eMCPy.csproj @@ -11,4 +11,8 @@ + + + +