merge: PDU MCP server (v0.3.0)

This commit is contained in:
2026-06-08 10:12:24 +08:00
12 changed files with 434 additions and 60 deletions
+49 -10
View File
@@ -32,7 +32,7 @@ ETTerms 是一個給工程師 / 韌體 / 硬體驗證人員用的**單一視窗
| 祕密儲存 | **Windows Credential Manager**DPAPI / CredMan | 連線密碼、SSH key passphrase,不落地明碼 | | 祕密儲存 | **Windows Credential Manager**DPAPI / CredMan | 連線密碼、SSH key passphrase,不落地明碼 |
| PDU 控制(選用) | **SnmpSharpNet** | 沿用 MyTeraTerm PDU 控制(`pductrl` / `pduconnect` | | PDU 控制(選用) | **SnmpSharpNet** | 沿用 MyTeraTerm PDU 控制(`pductrl` / `pduconnect` |
| 日誌 | 自製 **AppLogger**(從 MyTeraTerm 移植) | 檔案 + Debug 雙輸出 | | 日誌 | 自製 **AppLogger**(從 MyTeraTerm 移植) | 檔案 + Debug 雙輸出 |
| AI / MCP 整合(選用) | **stdio MCP server**(官方 C# SDK `ModelContextProtocol` | 獨立行程,但不自己開 port——經本機 named pipe 橋接 GUI 持有的 serial session,把收發暴露成 AI 可呼叫工具(Kiro CLI / Claude CLI),見 [AI / MCP Integration](#ai--mcp-integrationserial-mcp-server) | | AI / MCP 整合(選用) | **stdio MCP server**(官方 C# SDK `ModelContextProtocol` | 兩個獨立 server`ETTerms.SerialMcp`不自己開 port經本機 named pipe 橋接 GUI 持有的 serial session)與 `ETTerms.PduMcp`(直接打 SNMP 控制 PDU 插座,不需 GUI);把收發 / 電源控制暴露成 AI 可呼叫工具(Kiro CLI / Claude CLI),見 [AI / MCP Integration](#ai--mcp-integrationserial-mcp--pdu-mcp-server) |
| 打包 | `dotnet publish` + (選用)Inno Setup / MSIX | 單機安裝,current-user | | 打包 | `dotnet publish` + (選用)Inno Setup / MSIX | 單機安裝,current-user |
> **與舊版 MyTeraTerm 的關鍵差異:** 舊版是把真正的 `ttermpro.exe`TeraTerm)嵌進 Panel,靠 **com0com 虛擬 COM 對**攔截 serial 來跑腳本。ETTerms 改走**全原生**SSH.NET 做 SSH、`System.IO.Ports` 做 serial、自繪 VT100 控制項做終端機畫面,**不再依賴外部 TeraTerm exe,也不再需要 com0com**。腳本引擎從「驅動 com0com bridge」改成「驅動原生 `ISessionChannel`」。 > **與舊版 MyTeraTerm 的關鍵差異:** 舊版是把真正的 `ttermpro.exe`TeraTerm)嵌進 Panel,靠 **com0com 虛擬 COM 對**攔截 serial 來跑腳本。ETTerms 改走**全原生**SSH.NET 做 SSH、`System.IO.Ports` 做 serial、自繪 VT100 控制項做終端機畫面,**不再依賴外部 TeraTerm exe,也不再需要 com0com**。腳本引擎從「驅動 com0com bridge」改成「驅動原生 `ISessionChannel`」。
@@ -356,7 +356,16 @@ ScriptRunner.RunAsync(scriptText, activeChannel)
--- ---
## AI / MCP IntegrationSerial MCP Server ## AI / MCP IntegrationSerial MCP + PDU MCP Server
ETTerms 提供**兩個獨立的 stdio MCP server**給 AI agentKiro CLI / Claude CLI):
- **`ETTerms.SerialMcp`** — 收發 serial。COM port 獨佔,故由 GUI 唯一持有、MCP 經本機 named pipe 橋接(見下方)。
- **`ETTerms.PduMcp`** — 控制 SNMP PDU 電源插座。SNMP(UDP) 非獨佔,故 MCP **直接打 SNMP**,不需 GUI 在跑、也不經 pipe。
兩者都能用 GUI **Settings → AI MCP** 一鍵 Setup`McpRegistrar` 會同時註冊 `etterms-serial``etterms-pdu`)。
### Serial MCP Server
> 讓 **Kiro CLI / Claude CLI** 等 AI agent 收發 serial**且使用者能在 ETTerms GUI 即時看到 AI 的每筆收發**。 > 讓 **Kiro CLI / Claude CLI** 等 AI agent 收發 serial**且使用者能在 ETTerms GUI 即時看到 AI 的每筆收發**。
> >
@@ -425,6 +434,33 @@ kiro-cli mcp add --name serial --command dotnet `
或寫進 agent.json 的 `mcpServers`Claude CLI 則用其對應的 `mcpServers` 設定。**使用前提:先在 ETTerms GUI 開好要操作的 serial 連線**,AI 才能 `serial_attach` 上去。註冊後即可對 AI 說「列出目前 serial session → 接上 COM3 → 送指令看回應」。 或寫進 agent.json 的 `mcpServers`Claude CLI 則用其對應的 `mcpServers` 設定。**使用前提:先在 ETTerms GUI 開好要操作的 serial 連線**,AI 才能 `serial_attach` 上去。註冊後即可對 AI 說「列出目前 serial session → 接上 COM3 → 送指令看回應」。
### PDU MCP Serverv0.3.0
> 讓 AI agent 直接控制 SNMP PDU 的電源插座,**典型用途:測試中自動 power-cycle DUT**。
**關鍵設計:直接打 SNMP,不經 GUI 橋接。** 與 serial 不同,PDU 走 SNMPUDP)**非獨佔**——多個行程可同時對同一台 PDU 下命令。因此 `ETTerms.PduMcp` 不需要像 serial 那樣繞 GUI 的 named pipe,而是內含一份精簡版 `PduController`OID 邏輯複製自 GUI 的 `Scripting/Pdu/PduController`,診斷改走 stderr 以免污染 stdio JSON-RPC)直接與 PDU 對話。**好處:GUI 不必開著,AI 也能控制 PDU;最少程式碼、最穩。**
```
Kiro/Claude CLI ── 啟動子行程 ETTerms.PduMcpstdio / JSON-RPC
└─ SnmpSharpNet ──(SNMP/UDP 161)──► PDUiPoMan II/III
```
連線狀態(device IP → controller)以行程內單例 `PduRegistry` 保存,跨工具呼叫保留,直到 `pdu_disconnect` 或行程結束。
**暴露的工具:**
| 工具 | 參數 | 說明 |
|------|------|------|
| `pdu_connect` | ip | 以 SNMP 連線並驗證 PDU 回應,成功回傳 model name;控制前必須先呼叫 |
| `pdu_list` | — | 列出本 session 已連線的 PDU(依 IP |
| `pdu_set_port` | ip, port, on | 將某插座開(on=true)/關(off=false) |
| `pdu_get_port` | ip, port | 讀單一插座的狀態 / 電流(mA) / 功率(W) |
| `pdu_status` | ip | 讀全部 12 個插座的狀態 / 電流 / 功率 |
| `pdu_power_cycle` | ip, port, offSeconds? | 關 → 等 offSeconds → 開(重啟 DUT |
| `pdu_disconnect` | ip | 解除本 session 的 PDU 連線(不改變插座狀態) |
> 所有工具回傳統一的 `{ "ok": bool, "result"/"error": ... }` JSON。SNMP community 目前沿用 GUI 版的 `"private"`。
--- ---
## Key Constraints & Business Rules ## Key Constraints & Business Rules
@@ -504,17 +540,20 @@ dotnet publish src\ETTerms\ETTerms.csproj -c Release -r win-x64 --self-contained
**內容結構:** **內容結構:**
``` ```
ETTerms_v0.2.0\ ETTerms_v0.3.0\
├── ETTerms v0.2.0.exe # 主程式 apphost,改名為「ETTerms v{Version}.exe」 ├── ETTerms v0.3.0.exe # 主程式 apphost,改名為「ETTerms v{Version}.exe」
├── ETTerms.dll + 各相依 dll # SSH.NET / SQLite / SnmpSharpNet / System.IO.Ports … ├── ETTerms.dll + 各相依 dll # SSH.NET / SQLite / SnmpSharpNet / System.IO.Ports …
── ETTerms.SerialMcp\ # Serial MCP server,獨立發佈到子資料夾(相依 dll 與 GUI 隔離) ── ETTerms.SerialMcp\ # Serial MCP server,獨立發佈到子資料夾(相依 dll 與 GUI 隔離)
├── ETTerms.SerialMcp.exe ├── ETTerms.SerialMcp.exe
└── ETTerms.SerialMcp.dll + 相依 └── ETTerms.SerialMcp.dll + 相依
└── ETTerms.PduMcp\ # PDU MCP serverv0.3.0),同樣獨立發佈到子資料夾
├── ETTerms.PduMcp.exe
└── ETTerms.PduMcp.dll + 相依(含 SnmpSharpNet
``` ```
**規則:** **規則:**
1. **GUI publish 會自動帶上 MCP**`ETTerms.csproj``PublishSerialMcp` target`AfterTargets="Publish"`),會把 `ETTerms.SerialMcp` 一併發佈到 `<publish>\ETTerms.SerialMcp\` **子資料夾**(與 GUI 相依 dll 隔離)。因此**只要發佈 GUI 一個指令**即可,不必再單獨發 MCP。 1. **GUI publish 會自動帶上兩個 MCP server**`ETTerms.csproj``PublishMcpServers` target`AfterTargets="Publish"`),會把 `ETTerms.SerialMcp``ETTerms.PduMcp` 一併發佈到各自的 `<publish>\<server>\` **子資料夾**(與 GUI 相依 dll 隔離)。因此**只要發佈 GUI 一個指令**即可,不必再單獨發 MCP。
- 對齊 `McpRegistrar.ResolveServerExe()`:它解析的 `<ETTerms.exe>\ETTerms.SerialMcp\ETTerms.SerialMcp.exe` 因此**必定存在**,AI MCP 一鍵設定寫進去的路徑才不會落空。 - 對齊 `McpRegistrar.ResolveServerExe()`:它解析的 `<ETTerms.exe>\<server>\<server>.exe` 因此**必定存在**,AI MCP 一鍵設定寫進去的路徑才不會落空。
- MCP 子發佈會**跟隨 GUI 的 `SelfContained` 設定**target 內以 `$(SelfContained)` 傳入):框架相依版的 MCP 也框架相依;portable 版的 MCP 也免 runtime。 - MCP 子發佈會**跟隨 GUI 的 `SelfContained` 設定**target 內以 `$(SelfContained)` 傳入):框架相依版的 MCP 也框架相依;portable 版的 MCP 也免 runtime。
2. **主 exe 改名**`dotnet publish` 產生的 `ETTerms.exe` 重新命名為 **`ETTerms v{Version}.exe`**。 2. **主 exe 改名**`dotnet publish` 產生的 `ETTerms.exe` 重新命名為 **`ETTerms v{Version}.exe`**。
- 可安全改名:.NET apphost 內部記錄要載入的 `ETTerms.dll`,**不靠自身檔名**,改名後仍正常啟動。 - 可安全改名:.NET apphost 內部記錄要載入的 `ETTerms.dll`,**不靠自身檔名**,改名後仍正常啟動。
@@ -545,7 +584,7 @@ dotnet publish src\ETTerms\ETTerms.csproj -c Release -r win-x64 --self-contained
Rename-Item (Join-Path $proot "ETTerms.exe") "ETTerms v$ver.exe" Rename-Item (Join-Path $proot "ETTerms.exe") "ETTerms v$ver.exe"
``` ```
> 兩版的 `ETTerms.SerialMcp\` 子資料夾都由 `PublishSerialMcp` target 自動產生;portable 版的 MCP 也是 self-contained,故 AI MCP 功能在無 runtime 環境同樣可用。 > 兩版的 `ETTerms.SerialMcp\` 與 `ETTerms.PduMcp\` 子資料夾都由 `PublishMcpServers` target 自動產生;portable 版的 MCP 也是 self-contained,故 AI MCP 功能在無 runtime 環境同樣可用。
--- ---
+8 -5
View File
@@ -10,7 +10,9 @@ ETTerms 是一個 **C# .NET 8 WinForms** 的原生 Windows 終端機工作台,
**進度:** Phase 15 ✅、Phase 6 ✅(TTL 引擎 + Group 同步,SSH 待驗收)、Phase 7 ✅(Settings/About)、Phase 8 ✅(PDU + Shell/ConPTY + SFTP + Settings 擴充)、Phase 9 ✅(Serial MCP server**GUI 持有 COM portMCP 經本機 named pipe 橋接**,AI 收發的資料即時以 `[AI]` 標色顯示在 GUI)。打包待指示。 **進度:** Phase 15 ✅、Phase 6 ✅(TTL 引擎 + Group 同步,SSH 待驗收)、Phase 7 ✅(Settings/About)、Phase 8 ✅(PDU + Shell/ConPTY + SFTP + Settings 擴充)、Phase 9 ✅(Serial MCP server**GUI 持有 COM portMCP 經本機 named pipe 橋接**,AI 收發的資料即時以 `[AI]` 標色顯示在 GUI)。打包待指示。
**v0.2.1** 新增 GUI **Settings → AI MCP** 分頁(`McpRegistrar`):對 Claude Code`~/.claude.json`)與 Kiro`~/.kiro/settings/mcp.json`**一鍵 Setup / Remove** 註冊 `etterms-serial` MCP serverread-modify-write 保留檔內其他設定、原子寫回;卡片附 CLI 驗證指令。`ETTerms.csproj` `PublishSerialMcp` target`AfterTargets=Publish`GUI publish 會自動`ETTerms.SerialMcp` 帶到 `\ETTerms.SerialMcp\` 子資料夾,與 `McpRegistrar.ResolveServerExe()` 解析路徑對齊 **v0.3.0** 新增 **`ETTerms.PduMcp`**stdio MCP server):讓 AI agent 直接控制 SNMP PDU 插座。與 serial 不同,PDU 走 SNMP(UDP) **非獨佔**,故 PduMcp **直接打 SNMP、不經 GUI 橋接**(內含精簡版 `PduController`OID 邏輯複製自 GUI 版,log 走 stderr),GUI 不開著也能用。工具:`pdu_connect` / `pdu_list` / `pdu_set_port` / `pdu_get_port` / `pdu_status` / `pdu_power_cycle` / `pdu_disconnect`,回傳統一 `{ok, result/error}` JSON;連線狀態以行程內單例 `PduRegistry`IP→controller)保存。`McpRegistrar` 改為多 server**Settings → AI MCP 一鍵同時註冊 `etterms-serial``etterms-pdu`**`ETTerms.csproj` 的 publish target 更名 `PublishMcpServers`GUI publish 會把兩個 MCP 各自帶到 `\ETTerms.SerialMcp\``\ETTerms.PduMcp\` 子資料夾。
**v0.2.1** 新增 GUI **Settings → AI MCP** 分頁(`McpRegistrar`):對 Claude Code`~/.claude.json`)與 Kiro`~/.kiro/settings/mcp.json`**一鍵 Setup / Remove** 註冊 `etterms-serial` MCP serverread-modify-write 保留檔內其他設定、原子寫回;卡片附 CLI 驗證指令。`ETTerms.csproj` 加 publish target`AfterTargets=Publish`),GUI publish 會自動把 MCP server 帶到子資料夾,與 `McpRegistrar.ResolveServerExe()` 解析路徑對齊。
**v0.2.0** Phase 9 完成 — `ETTerms.SerialMcp`stdio MCP server+ GUI `SerialBridgeServer`named pipe `\\.\pipe\etterms-serial`)上線,提供 `serial_list` / `serial_attach` / `serial_write` / `serial_read` / `serial_detach` 五個工具,AI 的 TX 在 GUI 以 `[AI]` 標色即時 echo;視窗 / 工作列 / About 改用 Choco 圖示,標題列顯示版本號。見 [docs/serial-mcp-guide.md](docs/serial-mcp-guide.md)。 **v0.2.0** Phase 9 完成 — `ETTerms.SerialMcp`stdio MCP server+ GUI `SerialBridgeServer`named pipe `\\.\pipe\etterms-serial`)上線,提供 `serial_list` / `serial_attach` / `serial_write` / `serial_read` / `serial_detach` 五個工具,AI 的 TX 在 GUI 以 `[AI]` 標色即時 echo;視窗 / 工作列 / About 改用 Choco 圖示,標題列顯示版本號。見 [docs/serial-mcp-guide.md](docs/serial-mcp-guide.md)。
@@ -27,7 +29,7 @@ ETTerms 是一個 **C# .NET 8 WinForms** 的原生 Windows 終端機工作台,
- **連線儲存:** SQLite`Microsoft.Data.Sqlite` - **連線儲存:** SQLite`Microsoft.Data.Sqlite`
- **密碼儲存:** Windows Credential Manager(不落地明碼) - **密碼儲存:** Windows Credential Manager(不落地明碼)
- **PDU** SnmpSharpNetiPoMan II/III via SNMP - **PDU** SnmpSharpNetiPoMan II/III via SNMP
- **AI / MCP(選用):** stdio MCP server`ETTerms.SerialMcp`官方 C# SDK `ModelContextProtocol`)。**不自己開 COM port**而是經本機 named pipe 接上 GUI 持有的 serial session把 serial 收發暴露給 Kiro CLI / Claude CLIAI 的 TX/RX 同步顯示在 GUI - **AI / MCP(選用):** 兩個 stdio MCP server(官方 C# SDK `ModelContextProtocol`)。`ETTerms.SerialMcp`**不自己開 COM port**,經本機 named pipe 接上 GUI 持有的 serial sessionAI 的 TX/RX 同步顯示在 GUI。`ETTerms.PduMcp`v0.3.0):**直接打 SNMP** 控制 PDU 插座,非獨佔故不需 GUI 在跑。皆暴露給 Kiro CLI / Claude CLI
- **設定持久化:** JSON → `%LocalAppData%\ETTerms\settings.json` - **設定持久化:** JSON → `%LocalAppData%\ETTerms\settings.json`
## 常用指令 ## 常用指令
@@ -41,8 +43,8 @@ dotnet run --project src\ETTerms\ETTerms.csproj
dotnet add src\ETTerms package SSH.NET dotnet add src\ETTerms package SSH.NET
# 打包(見「Publish / 打包慣例」)—— 兩種版本都產出,輸出到 src\ETTerms\Publish\ # 打包(見「Publish / 打包慣例」)—— 兩種版本都產出,輸出到 src\ETTerms\Publish\
# GUI publish 會「自動」把 ETTerms.SerialMcp 一併發到 \ETTerms.SerialMcp\ 子資料夾 # GUI publish 會「自動」把 ETTerms.SerialMcp ETTerms.PduMcp 一併發到各自的子資料夾
# ETTerms.csproj 的 PublishSerialMcp targetAfterTargets=Publish),且 MCP 跟隨 GUI 的 self-contained 設定。 # ETTerms.csproj 的 PublishMcpServers targetAfterTargets=Publish),且 MCP 跟隨 GUI 的 self-contained 設定。
$ver = ([regex]::Match((Get-Content src\ETTerms\ETTerms.csproj -Raw), '<Version>([^<]+)</Version>')).Groups[1].Value $ver = ([regex]::Match((Get-Content src\ETTerms\ETTerms.csproj -Raw), '<Version>([^<]+)</Version>')).Groups[1].Value
# A. 框架相依版(需目標機已裝 .NET 8 Desktop Runtime)→ ETTerms_v{Version}\ # A. 框架相依版(需目標機已裝 .NET 8 Desktop Runtime)→ ETTerms_v{Version}\
@@ -64,7 +66,7 @@ kiro-cli mcp add --name serial --command dotnet --args "run --project src\ETTerm
## 開發慣例 ## 開發慣例
- **命名:** PascalCase 類別 / 方法,`_camelCase` 私有欄位;檔名 = 類別名。 - **命名:** PascalCase 類別 / 方法,`_camelCase` 私有欄位;檔名 = 類別名。
- **Publish / 打包:** 輸出到 `src\ETTerms\Publish\`;主 exe 改名為 `ETTerms v{Version}.exe``ETTerms.SerialMcp` 一併發到其下 `ETTerms.SerialMcp\` 子資料夾(且跟隨 GUI 的 self-contained 設定)。**兩種版本都產出**:框架相依 `ETTerms_v{Version}\``--self-contained false`,需裝 .NET 8 Desktop Runtime)+ portable 免安裝 `ETTerms_v{Version}_portable\``--self-contained true`runtime 內含)。不要開 trimmingWinForms 反射)。詳見 [ARCHITECTURE.md](ARCHITECTURE.md#publish--打包慣例)。 - **Publish / 打包:** 輸出到 `src\ETTerms\Publish\`;主 exe 改名為 `ETTerms v{Version}.exe``ETTerms.SerialMcp``ETTerms.PduMcp` 一併發到其下 `ETTerms.SerialMcp\``ETTerms.PduMcp\` 子資料夾(且跟隨 GUI 的 self-contained 設定)。**兩種版本都產出**:框架相依 `ETTerms_v{Version}\``--self-contained false`,需裝 .NET 8 Desktop Runtime)+ portable 免安裝 `ETTerms_v{Version}_portable\``--self-contained true`runtime 內含)。不要開 trimmingWinForms 反射)。詳見 [ARCHITECTURE.md](ARCHITECTURE.md#publish--打包慣例)。
- **分層:** UI`App/`)只認 `ISessionChannel` 抽象,不直接相依 SSH.NET / SerialPort。 - **分層:** UI`App/`)只認 `ISessionChannel` 抽象,不直接相依 SSH.NET / SerialPort。
- **執行緒:** channel I/O 在背景;所有 UI 更新一律 `Control.Invoke` 回 UI thread。 - **執行緒:** channel I/O 在背景;所有 UI 更新一律 `Control.Invoke` 回 UI thread。
- **commit** 走 Conventional Commits`feat:` / `fix:` / `refactor:` …)。 - **commit** 走 Conventional Commits`feat:` / `fix:` / `refactor:` …)。
@@ -85,5 +87,6 @@ kiro-cli mcp add --name serial --command dotnet --args "run --project src\ETTerm
- **`src/ETTerms/`** — 主應用程式(WinForms 視窗外殼 + 連線 / 終端機 / 腳本引擎)。 - **`src/ETTerms/`** — 主應用程式(WinForms 視窗外殼 + 連線 / 終端機 / 腳本引擎)。
- **`src/ETTerms.SerialMcp/`** — ✅ stdio MCP server(給 AI agent 收發 serial)。獨立行程,但**不直接開 COM port**:經本機 named pipe 連到 GUI 的 `SerialBridgeServer`,由 GUI 代為讀寫實體 portnet8.0 console + `ModelContextProtocol` SDK。 - **`src/ETTerms.SerialMcp/`** — ✅ stdio MCP server(給 AI agent 收發 serial)。獨立行程,但**不直接開 COM port**:經本機 named pipe 連到 GUI 的 `SerialBridgeServer`,由 GUI 代為讀寫實體 portnet8.0 console + `ModelContextProtocol` SDK。
- **`src/ETTerms.PduMcp/`** — ✅ stdio MCP server(給 AI agent 控制 SNMP PDUv0.3.0)。獨立行程,**直接打 SNMP**(內含精簡版 `PduController`),不經 GUI、GUI 不開著也能用;net8.0 console + `ModelContextProtocol` + `SnmpSharpNet`
- **`For_AI/`** — AI 協作素材與**參考專案**(`KKTerm-main` UI 參考、`MyTeraTerm` Script 參考)。整個資料夾 gitignored,僅供開發對照。 - **`For_AI/`** — AI 協作素材與**參考專案**(`KKTerm-main` UI 參考、`MyTeraTerm` Script 參考)。整個資料夾 gitignored,僅供開發對照。
- 本專案**無 `secret/` 資料夾**:沒有伺服端祕密 / DB 密碼 / compile-time secret,連線密碼一律走 Windows Credential Manager。 - 本專案**無 `secret/` 資料夾**:沒有伺服端祕密 / DB 密碼 / compile-time secret,連線密碼一律走 Windows Credential Manager。
+1
View File
@@ -2,5 +2,6 @@
<Folder Name="/src/"> <Folder Name="/src/">
<Project Path="src/ETTerms/ETTerms.csproj" /> <Project Path="src/ETTerms/ETTerms.csproj" />
<Project Path="src/ETTerms.SerialMcp/ETTerms.SerialMcp.csproj" /> <Project Path="src/ETTerms.SerialMcp/ETTerms.SerialMcp.csproj" />
<Project Path="src/ETTerms.PduMcp/ETTerms.PduMcp.csproj" />
</Folder> </Folder>
</Solution> </Solution>
+20
View File
@@ -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>
+92
View File
@@ -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 serverstdout 專供 JSON-RPC,診斷一律走 stderr。
private static void Log(string msg) => Console.Error.WriteLine($"[PDU] {msg}");
public void Dispose() { }
}
+31
View File
@@ -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();
}
+132
View File
@@ -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));
}
+17
View File
@@ -0,0 +1,17 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
// stdio MCP server:把 SNMP PDU 控制暴露給 AIKiro / Claude CLI)。
// 與 ETTerms.SerialMcp 不同,PDU 走 SNMP(UDP) 非獨佔,故直接打 SNMP,不需 GUI 在跑。
var builder = Host.CreateApplicationBuilder(args);
// stdio 傳輸:stdout 專供 JSON-RPClog 一律走 stderr,否則會污染協議。
builder.Logging.AddConsole(o => o.LogToStandardErrorThreshold = LogLevel.Trace);
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
+7
View File
@@ -183,6 +183,13 @@ public sealed class AboutView : UserControl
private static readonly ChangelogEntry[] Changelog = private static readonly ChangelogEntry[] Changelog =
[ [
new("0.3.0", new DateOnly(2026, 6, 8), "feat: PDU MCP server",
[
"New ETTerms.PduMcp server: AI agents (Kiro / Claude CLI) can now control SNMP PDU outlets directly.",
"Tools: pdu_connect / pdu_list / pdu_set_port / pdu_get_port / pdu_status / pdu_power_cycle / pdu_disconnect.",
"PDU runs over SNMP, so the AI can power-cycle a DUT without the GUI session being open.",
"Settings → AI MCP now registers both Serial and PDU MCP servers with one click.",
]),
new("0.2.2", new DateOnly(2026, 6, 5), "Bugfix — terminal stability", new("0.2.2", new DateOnly(2026, 6, 5), "Bugfix — terminal stability",
[ [
"Fixed: the terminal no longer freezes after minimizing or switching tabs (notably in PowerShell / Kiro).", "Fixed: the terminal no longer freezes after minimizing or switching tabs (notably in PowerShell / Kiro).",
+12 -10
View File
@@ -291,28 +291,30 @@ public sealed class SettingsView : UserControl
}); });
flow.Controls.Add(new Label flow.Controls.Add(new Label
{ {
Text = "One-click register the ETTerms Serial MCP server into your AI CLI's user-level\n" + Text = "One-click register the ETTerms MCP servers (Serial + PDU) into your AI CLI's\n" +
"config. ETTerms keeps sole ownership of the COM port; the AI drives serial through\n" + "user-level config. Serial: ETTerms owns the COM port, the AI drives it through a\n" +
"a local named pipe. Open a Serial session in ETTerms first, then the AI can attach.", "local named pipe (open a Serial session first). PDU: the AI controls outlets\n" +
AutoSize = false, Width = 600, Height = 56, "directly over SNMP — no GUI session required.",
AutoSize = false, Width = 600, Height = 64,
ForeColor = Theme.TextDim, Font = Theme.UiFont, Margin = new Padding(0, 0, 0, 8) ForeColor = Theme.TextDim, Font = Theme.UiFont, Margin = new Padding(0, 0, 0, 8)
}); });
// Resolved MCP server exe // Resolved MCP server exes (serial + pdu)
var exe = McpRegistrar.ResolveServerExe(); foreach (var (name, exe, exists) in McpRegistrar.ServerInfos())
var exists = McpRegistrar.ServerExeExists(); {
flow.Controls.Add(new Label flow.Controls.Add(new Label
{ {
Text = $"MCP server: {exe}", Text = $"{name}: {exe}",
AutoSize = false, Width = 600, Height = 20, AutoSize = false, Width = 600, Height = 20,
ForeColor = exists ? Theme.SerialColor : Color.FromArgb(210, 150, 120), ForeColor = exists ? Theme.SerialColor : Color.FromArgb(210, 150, 120),
Font = Theme.UiFont, Margin = new Padding(0, 0, 0, 2) Font = Theme.UiFont, Margin = new Padding(0, 0, 0, 2)
}); });
if (!exists) }
if (!McpRegistrar.ServerExeExists())
{ {
flow.Controls.Add(new Label flow.Controls.Add(new Label
{ {
Text = "⚠ Not found yet — publish the app (or build ETTerms.SerialMcp). Setup still writes this expected path.", Text = "⚠ Some servers not built yet — publish the app (or build the MCP projects). Setup still writes the expected paths.",
AutoSize = false, Width = 600, Height = 20, AutoSize = false, Width = 600, Height = 20,
ForeColor = Color.FromArgb(210, 150, 120), Font = Theme.UiFont, Margin = new Padding(0, 0, 0, 4) ForeColor = Color.FromArgb(210, 150, 120), Font = Theme.UiFont, Margin = new Padding(0, 0, 0, 4)
}); });
+6 -4
View File
@@ -10,7 +10,7 @@
<AssemblyName>ETTerms</AssemblyName> <AssemblyName>ETTerms</AssemblyName>
<!-- 版本資訊 --> <!-- 版本資訊 -->
<Version>0.2.2</Version> <Version>0.3.0</Version>
<Product>ETTerms</Product> <Product>ETTerms</Product>
<Company>ETTerms Project</Company> <Company>ETTerms Project</Company>
@@ -36,13 +36,13 @@
</ItemGroup> </ItemGroup>
<!-- <!--
發佈 GUI 時,自動把 Serial MCP server 一併發佈到 <publish>\ETTerms.SerialMcp\ 子資料夾。 發佈 GUI 時,自動把 MCP serversSerial + PDU一併發佈到 <publish>\<server>\ 子資料夾。
這樣單一 `dotnet publish src\ETTerms` 就會產生完整自洽的 bundle, 這樣單一 `dotnet publish src\ETTerms` 就會產生完整自洽的 bundle,
且 McpRegistrar.ResolveServerExe() 解析的 <ETTerms.exe>\ETTerms.SerialMcp\ETTerms.SerialMcp.exe 必定存在。 且 McpRegistrar.ResolveServerExe() 解析的 <ETTerms.exe>\<server>\<server>.exe 必定存在。
刻意放子資料夾:與 GUI 的相依 dll 隔離,避免互相覆蓋。 刻意放子資料夾:與 GUI 的相依 dll 隔離,避免互相覆蓋。
MCP 跟隨 GUI 的 self-contained 設定:框架相依版 → MCP 也框架相依;portable(self-contained)版 → MCP 也免 runtime。 MCP 跟隨 GUI 的 self-contained 設定:框架相依版 → MCP 也框架相依;portable(self-contained)版 → MCP 也免 runtime。
--> -->
<Target Name="PublishSerialMcp" AfterTargets="Publish"> <Target Name="PublishMcpServers" AfterTargets="Publish">
<PropertyGroup> <PropertyGroup>
<_McpRid Condition="'$(RuntimeIdentifier)' != ''">$(RuntimeIdentifier)</_McpRid> <_McpRid Condition="'$(RuntimeIdentifier)' != ''">$(RuntimeIdentifier)</_McpRid>
<_McpRid Condition="'$(RuntimeIdentifier)' == ''">win-x64</_McpRid> <_McpRid Condition="'$(RuntimeIdentifier)' == ''">win-x64</_McpRid>
@@ -51,6 +51,8 @@
</PropertyGroup> </PropertyGroup>
<Message Importance="high" Text="[ETTerms] Publishing ETTerms.SerialMcp -> $(PublishDir)ETTerms.SerialMcp (self-contained=$(_McpSelfContained))" /> <Message Importance="high" Text="[ETTerms] Publishing ETTerms.SerialMcp -> $(PublishDir)ETTerms.SerialMcp (self-contained=$(_McpSelfContained))" />
<Exec Command="dotnet publish &quot;$(MSBuildThisFileDirectory)..\ETTerms.SerialMcp\ETTerms.SerialMcp.csproj&quot; -c $(Configuration) -r $(_McpRid) --self-contained $(_McpSelfContained) -o &quot;$(PublishDir)ETTerms.SerialMcp&quot;" /> <Exec Command="dotnet publish &quot;$(MSBuildThisFileDirectory)..\ETTerms.SerialMcp\ETTerms.SerialMcp.csproj&quot; -c $(Configuration) -r $(_McpRid) --self-contained $(_McpSelfContained) -o &quot;$(PublishDir)ETTerms.SerialMcp&quot;" />
<Message Importance="high" Text="[ETTerms] Publishing ETTerms.PduMcp -> $(PublishDir)ETTerms.PduMcp (self-contained=$(_McpSelfContained))" />
<Exec Command="dotnet publish &quot;$(MSBuildThisFileDirectory)..\ETTerms.PduMcp\ETTerms.PduMcp.csproj&quot; -c $(Configuration) -r $(_McpRid) --self-contained $(_McpSelfContained) -o &quot;$(PublishDir)ETTerms.PduMcp&quot;" />
</Target> </Target>
</Project> </Project>
+51 -23
View File
@@ -8,16 +8,25 @@ namespace ETTerms.Infrastructure;
public enum McpTarget { Claude, Kiro } public enum McpTarget { Claude, Kiro }
/// <summary> /// <summary>
/// 把 ETTerms 的 Serial MCP server<c>ETTerms.SerialMcp</c>)一鍵註冊 / 移除到 /// 把 ETTerms 的 MCP servers<c>ETTerms.SerialMcp</c> 與 <c>ETTerms.PduMcp</c>)一鍵註冊 /
/// 各 AI CLI 的「使用者層級」MCP 設定檔。採 read-modify-write,保留檔內其他既有伺服器。 /// 移除到各 AI CLI 的「使用者層級」MCP 設定檔。採 read-modify-write,保留檔內其他既有伺服器。
/// ///
/// - Claude Code<c>~/.claude.json</c> 頂層 <c>mcpServers</c>entry 需 <c>type:"stdio"</c>。 /// - Claude Code<c>~/.claude.json</c> 頂層 <c>mcpServers</c>entry 需 <c>type:"stdio"</c>。
/// - Kiro<c>%USERPROFILE%\.kiro\settings\mcp.json</c> 頂層 <c>mcpServers</c>。 /// - Kiro<c>%USERPROFILE%\.kiro\settings\mcp.json</c> 頂層 <c>mcpServers</c>。
///
/// 兩個 server 一起註冊 / 移除(一鍵同時設定 serial 與 pdu)。
/// </summary> /// </summary>
public static class McpRegistrar public static class McpRegistrar
{ {
/// <summary>註冊到各 CLI 時用的 MCP server 名。</summary> /// <summary>一個可被註冊的 MCP server 描述:CLI 內名稱 + 發佈子資料夾 + 執行檔名。</summary>
public const string ServerName = "etterms-serial"; public sealed record McpServer(string Name, string PublishFolder, string ExeName);
/// <summary>ETTerms 提供的所有 MCP servers。</summary>
public static readonly IReadOnlyList<McpServer> Servers = new[]
{
new McpServer("etterms-serial", "ETTerms.SerialMcp", "ETTerms.SerialMcp.exe"),
new McpServer("etterms-pdu", "ETTerms.PduMcp", "ETTerms.PduMcp.exe"),
};
public static string DisplayName(McpTarget t) => t switch public static string DisplayName(McpTarget t) => t switch
{ {
@@ -43,33 +52,33 @@ public static class McpRegistrar
{ {
McpTarget.Claude => McpTarget.Claude =>
"claude mcp list\r\n" + "claude mcp list\r\n" +
$"# 應看到:{ServerName} ✓ Connected\r\n" + "# 應看到:etterms-serial / etterms-pdu ✓ Connected\r\n" +
$"# 細節: claude mcp get {ServerName}", "# 細節: claude mcp get etterms-pdu",
McpTarget.Kiro => McpTarget.Kiro =>
"kiro-cli mcp list\r\n" + "kiro-cli mcp list\r\n" +
$"kiro-cli mcp status --name {ServerName}\r\n" + "kiro-cli mcp status --name etterms-pdu\r\n" +
"# 或在 Kiro IDE:點 ghost 圖示開 MCP Servers 面板查看狀態", "# 或在 Kiro IDE:點 ghost 圖示開 MCP Servers 面板查看狀態",
_ => "" _ => ""
}; };
/// <summary>找出 ETTerms.SerialMcp 執行檔路徑(找不到回傳最可能的位置作為註冊值)。</summary> /// <summary>找出某個 MCP server 執行檔路徑(找不到回傳最可能的位置作為註冊值)。</summary>
public static string ResolveServerExe() public static string ResolveServerExe(McpServer server)
{ {
var baseDir = AppContext.BaseDirectory; var baseDir = AppContext.BaseDirectory;
var candidates = new List<string> var candidates = new List<string>
{ {
Path.Combine(baseDir, "ETTerms.SerialMcp", "ETTerms.SerialMcp.exe"), // 發佈版(子資料夾) Path.Combine(baseDir, server.PublishFolder, server.ExeName), // 發佈版(子資料夾)
Path.Combine(baseDir, "ETTerms.SerialMcp.exe"), // 同層 Path.Combine(baseDir, server.ExeName), // 同層
}; };
// 開發版 fallbacksrc\ETTerms\bin\<cfg>\net8.0-windows → src\ETTerms.SerialMcp\bin\<cfg>\net8.0 // 開發版 fallbacksrc\ETTerms\bin\<cfg>\net8.0-windows → src\<folder>\bin\<cfg>\net8.0
try try
{ {
var binCfg = new DirectoryInfo(baseDir); // ...\net8.0-windows var binCfg = new DirectoryInfo(baseDir); // ...\net8.0-windows
var config = binCfg.Parent?.Name ?? "Debug"; // Debug / Release var config = binCfg.Parent?.Name ?? "Debug"; // Debug / Release
var srcDir = binCfg.Parent?.Parent?.Parent?.Parent; // ...\src var srcDir = binCfg.Parent?.Parent?.Parent?.Parent; // ...\src
if (srcDir != null) if (srcDir != null)
candidates.Add(Path.Combine(srcDir.FullName, "ETTerms.SerialMcp", "bin", config, "net8.0", "ETTerms.SerialMcp.exe")); candidates.Add(Path.Combine(srcDir.FullName, server.PublishFolder, "bin", config, "net8.0", server.ExeName));
} }
catch { /* 路徑推導失敗就略過開發版 fallback */ } catch { /* 路徑推導失敗就略過開發版 fallback */ }
@@ -78,22 +87,34 @@ public static class McpRegistrar
return candidates[0]; // 都找不到 → 回發佈版預期位置 return candidates[0]; // 都找不到 → 回發佈版預期位置
} }
public static bool ServerExeExists() => File.Exists(ResolveServerExe()); /// <summary>所有 server 執行檔是否都存在。</summary>
public static bool ServerExeExists() => Servers.All(s => File.Exists(ResolveServerExe(s)));
/// <summary>該目標是否已註冊 etterms-serial。</summary> /// <summary>列出每個 server 的解析路徑與是否存在(給 UI 顯示)。</summary>
public static IEnumerable<(string Name, string Exe, bool Exists)> ServerInfos()
{
foreach (var s in Servers)
{
var exe = ResolveServerExe(s);
yield return (s.Name, exe, File.Exists(exe));
}
}
/// <summary>該目標是否已註冊「全部」ETTerms MCP servers。</summary>
public static bool IsRegistered(McpTarget t) public static bool IsRegistered(McpTarget t)
{ {
try try
{ {
var path = ConfigPath(t); var path = ConfigPath(t);
if (!File.Exists(path)) return false; if (!File.Exists(path)) return false;
var root = JsonNode.Parse(File.ReadAllText(path)) as JsonObject; var servers = (JsonNode.Parse(File.ReadAllText(path)) as JsonObject)?["mcpServers"] as JsonObject;
return (root?["mcpServers"] as JsonObject)?[ServerName] != null; if (servers == null) return false;
return Servers.All(s => servers[s.Name] != null);
} }
catch { return false; } catch { return false; }
} }
/// <summary>註冊(或更新)etterms-serial 到該目標設定檔。</summary> /// <summary>註冊(或更新)所有 ETTerms MCP servers 到該目標設定檔。</summary>
public static void Register(McpTarget t) public static void Register(McpTarget t)
{ {
var path = ConfigPath(t); var path = ConfigPath(t);
@@ -106,27 +127,34 @@ public static class McpRegistrar
servers = new JsonObject(); servers = new JsonObject();
root["mcpServers"] = servers; root["mcpServers"] = servers;
} }
servers[ServerName] = BuildEntry(t); foreach (var s in Servers)
servers[s.Name] = BuildEntry(t, s);
WriteRoot(path, root); WriteRoot(path, root);
AppLogger.Info($"MCP registered to {DisplayName(t)} at {path}"); AppLogger.Info($"MCP registered to {DisplayName(t)} at {path}");
} }
/// <summary>從該目標設定檔移除 etterms-serial。</summary> /// <summary>從該目標設定檔移除所有 ETTerms MCP servers。</summary>
public static void Unregister(McpTarget t) public static void Unregister(McpTarget t)
{ {
var path = ConfigPath(t); var path = ConfigPath(t);
if (!File.Exists(path)) return; if (!File.Exists(path)) return;
var root = LoadRoot(path); var root = LoadRoot(path);
if (root["mcpServers"] is JsonObject servers && servers.Remove(ServerName)) if (root["mcpServers"] is JsonObject servers)
{
bool changed = false;
foreach (var s in Servers)
changed |= servers.Remove(s.Name);
if (changed)
{ {
WriteRoot(path, root); WriteRoot(path, root);
AppLogger.Info($"MCP unregistered from {DisplayName(t)} at {path}"); AppLogger.Info($"MCP unregistered from {DisplayName(t)} at {path}");
} }
} }
}
private static JsonObject BuildEntry(McpTarget t) private static JsonObject BuildEntry(McpTarget t, McpServer server)
{ {
var exe = ResolveServerExe(); var exe = ResolveServerExe(server);
return t switch return t switch
{ {
// Claude Codestdio server 需 type 欄位 // Claude Codestdio server 需 type 欄位