feat(pdu): add PDU MCP server for AI-driven SNMP power control
New ETTerms.PduMcp stdio MCP server lets AI agents (Kiro/Claude CLI) control SNMP PDU outlets directly. Unlike serial, SNMP is non-exclusive so it talks to the PDU directly without bridging through the GUI. Tools: pdu_connect / pdu_list / pdu_set_port / pdu_get_port / pdu_status / pdu_power_cycle / pdu_disconnect. - McpRegistrar now registers both etterms-serial and etterms-pdu in one click - Settings -> AI MCP shows both server paths - publish target (PublishMcpServers) bundles both MCP servers - bump version to 0.3.0, update About changelog, ARCHITECTURE.md, CLAUDE.md
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>ETTerms.PduMcp</RootNamespace>
|
||||
<AssemblyName>ETTerms.PduMcp</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
|
||||
<PackageReference Include="SnmpSharpNet" Version="0.9.7">
|
||||
<NoWarn>NU1701</NoWarn>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.Net;
|
||||
using SnmpSharpNet;
|
||||
|
||||
namespace ETTerms.PduMcp;
|
||||
|
||||
/// <summary>
|
||||
/// PDU controller for iPoMan II/III models via SNMP (slim copy of the GUI's
|
||||
/// ETTerms.Scripting.Pdu.PduController, ported into the standalone MCP server).
|
||||
///
|
||||
/// Differences from the GUI version:
|
||||
/// • No dependency on ETTerms.Infrastructure.AppLogger — diagnostics go to stderr
|
||||
/// (stdout is reserved for the MCP JSON-RPC stream).
|
||||
/// • Adds <see cref="GetModelName"/> so tools can surface the device identity.
|
||||
///
|
||||
/// SNMP is connectionless (UDP) and non-exclusive, so this talks to the PDU directly
|
||||
/// without bridging through the GUI.
|
||||
/// </summary>
|
||||
public sealed class PduController : IDisposable
|
||||
{
|
||||
private readonly string _ip;
|
||||
private const string Community = "private";
|
||||
private const int SnmpPort = 161;
|
||||
private const int Timeout = 3000;
|
||||
|
||||
public string Ip => _ip;
|
||||
|
||||
public PduController(string ip) => _ip = ip;
|
||||
|
||||
/// <summary>Reads the PDU model/name OID; non-empty containing "PDU" means reachable.</summary>
|
||||
public string? GetModelName() => SnmpGet(".1.3.6.1.4.1.2468.1.4.2.1.1.4");
|
||||
|
||||
public bool CheckConnection()
|
||||
{
|
||||
var name = GetModelName();
|
||||
Log($"CheckConnection {_ip}: name='{name ?? "<null>"}'");
|
||||
return !string.IsNullOrEmpty(name) && name.Contains("PDU");
|
||||
}
|
||||
|
||||
public bool SetPortOn(int port) => SnmpSet(PortControlOid(port), new Integer32(3));
|
||||
public bool SetPortOff(int port) => SnmpSet(PortControlOid(port), new Integer32(4));
|
||||
|
||||
/// <summary>true = on, false = off, null = unknown/unreachable.</summary>
|
||||
public bool? GetPortState(int port)
|
||||
{
|
||||
var r = SnmpGet(PortStateOid(port));
|
||||
return r == "3" ? true : (r == "2" || r == "4") ? false : null;
|
||||
}
|
||||
|
||||
public int? GetPortCurrent(int port) => int.TryParse(SnmpGet(PortCurrentOid(port)), out int v) ? v : null;
|
||||
public double? GetPortPowerWatts(int port) => int.TryParse(SnmpGet(PortPowerOid(port)), out int v) ? v / 10.0 : null;
|
||||
|
||||
private static string PortControlOid(int port) => $".1.3.6.1.4.1.2468.1.4.2.1.3.2.4.1.2.{port}";
|
||||
private static string PortStateOid(int port) => $".1.3.6.1.4.1.2468.1.4.2.1.3.2.3.1.2.{port}";
|
||||
private static string PortCurrentOid(int port) => $".1.3.6.1.4.1.2468.1.4.2.1.3.2.3.1.3.{port}";
|
||||
private static string PortPowerOid(int port) => $".1.3.6.1.4.1.2468.1.4.2.1.3.2.3.1.5.{port}";
|
||||
|
||||
private bool SnmpSet(string oid, AsnType value)
|
||||
{
|
||||
try
|
||||
{
|
||||
var param = new AgentParameters(new OctetString(Community)) { Version = SnmpVersion.Ver1 };
|
||||
using var target = new UdpTarget((IPAddress)new IpAddress(_ip), SnmpPort, Timeout, 1);
|
||||
var pdu = new SnmpSharpNet.Pdu(PduType.Set);
|
||||
pdu.VbList.Add(new Oid(oid), value);
|
||||
var result = (SnmpV1Packet)target.Request(pdu, param);
|
||||
return result?.Pdu.ErrorStatus == 0;
|
||||
}
|
||||
catch (Exception ex) { Log($"SNMP SET {oid} exception: {ex.Message}"); return false; }
|
||||
}
|
||||
|
||||
private string? SnmpGet(string oid)
|
||||
{
|
||||
try
|
||||
{
|
||||
var param = new AgentParameters(new OctetString(Community)) { Version = SnmpVersion.Ver1 };
|
||||
using var target = new UdpTarget((IPAddress)new IpAddress(_ip), SnmpPort, Timeout, 1);
|
||||
var pdu = new SnmpSharpNet.Pdu(PduType.Get);
|
||||
pdu.VbList.Add(new Oid(oid));
|
||||
var result = (SnmpV1Packet)target.Request(pdu, param);
|
||||
if (result == null) { Log($"SNMP GET {oid}: no response (timeout)"); return null; }
|
||||
if (result.Pdu.ErrorStatus != 0) { Log($"SNMP GET {oid}: ErrorStatus={result.Pdu.ErrorStatus}"); return null; }
|
||||
foreach (var v in result.Pdu.VbList) return v.Value.ToString();
|
||||
}
|
||||
catch (Exception ex) { Log($"SNMP GET {oid} exception: {ex.Message}"); }
|
||||
return null;
|
||||
}
|
||||
|
||||
// stdio MCP server:stdout 專供 JSON-RPC,診斷一律走 stderr。
|
||||
private static void Log(string msg) => Console.Error.WriteLine($"[PDU] {msg}");
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace ETTerms.PduMcp;
|
||||
|
||||
/// <summary>
|
||||
/// Process-wide registry of connected PDUs, keyed by IP. The MCP server is long-lived,
|
||||
/// so connections established by <c>pdu_connect</c> persist across tool calls.
|
||||
/// </summary>
|
||||
public sealed class PduRegistry
|
||||
{
|
||||
public static readonly PduRegistry Instance = new();
|
||||
|
||||
/// <summary>iPoMan II/III outlet count.</summary>
|
||||
public const int PortCount = 12;
|
||||
|
||||
private readonly ConcurrentDictionary<string, PduController> _pdus = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public PduController GetOrAdd(string ip) =>
|
||||
_pdus.GetOrAdd(ip.Trim(), static k => new PduController(k));
|
||||
|
||||
public bool TryGet(string ip, out PduController pdu) =>
|
||||
_pdus.TryGetValue(ip.Trim(), out pdu!);
|
||||
|
||||
public bool Remove(string ip)
|
||||
{
|
||||
if (_pdus.TryRemove(ip.Trim(), out var pdu)) { pdu.Dispose(); return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
public IReadOnlyCollection<string> ConnectedIps => _pdus.Keys.ToArray();
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using ModelContextProtocol.Server;
|
||||
|
||||
namespace ETTerms.PduMcp;
|
||||
|
||||
/// <summary>
|
||||
/// MCP tools exposed to the AI for controlling an SNMP PDU (iPoMan II/III).
|
||||
///
|
||||
/// Unlike the serial bridge, the PDU is reached directly over SNMP — the ETTerms GUI
|
||||
/// does NOT need to be running. Connections are held per-IP and persist for the lifetime
|
||||
/// of this MCP server. Always <c>pdu_connect</c> an IP first, then control its ports.
|
||||
/// </summary>
|
||||
[McpServerToolType]
|
||||
public static class PduTools
|
||||
{
|
||||
private static readonly JsonSerializerOptions Json = new() { WriteIndented = false };
|
||||
|
||||
[McpServerTool, Description("Connect to a PDU over SNMP by IP and verify it responds. Required before controlling ports. Returns the model name on success.")]
|
||||
public static Task<string> pdu_connect(
|
||||
[Description("PDU IP address, e.g. 192.168.1.21")] string ip)
|
||||
{
|
||||
ip = (ip ?? "").Trim();
|
||||
if (ip.Length == 0) return Err("ip is required");
|
||||
var pdu = PduRegistry.Instance.GetOrAdd(ip);
|
||||
var model = pdu.GetModelName();
|
||||
bool ok = !string.IsNullOrEmpty(model) && model.Contains("PDU");
|
||||
if (!ok)
|
||||
{
|
||||
PduRegistry.Instance.Remove(ip);
|
||||
return Err($"no SNMP response from PDU at {ip} (check IP/network/community)");
|
||||
}
|
||||
return Ok(new { ip, model });
|
||||
}
|
||||
|
||||
[McpServerTool, Description("List PDUs currently connected in this MCP session (by IP).")]
|
||||
public static Task<string> pdu_list()
|
||||
=> Ok(new { connected = PduRegistry.Instance.ConnectedIps });
|
||||
|
||||
[McpServerTool, Description("Turn a PDU outlet on or off. The PDU must be connected first via pdu_connect.")]
|
||||
public static Task<string> pdu_set_port(
|
||||
[Description("PDU IP address")] string ip,
|
||||
[Description("Outlet/port number (1-12)")] int port,
|
||||
[Description("true = ON, false = OFF")] bool on)
|
||||
{
|
||||
if (!TryResolve(ip, port, out var pdu, out var error)) return Err(error);
|
||||
bool ok = on ? pdu.SetPortOn(port) : pdu.SetPortOff(port);
|
||||
if (!ok) return Err($"SNMP set failed for {ip} port {port}");
|
||||
return Ok(new { ip, port, state = on ? "on" : "off" });
|
||||
}
|
||||
|
||||
[McpServerTool, Description("Read a single outlet's state, current (mA) and power (W).")]
|
||||
public static Task<string> pdu_get_port(
|
||||
[Description("PDU IP address")] string ip,
|
||||
[Description("Outlet/port number (1-12)")] int port)
|
||||
{
|
||||
if (!TryResolve(ip, port, out var pdu, out var error)) return Err(error);
|
||||
return Ok(PortSnapshot(pdu, port));
|
||||
}
|
||||
|
||||
[McpServerTool, Description("Read the state, current (mA) and power (W) of all outlets on the PDU.")]
|
||||
public static Task<string> pdu_status(
|
||||
[Description("PDU IP address")] string ip)
|
||||
{
|
||||
if (!PduRegistry.Instance.TryGet(ip, out var pdu))
|
||||
return Err($"PDU {ip} not connected. Call pdu_connect first.");
|
||||
var ports = new List<object>();
|
||||
for (int p = 1; p <= PduRegistry.PortCount; p++)
|
||||
ports.Add(PortSnapshot(pdu, p));
|
||||
return Ok(new { ip, ports });
|
||||
}
|
||||
|
||||
[McpServerTool, Description("Power-cycle an outlet: turn it OFF, wait offSeconds, then turn it ON. Useful for rebooting a DUT.")]
|
||||
public static async Task<string> pdu_power_cycle(
|
||||
[Description("PDU IP address")] string ip,
|
||||
[Description("Outlet/port number (1-12)")] int port,
|
||||
[Description("Seconds to stay off before powering back on")] int offSeconds = 5)
|
||||
{
|
||||
if (!TryResolve(ip, port, out var pdu, out var error)) return await Err(error);
|
||||
if (offSeconds < 0) offSeconds = 0;
|
||||
if (!pdu.SetPortOff(port)) return await Err($"SNMP off failed for {ip} port {port}");
|
||||
await Task.Delay(offSeconds * 1000);
|
||||
if (!pdu.SetPortOn(port)) return await Err($"SNMP on failed for {ip} port {port}");
|
||||
return await Ok(new { ip, port, action = "power_cycle", offSeconds, state = "on" });
|
||||
}
|
||||
|
||||
[McpServerTool, Description("Disconnect a PDU from this MCP session (does not change outlet states).")]
|
||||
public static Task<string> pdu_disconnect(
|
||||
[Description("PDU IP address")] string ip)
|
||||
=> Ok(new { ip, removed = PduRegistry.Instance.Remove(ip) });
|
||||
|
||||
// ── helpers ──
|
||||
|
||||
private static bool TryResolve(string ip, int port, out PduController pdu, out string error)
|
||||
{
|
||||
pdu = null!;
|
||||
error = "";
|
||||
if (port < 1 || port > PduRegistry.PortCount)
|
||||
{
|
||||
error = $"port must be 1-{PduRegistry.PortCount}";
|
||||
return false;
|
||||
}
|
||||
if (!PduRegistry.Instance.TryGet(ip, out pdu))
|
||||
{
|
||||
error = $"PDU {ip} not connected. Call pdu_connect first.";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static object PortSnapshot(PduController pdu, int port)
|
||||
{
|
||||
var state = pdu.GetPortState(port);
|
||||
return new
|
||||
{
|
||||
port,
|
||||
state = state == true ? "on" : state == false ? "off" : "unknown",
|
||||
currentMilliAmps = pdu.GetPortCurrent(port),
|
||||
powerWatts = pdu.GetPortPowerWatts(port)
|
||||
};
|
||||
}
|
||||
|
||||
private static Task<string> Ok(object payload)
|
||||
{
|
||||
var node = new { ok = true, result = payload };
|
||||
return Task.FromResult(JsonSerializer.Serialize(node, Json));
|
||||
}
|
||||
|
||||
private static Task<string> Err(string message)
|
||||
=> Task.FromResult(JsonSerializer.Serialize(new { ok = false, error = message }, Json));
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
// stdio MCP server:把 SNMP PDU 控制暴露給 AI(Kiro / Claude CLI)。
|
||||
// 與 ETTerms.SerialMcp 不同,PDU 走 SNMP(UDP) 非獨佔,故直接打 SNMP,不需 GUI 在跑。
|
||||
var builder = Host.CreateApplicationBuilder(args);
|
||||
|
||||
// stdio 傳輸:stdout 專供 JSON-RPC,log 一律走 stderr,否則會污染協議。
|
||||
builder.Logging.AddConsole(o => o.LogToStandardErrorThreshold = LogLevel.Trace);
|
||||
|
||||
builder.Services
|
||||
.AddMcpServer()
|
||||
.WithStdioServerTransport()
|
||||
.WithToolsFromAssembly();
|
||||
|
||||
await builder.Build().RunAsync();
|
||||
Reference in New Issue
Block a user