feat: Dashboard-Config-Seite (Port, Listen-Adresse, API-Key) + CORS für Browser-Zugriff

This commit is contained in:
michael committed 2026-09-08 07:25:14 +02:00
1 parent 10176d0ebc
commit 303791c3cb
5 files changed
+278 -1

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
<div is="emby-scroller" class="view flex flex-direction-column scrollFrameY flex-grow" data-horizontal="false" data-forcescrollbar="true" data-centerfocus="true" data-bindheader="true" data-controller="__plugin/configPagejs" data-title="eMCPy">
<style>
.emcpy-page h2 { margin-top: 1.5em; margin-bottom: 0.5em; }
.emcpy-page code { background: #333; padding: 0.2em 0.5em; border-radius: 3px; }
.emcpy-status { margin-top: 1em; padding: 0.8em 1em; border-radius: 6px; background: rgba(255,255,255,0.03); border: 1px solid #3a3a3a; }
.emcpy-status.ok { border-color: #4CAF50; color: #4CAF50; }
.emcpy-status.err { border-color: #F44336; color: #F44336; }
.emcpy-status.pending { color: #FFA500; }
</style>
<div class="scrollSlider flex-direction-column padded-left padded-left-page padded-right padded-top-page padded-bottom-page">
<div class="readOnlyContent auto-center" style="max-width: 900px;">
<h1 class="pageTitle">eMCPy Configuration</h1>
<p style="color: #999; margin-top: -0.5em; margin-bottom: 1.5em;">MCP-Server (Model Context Protocol) für AI-Agenten. Läuft eingebettet in Emby auf einem eigenen Port.</p>
<form id="emcpyConfigForm" class="emcpyConfigForm">
<div class="paper-card" style="padding: 1.5em; margin-top: 2em;">
<h2 style="margin-top:0;">MCP-Server</h2>
<div class="checkboxContainer">
<label>
<input is="emby-checkbox" type="checkbox" id="enableMcpServer" />
<span>MCP-Server aktivieren</span>
</label>
<div class="fieldDescription">
Startet den HTTP-Listener mit dem MCP-Protokoll (JSON-RPC 2.0) beim Serverstart.
</div>
</div>
<div class="inputContainer" style="margin-top: 1em;">
<label class="inputLabel inputLabelUnfocused" for="mcpPort">Port</label>
<input is="emby-input" type="number" id="mcpPort" min="1024" max="65535" step="1" />
<div class="fieldDescription">
TCP-Port des MCP-Endpunkts (Standard: 8097). Muss auf dem Host frei sein und ggf. im Docker-Template gemappt werden.
</div>
</div>
<div class="inputContainer" style="margin-top: 1em;">
<label class="inputLabel inputLabelUnfocused" for="listenAddress">Listen-Adresse</label>
<input is="emby-input" type="text" id="listenAddress" />
<div class="fieldDescription">
<code>0.0.0.0</code> = alle Interfaces (empfohlen für Docker), <code>127.0.0.1</code> = nur lokal.
</div>
</div>
<div class="inputContainer" style="margin-top: 1em;">
<label class="inputLabel" for="apiKey">API-Key</label>
<input is="emby-input" type="password" id="apiKey" autocomplete="off" />
<div class="fieldDescription">
Optional. Leer = offen (nur im LAN verwenden!). Bei gesetztem Key müssen Clients den Header <code>X-Api-Key</code> oder <code>Authorization: Bearer &lt;Key&gt;</code> senden.
</div>
</div>
<div class="emcpy-status pending" id="serverStatus">
Status wird geladen …
</div>
<div style="margin-top: 1.5em;">
<button is="emby-button" type="submit" class="raised button-submit emby-button">
<span>Speichern</span>
</button>
</div>
</div>
</form>
</div>
</div>
</div>
+127
View File
@@ -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 +
' <a href="' + url + '" target="_blank" style="color:#4CAF50;">(Endpunkt)</a>';
})
.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);
}
};
});
+34
View File
@@ -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
}
}
/// <summary>
/// Setzt CORS-Header, damit das Emby-Dashboard (Browser) den MCP-Port
/// cross-origin aufrufen kann. Origin wird zurückgespiegelt (LAN-Plugin,
/// kein öffentlicher Service).
/// </summary>
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);
+47 -1
View File
@@ -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<PluginConfiguration>, IServerEntryPoint
public class Plugin : BasePlugin<PluginConfiguration>, 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();
}
/// <summary>
/// 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.
/// </summary>
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();
}
/// <summary>
/// Registriert die Dashboard-Config-Seite (HTML + JS als Embedded Resources).
/// </summary>
public IEnumerable<PluginPageInfo> 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();
+4
View File
@@ -11,4 +11,8 @@
<ItemGroup>
<PackageReference Include="MediaBrowser.Server.Core" Version="4.9.1.90" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Configuration/configPage.html" />
<EmbeddedResource Include="Configuration/configPage.js" />
</ItemGroup>
</Project>