155 lines
5.4 KiB
C#
155 lines
5.4 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// Eigenständiger HTTP-Listener (Muster: WatchParty ExternalWebServer), der das
|
|
/// MCP-Protokoll (JSON-RPC 2.0) auf /mcp bedient. Läuft neben dem Emby-Port.
|
|
/// </summary>
|
|
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();
|
|
}
|
|
}
|
|
}
|