返回 DeepSeek-Reasonix
mcp_manager_view.go
根目录 / internal / cli / mcp_manager_view.go
1 package cli
2
3 // mcp_manager_view.go renders the /mcp manager overlay and its display strings.
4
5 import (
6 "fmt"
7 "strings"
8
9 "reasonix/internal/config"
10 "reasonix/internal/mcpdiag"
11 )
12
13 func (m chatTUI) renderMCPManagerPanel() panelContent {
14 if m.mcp == nil {
15 return panelContent{}
16 }
17 return m.mcp.renderPanel(m.width)
18 }
19
20 func (p *mcpManager) renderPanel(width int) panelContent {
21 w := max(viewWidth(width), 40)
22 switch p.stage {
23 case mcpStageDetail:
24 return p.renderDetailBody(w).render(managerContentPanelStyle(w), width)
25 case mcpStageTools:
26 return p.renderToolsBody(w).render(managerContentPanelStyle(w), width)
27 case mcpStageLogs:
28 return p.renderLogsBody(w).render(managerContentPanelStyle(w), width)
29 case mcpStageConfirmRemove:
30 return p.renderConfirmRemoveBody(w).render(managerContentPanelStyle(w), width)
31 case mcpStageConfirmClearAuth:
32 return p.renderConfirmClearAuthBody(w).render(managerContentPanelStyle(w), width)
33 default:
34 return p.renderListBody(w).render(managerContentPanelStyle(w), width)
35 }
36 }
37
38 func (p *mcpManager) footerHint() string {
39 switch p.stage {
40 case mcpStageDetail:
41 return "↑/↓ navigate · r refresh · Enter to select · Esc to back"
42 case mcpStageTools, mcpStageLogs:
43 return "Esc to back"
44 case mcpStageConfirmRemove, mcpStageConfirmClearAuth:
45 return "Enter to select · y confirm · n cancel · Esc to back"
46 default:
47 if len(p.snapshot.servers) == 0 {
48 return "↑/↓ navigate · Enter to confirm · Esc to cancel"
49 }
50 return "↑/↓ navigate · r refresh · Enter for details · Esc to close"
51 }
52 }
53
54 func (p *mcpManager) renderList(width int) string {
55 return p.renderListBody(width).text
56 }
57
58 func (p *mcpManager) renderListBody(width int) panelBody {
59 var b panelBuilder
60 fmt.Fprintf(&b, "%s\n", viewHeader("Manage MCP servers"))
61 fmt.Fprintf(&b, "%s\n\n", viewMeta(fmt.Sprintf("%d servers", len(p.snapshot.servers))))
62 if p.snapshot.err != "" {
63 fmt.Fprintf(&b, "%s\n\n", yellow("config: "+p.snapshot.err))
64 }
65 if len(p.snapshot.servers) == 0 {
66 b.WriteString(viewMeta("No MCP servers configured. Use /mcp add <name> ... to add one.") + "\n\n")
67 return b.body()
68 }
69 start, end := visibleRange(len(p.snapshot.servers), p.sel, mcpListMaxRows)
70 if start > 0 {
71 fmt.Fprintf(&b, "%s\n", viewMeta(fmt.Sprintf("↑ %d more above", start)))
72 }
73 lastGroup := ""
74 for i := start; i < end; i++ {
75 s := p.snapshot.servers[i]
76 group := mcpServerGroupLabel(s)
77 if group != lastGroup {
78 if lastGroup != "" {
79 b.WriteByte('\n')
80 }
81 header := group
82 if group == "Global MCPs" && p.snapshot.configPath != "" {
83 header += " (" + p.snapshot.configPath + ")"
84 }
85 fmt.Fprintf(&b, " %s\n", bold(header))
86 lastGroup = group
87 }
88 b.MarkFocus(i == p.sel, i)
89 b.WriteString(p.renderListRow(i, s, width) + "\n")
90 }
91 if end < len(p.snapshot.servers) {
92 fmt.Fprintf(&b, "%s\n", viewMeta(fmt.Sprintf("↓ %d more below", len(p.snapshot.servers)-end)))
93 }
94 return b.body().trimTrailingNewlines()
95 }
96
97 func (p *mcpManager) renderListRow(i int, s mcpServerView, width int) string {
98 prefix := " "
99 if i == p.sel {
100 prefix = accent(" › ")
101 }
102 nameWidth := min(28, max(12, width/3))
103 name := compactMiddle(s.Name, nameWidth)
104 status := mcpStatusLabel(s)
105 meta := fmt.Sprintf("%s · %s", status, countText(s.Tools, "tool"))
106 if s.Prompts > 0 {
107 meta += " · " + countText(s.Prompts, "prompt")
108 }
109 if s.Resources > 0 {
110 meta += " · " + countText(s.Resources, "resource")
111 }
112 if s.Transport != "" {
113 meta = s.Transport + " · " + meta
114 }
115 used := visibleWidth(prefix) + nameWidth + 3
116 meta = viewCompactText(meta, viewBudget(width, used))
117 name = padRight(name, nameWidth)
118 if i == p.sel {
119 name = bold(name)
120 }
121 return fmt.Sprintf("%s%s · %s", prefix, name, viewMeta(meta))
122 }
123
124 func (p *mcpManager) renderDetail(width int) string {
125 return p.renderDetailBody(width).text
126 }
127
128 func (p *mcpManager) renderDetailBody(width int) panelBody {
129 v, ok := p.selectedServer()
130 if !ok {
131 return panelBody{text: "MCP server not found\n\n" + dim("Esc to back")}
132 }
133 actions := mcpActionsFor(v, p.snapshot.configPath)
134 if p.action >= len(actions) {
135 p.action = max(0, len(actions)-1)
136 }
137 var b panelBuilder
138 fmt.Fprintf(&b, "%s MCP Server\n\n", bold(titleText(v.Name)))
139 writeMCPDetailField(&b.Builder, "Status", mcpStatusLabel(v))
140 if auth := mcpAuthLabel(v); auth != "" {
141 writeMCPDetailField(&b.Builder, "Auth", auth)
142 }
143 writeMCPDetailField(&b.Builder, "Transport", fallbackText(v.Transport, "unknown"))
144 if v.BuiltIn {
145 writeMCPDetailField(&b.Builder, "Config location", "built-in")
146 } else if v.Source == config.MCPSourceProjectMCPJSON {
147 writeMCPDetailField(&b.Builder, "Config location", "current project .mcp.json")
148 } else if v.Source == config.MCPSourceProjectConfig {
149 writeMCPDetailField(&b.Builder, "Config location", "current project reasonix.toml")
150 } else {
151 loc := fallbackText(p.snapshot.configPath, "not saved")
152 if loc != "not saved" {
153 loc = viewCompactPath(loc, viewBudget(width, 18))
154 }
155 writeMCPDetailField(&b.Builder, "Config location", loc)
156 }
157 writeMCPDetailField(&b.Builder, "Capabilities", mcpCapabilitiesText(v))
158 writeMCPDetailField(&b.Builder, "Tools", countText(v.Tools, "tool"))
159 if line := mcpCommandLine(v); line != "" {
160 writeMCPDetailField(&b.Builder, mcpCommandLabel(v), viewCompactText(line, viewBudget(width, 18)))
161 }
162 if len(v.EnvKeys) > 0 {
163 writeMCPDetailField(&b.Builder, "Env", strings.Join(v.EnvKeys, ", "))
164 }
165 if v.Error != "" {
166 writeMCPDetailField(&b.Builder, "Error", viewCompactText(v.Error, viewBudget(width, 18)))
167 }
168 b.WriteByte('\n')
169 if len(actions) == 0 {
170 b.WriteString(viewMeta("No actions available.") + "\n")
171 } else {
172 for i, a := range actions {
173 b.MarkFocus(i == p.action, i)
174 b.WriteString(rowLine(i == p.action, i+1, "", a.label, false) + "\n")
175 }
176 }
177 return b.body().trimTrailingNewlines()
178 }
179
180 func (p *mcpManager) renderToolsBody(width int) panelBody {
181 v, ok := p.selectedServer()
182 if !ok {
183 return panelBody{text: "MCP server not found\n\n" + dim("Esc to back")}
184 }
185 var b panelBuilder
186 fmt.Fprintf(&b, "%s tools\n\n", bold(v.Name))
187 if len(v.ToolList) == 0 {
188 b.WriteString(viewMeta("Current connection did not return tool details.") + "\n")
189 } else {
190 limit := min(len(v.ToolList), mcpToolMaxRows)
191 for _, t := range v.ToolList[:limit] {
192 desc := t.Description
193 if t.SchemaError != "" {
194 desc = "unavailable: " + t.SchemaError
195 }
196 desc = viewCompactText(desc, viewBudget(width, 24))
197 fmt.Fprintf(&b, " %-20s %s\n", t.Name, viewMeta(desc))
198 }
199 if extra := len(v.ToolList) - limit; extra > 0 {
200 fmt.Fprintf(&b, "%s\n", viewMore(extra, "tools"))
201 }
202 }
203 return b.body().trimTrailingNewlines()
204 }
205
206 func (p *mcpManager) renderLogsBody(width int) panelBody {
207 v, ok := p.selectedServer()
208 if !ok {
209 return panelBody{text: "MCP server not found\n\n" + dim("Esc to back")}
210 }
211 var b panelBuilder
212 fmt.Fprintf(&b, "%s logs\n\n", bold(v.Name))
213 if strings.TrimSpace(v.Error) == "" {
214 b.WriteString(viewMeta("No failure log recorded for this MCP.") + "\n")
215 } else {
216 b.WriteString(viewProtectLines(v.Error, viewBudget(width, 2)) + "\n")
217 }
218 return b.body().trimTrailingNewlines()
219 }
220
221 func (p *mcpManager) renderConfirmRemoveBody(width int) panelBody {
222 v, ok := p.selectedServer()
223 if !ok {
224 return panelBody{text: "MCP server not found\n\n" + dim("Esc to back")}
225 }
226 var b panelBuilder
227 fmt.Fprintf(&b, "Remove MCP server %q?\n", v.Name)
228 b.WriteString(viewMeta("This removes it from Reasonix config. It cannot be undone from this panel.") + "\n\n")
229 b.MarkFocus(p.confirm == 0, 0)
230 b.WriteString(rowLine(p.confirm == 0, 1, "", "Confirm remove", false) + "\n")
231 b.MarkFocus(p.confirm == 1, 1)
232 b.WriteString(rowLine(p.confirm == 1, 2, "", "Cancel", false) + "\n")
233 return b.body().trimTrailingNewlines()
234 }
235
236 func (p *mcpManager) renderConfirmClearAuth(width int) string {
237 return p.renderConfirmClearAuthBody(width).text
238 }
239
240 func (p *mcpManager) renderConfirmClearAuthBody(width int) panelBody {
241 v, ok := p.selectedServer()
242 if !ok {
243 return panelBody{text: "MCP server not found\n\n" + dim("Esc to back")}
244 }
245 var b panelBuilder
246 fmt.Fprintf(&b, "Clear authentication for MCP server %q?\n", v.Name)
247 hint := "This removes local auth-like headers, environment values, and URL tokens; the server stays in config."
248 b.WriteString(viewMeta(viewCompactText(hint, viewBudget(width, 0))) + "\n\n")
249 b.MarkFocus(p.confirm == 0, 0)
250 b.WriteString(rowLine(p.confirm == 0, 1, "", "Confirm clear authentication", false) + "\n")
251 b.MarkFocus(p.confirm == 1, 1)
252 b.WriteString(rowLine(p.confirm == 1, 2, "", "Cancel", false) + "\n")
253 return b.body().trimTrailingNewlines()
254 }
255
256 func mcpActionsFor(v mcpServerView, configPath string) []mcpActionItem {
257 var out []mcpActionItem
258 managed := v.BuiltIn || v.Source == config.MCPSourcePluginPackage
259 if v.Tools > 0 || len(v.ToolList) > 0 {
260 out = append(out, mcpActionItem{mcpActionViewTools, "View tools"})
261 }
262 if v.Status == "failed" {
263 if mcpAuthStatus(v) == mcpdiag.AuthRequired {
264 out = append(out, mcpActionItem{mcpActionAuth, "Authenticate"})
265 } else {
266 out = append(out, mcpActionItem{mcpActionConnect, "Retry"})
267 }
268 if mcpCanClearAuth(v) {
269 out = append(out, mcpActionItem{mcpActionClearAuth, "Clear authentication"})
270 }
271 out = appendMCPFailureSecondaryActions(out, v, configPath)
272 return out
273 }
274 switch v.Status {
275 case "connected":
276 out = append(out, mcpActionItem{mcpActionConnect, "Reconnect"})
277 case "deferred":
278 out = append(out, mcpActionItem{mcpActionConnect, "Reconnect"})
279 case "disabled":
280 out = append(out, mcpActionItem{mcpActionConnect, "Enable and connect"})
281 }
282 out = appendMCPConfigActions(out, v, configPath)
283 if mcpCanClearAuth(v) {
284 out = append(out, mcpActionItem{mcpActionClearAuth, "Clear authentication"})
285 }
286 if v.Status != "disabled" {
287 out = append(out, mcpActionItem{mcpActionDisable, "Disable for this session"})
288 }
289 if !managed {
290 out = append(out, mcpActionItem{mcpActionRemove, "Remove server"})
291 }
292 return out
293 }
294
295 func appendMCPFailureSecondaryActions(out []mcpActionItem, v mcpServerView, configPath string) []mcpActionItem {
296 managed := v.BuiltIn || v.Source == config.MCPSourcePluginPackage
297 if strings.TrimSpace(v.Error) != "" {
298 out = append(out, mcpActionItem{mcpActionLogs, "View logs"})
299 }
300 out = appendMCPConfigActions(out, v, configPath)
301 if v.Status != "disabled" {
302 out = append(out, mcpActionItem{mcpActionDisable, "Disable for this session"})
303 }
304 if !managed {
305 out = append(out, mcpActionItem{mcpActionRemove, "Remove server"})
306 }
307 return out
308 }
309
310 func appendMCPConfigActions(out []mcpActionItem, v mcpServerView, configPath string) []mcpActionItem {
311 if v.Configured {
312 path := mcpConfigPathForView(v, configPath)
313 if !v.BuiltIn && v.Source != config.MCPSourcePluginPackage && path != "" {
314 out = append(out, mcpActionItem{mcpActionEdit, "Edit config"})
315 }
316 }
317 return out
318 }
319
320 func mcpConfigPathForView(v mcpServerView, fallback string) string {
321 if path := strings.TrimSpace(v.ConfigPath); path != "" {
322 return path
323 }
324 return strings.TrimSpace(fallback)
325 }
326
327 func writeMCPDetailField(b *strings.Builder, label, value string) {
328 if strings.TrimSpace(value) == "" {
329 return
330 }
331 fmt.Fprintf(b, "%-16s %s\n", label+":", value)
332 }
333
334 func mcpStatusLabel(v mcpServerView) string {
335 switch {
336 case v.Status == "connected":
337 return green("✓ connected")
338 case v.Status == "failed" && mcpAuthStatus(v) == mcpdiag.AuthRequired:
339 return yellow("⚠ needs authentication")
340 case v.Status == "failed":
341 return red("✕ failed")
342 case v.Status == "deferred":
343 return "○ preparing in background"
344 case v.Status == "initializing":
345 return "◌ connecting..."
346 case v.Status == "disabled":
347 return "○ disabled"
348 default:
349 return viewMeta("unknown")
350 }
351 }
352
353 func mcpServerGroupLabel(v mcpServerView) string {
354 switch mcpServerGroupRank(v) {
355 case 0:
356 return "Managed MCPs"
357 case 1:
358 return "Project MCPs"
359 default:
360 return "Global MCPs"
361 }
362 }
363
364 func mcpAuthLabel(v mcpServerView) string {
365 switch {
366 case v.Status == "connected":
367 return green("✓ authenticated")
368 case mcpAuthStatus(v) == mcpdiag.AuthRequired:
369 return red("✕ not authenticated")
370 case mcpAuthStatus(v) == mcpdiag.AuthPossible:
371 return yellow("may need authorization")
372 default:
373 return ""
374 }
375 }
376
377 func mcpCapabilitiesText(v mcpServerView) string {
378 var caps []string
379 if v.HasTools || v.Tools > 0 {
380 caps = append(caps, "tools")
381 }
382 if v.Prompts > 0 {
383 caps = append(caps, "prompts")
384 }
385 if v.Resources > 0 {
386 caps = append(caps, "resources")
387 }
388 if len(caps) == 0 {
389 return "none"
390 }
391 return strings.Join(caps, ", ")
392 }
393
394 func mcpCommandLabel(v mcpServerView) string {
395 if v.Transport == "http" || v.Transport == "sse" {
396 return "URL"
397 }
398 return "Command"
399 }
400
401 func mcpCommandLine(v mcpServerView) string {
402 if v.Transport == "http" || v.Transport == "sse" {
403 return strings.TrimSpace(v.URL)
404 }
405 return strings.TrimSpace(v.Command + " " + strings.Join(v.Args, " "))
406 }
407
407 lines GO