braid-coding-agent 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- braid_coding_agent/__init__.py +13 -0
- braid_coding_agent/assembly.py +460 -0
- braid_coding_agent/cancellation.py +25 -0
- braid_coding_agent/checkpoint/__init__.py +106 -0
- braid_coding_agent/checkpoint/git.py +305 -0
- braid_coding_agent/checkpoint/settings.py +26 -0
- braid_coding_agent/checkpoint/store.py +1261 -0
- braid_coding_agent/checkpoint/workspace.py +220 -0
- braid_coding_agent/cli.py +2168 -0
- braid_coding_agent/commands/__init__.py +50 -0
- braid_coding_agent/commands/auth.py +161 -0
- braid_coding_agent/commands/config.py +180 -0
- braid_coding_agent/commands/doctor.py +511 -0
- braid_coding_agent/commands/mcp.py +928 -0
- braid_coding_agent/commands/models.py +95 -0
- braid_coding_agent/commands/setup.py +89 -0
- braid_coding_agent/commands/uninstall.py +277 -0
- braid_coding_agent/commands/upgrade.py +381 -0
- braid_coding_agent/compaction/__init__.py +174 -0
- braid_coding_agent/compaction/prepare.py +430 -0
- braid_coding_agent/compaction/summarize.py +542 -0
- braid_coding_agent/compaction/tokens.py +204 -0
- braid_coding_agent/compaction/tool_results.py +196 -0
- braid_coding_agent/compaction/utils.py +181 -0
- braid_coding_agent/config.py +2776 -0
- braid_coding_agent/config_files.py +191 -0
- braid_coding_agent/credentials.py +252 -0
- braid_coding_agent/discovery.py +415 -0
- braid_coding_agent/extensions/__init__.py +77 -0
- braid_coding_agent/extensions/api.py +480 -0
- braid_coding_agent/extensions/runner.py +553 -0
- braid_coding_agent/formatting/__init__.py +62 -0
- braid_coding_agent/formatting/settings.py +87 -0
- braid_coding_agent/formatting/tool.py +179 -0
- braid_coding_agent/lsp/__init__.py +105 -0
- braid_coding_agent/lsp/client.py +546 -0
- braid_coding_agent/lsp/manager.py +187 -0
- braid_coding_agent/lsp/model.py +316 -0
- braid_coding_agent/lsp/protocol.py +105 -0
- braid_coding_agent/lsp/settings.py +120 -0
- braid_coding_agent/lsp/tool.py +429 -0
- braid_coding_agent/mcp/__init__.py +101 -0
- braid_coding_agent/mcp/cache.py +230 -0
- braid_coding_agent/mcp/catalog.py +108 -0
- braid_coding_agent/mcp/config.py +664 -0
- braid_coding_agent/mcp/config_store.py +142 -0
- braid_coding_agent/mcp/inspector.py +85 -0
- braid_coding_agent/mcp/panel.py +254 -0
- braid_coding_agent/mcp/runtime.py +1060 -0
- braid_coding_agent/mcp/tools.py +579 -0
- braid_coding_agent/mcp/trust.py +150 -0
- braid_coding_agent/mcp/tui_panel.py +444 -0
- braid_coding_agent/messages.py +152 -0
- braid_coding_agent/models_view.py +105 -0
- braid_coding_agent/modes/__init__.py +64 -0
- braid_coding_agent/modes/json_mode.py +480 -0
- braid_coding_agent/modes/lifecycle.py +217 -0
- braid_coding_agent/modes/print_mode.py +257 -0
- braid_coding_agent/modes/repl.py +2687 -0
- braid_coding_agent/modes/repl_commands.py +263 -0
- braid_coding_agent/modes/rpc.py +953 -0
- braid_coding_agent/modes/skill_commands.py +88 -0
- braid_coding_agent/modes/tui.py +2226 -0
- braid_coding_agent/modes/tui_control.py +90 -0
- braid_coding_agent/modes/tui_model.py +1043 -0
- braid_coding_agent/modes/tui_render.py +327 -0
- braid_coding_agent/modes/tui_rich.py +751 -0
- braid_coding_agent/modes/tui_style.py +42 -0
- braid_coding_agent/modes/wire.py +81 -0
- braid_coding_agent/netsafe.py +82 -0
- braid_coding_agent/network/__init__.py +20 -0
- braid_coding_agent/network/cache.py +77 -0
- braid_coding_agent/network/fetch.py +311 -0
- braid_coding_agent/network/html_text.py +160 -0
- braid_coding_agent/network/search.py +347 -0
- braid_coding_agent/network/settings.py +103 -0
- braid_coding_agent/network/urls.py +89 -0
- braid_coding_agent/observability/__init__.py +101 -0
- braid_coding_agent/observability/audit.py +124 -0
- braid_coding_agent/observability/collector.py +314 -0
- braid_coding_agent/observability/exporter.py +74 -0
- braid_coding_agent/observability/logging_setup.py +149 -0
- braid_coding_agent/observability/redaction.py +96 -0
- braid_coding_agent/observability/settings.py +29 -0
- braid_coding_agent/observability/spans.py +239 -0
- braid_coding_agent/permissions/__init__.py +185 -0
- braid_coding_agent/permissions/command.py +586 -0
- braid_coding_agent/permissions/engine.py +522 -0
- braid_coding_agent/permissions/evaluate.py +309 -0
- braid_coding_agent/permissions/matching.py +233 -0
- braid_coding_agent/permissions/model.py +278 -0
- braid_coding_agent/permissions/policy.py +99 -0
- braid_coding_agent/permissions/readonly.py +236 -0
- braid_coding_agent/permissions/store.py +379 -0
- braid_coding_agent/project_init.py +313 -0
- braid_coding_agent/prompt/__init__.py +98 -0
- braid_coding_agent/prompt/context_files.py +253 -0
- braid_coding_agent/prompt/project_context.py +172 -0
- braid_coding_agent/prompt/system_prompt.py +378 -0
- braid_coding_agent/questions.py +71 -0
- braid_coding_agent/render/__init__.py +56 -0
- braid_coding_agent/render/batch.py +66 -0
- braid_coding_agent/render/history.py +143 -0
- braid_coding_agent/render/stream.py +823 -0
- braid_coding_agent/render/theme.py +243 -0
- braid_coding_agent/sandbox/__init__.py +89 -0
- braid_coding_agent/sandbox/backend.py +184 -0
- braid_coding_agent/sandbox/bubblewrap.py +96 -0
- braid_coding_agent/sandbox/operations.py +301 -0
- braid_coding_agent/sandbox/policy.py +221 -0
- braid_coding_agent/sandbox/proxy.py +320 -0
- braid_coding_agent/sandbox/seatbelt.py +222 -0
- braid_coding_agent/sdk/__init__.py +31 -0
- braid_coding_agent/sdk/async_client.py +366 -0
- braid_coding_agent/sdk/client.py +386 -0
- braid_coding_agent/sdk/errors.py +52 -0
- braid_coding_agent/sdk/events.py +162 -0
- braid_coding_agent/sdk/types.py +63 -0
- braid_coding_agent/sdk/wire.py +59 -0
- braid_coding_agent/server/__init__.py +54 -0
- braid_coding_agent/server/errors.py +52 -0
- braid_coding_agent/server/http_server.py +419 -0
- braid_coding_agent/server/hub.py +530 -0
- braid_coding_agent/server/openapi.py +157 -0
- braid_coding_agent/server/registry.py +354 -0
- braid_coding_agent/server/router.py +275 -0
- braid_coding_agent/server/run.py +148 -0
- braid_coding_agent/server/schema.py +194 -0
- braid_coding_agent/server/service.py +975 -0
- braid_coding_agent/session/__init__.py +293 -0
- braid_coding_agent/session/agent_session.py +2706 -0
- braid_coding_agent/session/context_breakdown.py +302 -0
- braid_coding_agent/session/discovery.py +212 -0
- braid_coding_agent/session/entries.py +809 -0
- braid_coding_agent/session/evidence.py +295 -0
- braid_coding_agent/session/lock.py +176 -0
- braid_coding_agent/session/manager.py +1185 -0
- braid_coding_agent/session/plan.py +243 -0
- braid_coding_agent/session/plan_mode.py +423 -0
- braid_coding_agent/session/projection.py +262 -0
- braid_coding_agent/session/rewind.py +257 -0
- braid_coding_agent/session/status.py +240 -0
- braid_coding_agent/settings.py +94 -0
- braid_coding_agent/skills/__init__.py +70 -0
- braid_coding_agent/skills/loader.py +681 -0
- braid_coding_agent/startup/__init__.py +76 -0
- braid_coding_agent/startup/cache.py +72 -0
- braid_coding_agent/startup/diagnostics.py +37 -0
- braid_coding_agent/startup/monitor.py +245 -0
- braid_coding_agent/startup/phases.py +79 -0
- braid_coding_agent/startup/project.py +165 -0
- braid_coding_agent/startup/report.py +560 -0
- braid_coding_agent/startup/scheduler.py +347 -0
- braid_coding_agent/statusline.py +163 -0
- braid_coding_agent/subagents/__init__.py +22 -0
- braid_coding_agent/subagents/contract.py +75 -0
- braid_coding_agent/subagents/definitions.py +583 -0
- braid_coding_agent/subagents/registry.py +277 -0
- braid_coding_agent/subagents/runtime.py +610 -0
- braid_coding_agent/subagents/settings.py +156 -0
- braid_coding_agent/subagents/worktree.py +63 -0
- braid_coding_agent/tools/__init__.py +327 -0
- braid_coding_agent/tools/args.py +87 -0
- braid_coding_agent/tools/bash.py +359 -0
- braid_coding_agent/tools/edit.py +298 -0
- braid_coding_agent/tools/edit_diff.py +344 -0
- braid_coding_agent/tools/find.py +158 -0
- braid_coding_agent/tools/grep.py +305 -0
- braid_coding_agent/tools/ignore.py +198 -0
- braid_coding_agent/tools/ls.py +127 -0
- braid_coding_agent/tools/mutation_queue.py +90 -0
- braid_coding_agent/tools/operations.py +274 -0
- braid_coding_agent/tools/output_accumulator.py +282 -0
- braid_coding_agent/tools/output_store.py +244 -0
- braid_coding_agent/tools/path_utils.py +91 -0
- braid_coding_agent/tools/plan.py +141 -0
- braid_coding_agent/tools/prompt_notes.py +52 -0
- braid_coding_agent/tools/question.py +180 -0
- braid_coding_agent/tools/read.py +223 -0
- braid_coding_agent/tools/submit_plan.py +102 -0
- braid_coding_agent/tools/truncate.py +423 -0
- braid_coding_agent/tools/write.py +100 -0
- braid_coding_agent/untrusted.py +50 -0
- braid_coding_agent/verify/__init__.py +78 -0
- braid_coding_agent/verify/runner.py +260 -0
- braid_coding_agent/verify/settings.py +64 -0
- braid_coding_agent/verify/tool.py +143 -0
- braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
- braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
- braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
- braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""MCP 服务器的信任记录:外部进程或远程服务,首次连接要人点头。
|
|
2
|
+
|
|
3
|
+
沙箱保护的是 ``bash`` 启动的命令。MCP 服务器不走那条路:stdio 服务器由
|
|
4
|
+
:class:`~braid_coding_agent.mcp.runtime.McpRuntime` 直接 ``create_subprocess_exec``,
|
|
5
|
+
既不在 Seatbelt/bwrap 里,也不受权限引擎管辖(权限判定发生在**工具调用**上,
|
|
6
|
+
而服务器进程从启动那一刻起就在跑)。远程服务器则是另一类风险:它拿到了
|
|
7
|
+
``Authorization`` 头,并能决定把哪些工具声明交给模型。所以「它能不能被连上」
|
|
8
|
+
必须在连接之前问一次。
|
|
9
|
+
|
|
10
|
+
## 记录什么
|
|
11
|
+
|
|
12
|
+
stdio 记 ``command`` 与 ``args`` 的指纹;远程传输(http、sse、ws)记 ``url`` 与
|
|
13
|
+
全部请求头。改一个参数就等于换了一个程序——``npx foo`` 与
|
|
14
|
+
``npx foo --allow-write-everything`` 不是同一件事,名字相同也不该沿用上次的信任。
|
|
15
|
+
请求头里可能有租户标识,换租户等于换了服务。
|
|
16
|
+
|
|
17
|
+
stdio 的指纹构成保持不变:升级不该让用户已有的信任记录全部失效。
|
|
18
|
+
|
|
19
|
+
```json
|
|
20
|
+
{"servers": {"filesystem": {"fingerprint": "…", "trusted_at": "2026-11-14T12:00:00+08:00"}}}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
文件在 ``~/.braid/mcp_trust.json``。删掉一项就等于要求重新确认;用户不需要
|
|
24
|
+
记文件名,``--trust-mcp`` 与交互确认都会写它。
|
|
25
|
+
|
|
26
|
+
## 非交互通道的失败关闭
|
|
27
|
+
|
|
28
|
+
``-p``/``--mode json`` 没有终端可以问。此时未受信任的服务器**不连接**,stderr 留一行
|
|
29
|
+
说明。想在没有终端的环境里用 MCP,就显式加 ``--trust-mcp``(或在该条目上写
|
|
30
|
+
``"trusted": true``):这句显式的话就是确认。
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import hashlib
|
|
36
|
+
import json
|
|
37
|
+
from dataclasses import dataclass
|
|
38
|
+
from datetime import UTC, datetime
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
|
|
41
|
+
from braid_ai.types import JsonValue
|
|
42
|
+
from braid_coding_agent.mcp.config import McpServerConfig
|
|
43
|
+
|
|
44
|
+
#: 信任记录文件名(相对 ``~/.braid``)。
|
|
45
|
+
TRUST_FILE_NAME = "mcp_trust.json"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(slots=True, frozen=True)
|
|
49
|
+
class TrustRecord:
|
|
50
|
+
"""一个已信任服务器的指纹与时间。时间只用于排查,不参与判定。"""
|
|
51
|
+
|
|
52
|
+
fingerprint: str
|
|
53
|
+
trusted_at: str
|
|
54
|
+
|
|
55
|
+
def to_json(self) -> dict[str, JsonValue]:
|
|
56
|
+
return {"fingerprint": self.fingerprint, "trusted_at": self.trusted_at}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def server_fingerprint(server: McpServerConfig) -> str:
|
|
60
|
+
"""连接目标的指纹:stdio 看命令与参数,远程传输看地址与请求头。"""
|
|
61
|
+
if server.transport in ("http", "sse", "ws"):
|
|
62
|
+
headers = "\0".join(f"{key}:{value}" for key, value in sorted(server.headers.items()))
|
|
63
|
+
payload = "\0".join((server.transport, server.url or "", headers))
|
|
64
|
+
else:
|
|
65
|
+
# 这一段的构成不要改动:改了会让升级前写下的信任记录全部失效。
|
|
66
|
+
payload = "\0".join((server.command or "", *server.args, server.cwd or ""))
|
|
67
|
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def load_trust(agent_dir: Path) -> dict[str, TrustRecord]:
|
|
71
|
+
"""读信任表。文件不存在、读坏或结构不对都返回空表:宁可多问一次,不要误信。"""
|
|
72
|
+
path = agent_dir / TRUST_FILE_NAME
|
|
73
|
+
if not path.is_file():
|
|
74
|
+
return {}
|
|
75
|
+
try:
|
|
76
|
+
payload: JsonValue = json.loads(path.read_text(encoding="utf-8-sig"))
|
|
77
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
78
|
+
return {}
|
|
79
|
+
if not isinstance(payload, dict):
|
|
80
|
+
return {}
|
|
81
|
+
raw_servers = payload.get("servers")
|
|
82
|
+
if not isinstance(raw_servers, dict):
|
|
83
|
+
return {}
|
|
84
|
+
records: dict[str, TrustRecord] = {}
|
|
85
|
+
for name, entry in raw_servers.items():
|
|
86
|
+
if not isinstance(entry, dict):
|
|
87
|
+
continue
|
|
88
|
+
fingerprint = entry.get("fingerprint")
|
|
89
|
+
trusted_at = entry.get("trusted_at")
|
|
90
|
+
if isinstance(fingerprint, str) and fingerprint:
|
|
91
|
+
records[str(name)] = TrustRecord(
|
|
92
|
+
fingerprint=fingerprint,
|
|
93
|
+
trusted_at=trusted_at if isinstance(trusted_at, str) else "",
|
|
94
|
+
)
|
|
95
|
+
return records
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def save_trust(agent_dir: Path, records: dict[str, TrustRecord]) -> None:
|
|
99
|
+
"""写回信任表。目录不存在就建;写不出去不抛异常——记不住信任只会导致再问一次。"""
|
|
100
|
+
path = agent_dir / TRUST_FILE_NAME
|
|
101
|
+
payload = {"servers": {name: record.to_json() for name, record in records.items()}}
|
|
102
|
+
try:
|
|
103
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
path.write_text(
|
|
105
|
+
json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
|
|
106
|
+
encoding="utf-8",
|
|
107
|
+
)
|
|
108
|
+
except OSError:
|
|
109
|
+
return
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def is_trusted(records: dict[str, TrustRecord], server: McpServerConfig) -> bool:
|
|
113
|
+
"""名字对上且指纹一致才算信任。"""
|
|
114
|
+
record = records.get(server.name)
|
|
115
|
+
return record is not None and record.fingerprint == server_fingerprint(server)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def remember(records: dict[str, TrustRecord], server: McpServerConfig) -> TrustRecord:
|
|
119
|
+
"""把一个服务器记为已信任,返回新记录(调用方负责保存)。"""
|
|
120
|
+
record = TrustRecord(
|
|
121
|
+
fingerprint=server_fingerprint(server),
|
|
122
|
+
trusted_at=datetime.now(UTC).isoformat(timespec="seconds"),
|
|
123
|
+
)
|
|
124
|
+
records[server.name] = record
|
|
125
|
+
return record
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def risk_notice(server: McpServerConfig) -> str:
|
|
129
|
+
"""连接前的风险说明。写清来源与它拿到了什么。"""
|
|
130
|
+
if server.transport in ("http", "sse", "ws"):
|
|
131
|
+
return (
|
|
132
|
+
f"MCP 服务器 {server.name} 是一个远程服务({server.url}),"
|
|
133
|
+
"它会收到本机的请求头(含 OAuth 令牌),并决定把哪些工具声明交给模型。"
|
|
134
|
+
)
|
|
135
|
+
return (
|
|
136
|
+
f"MCP 服务器 {server.name} 是一个外部进程({server.endpoint}),"
|
|
137
|
+
"它不经过操作系统沙箱,也不受本会话的权限规则约束。"
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
__all__ = [
|
|
142
|
+
"TRUST_FILE_NAME",
|
|
143
|
+
"TrustRecord",
|
|
144
|
+
"is_trusted",
|
|
145
|
+
"load_trust",
|
|
146
|
+
"remember",
|
|
147
|
+
"risk_notice",
|
|
148
|
+
"save_trust",
|
|
149
|
+
"server_fingerprint",
|
|
150
|
+
]
|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
"""TUI 的 MCP 管理面板:服务器列表、服务器详情、工具 Schema 与调用历史。
|
|
2
|
+
|
|
3
|
+
这一层只维护层级、光标与滚动位置,并从 :class:`McpRuntime` 读取只读快照。
|
|
4
|
+
渲染交给 TUI 的内容块,按键在 :mod:`braid_coding_agent.modes.tui` 接线。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Literal
|
|
12
|
+
|
|
13
|
+
from braid_coding_agent.mcp.catalog import ToolEntry, estimate_tokens
|
|
14
|
+
from braid_coding_agent.mcp.runtime import McpRuntime, McpServerStatus
|
|
15
|
+
|
|
16
|
+
type McpPanelLevel = Literal["servers", "server", "schema", "history"]
|
|
17
|
+
type McpPanelVerb = Literal["toggle", "reconnect", "refresh", "reload"]
|
|
18
|
+
|
|
19
|
+
#: 服务器详情里排在最前面的管理动作行数。
|
|
20
|
+
_ACTION_ROWS = 5
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(slots=True, frozen=True)
|
|
24
|
+
class McpPanelView:
|
|
25
|
+
"""一帧可直接交给渲染层的内容。``selected`` 是 ``lines`` 里的高亮下标。"""
|
|
26
|
+
|
|
27
|
+
title: str
|
|
28
|
+
lines: tuple[str, ...]
|
|
29
|
+
selected: int = -1
|
|
30
|
+
hint: str = ""
|
|
31
|
+
message: str = ""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(slots=True, frozen=True)
|
|
35
|
+
class McpPanelAction:
|
|
36
|
+
"""面板发起的异步动作,由 TUI 调用运行时执行。"""
|
|
37
|
+
|
|
38
|
+
verb: McpPanelVerb
|
|
39
|
+
server: str | None = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(slots=True, frozen=True)
|
|
43
|
+
class _Row:
|
|
44
|
+
kind: Literal["server", "action", "tool"]
|
|
45
|
+
label: str
|
|
46
|
+
value: str
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class McpPanel:
|
|
50
|
+
"""MCP 管理面板的状态机。"""
|
|
51
|
+
|
|
52
|
+
def __init__(self, runtime: McpRuntime | None) -> None:
|
|
53
|
+
self._runtime = runtime
|
|
54
|
+
self._level: McpPanelLevel = "servers"
|
|
55
|
+
self._server: str | None = None
|
|
56
|
+
self._tool: str | None = None
|
|
57
|
+
self._cursor = 0
|
|
58
|
+
self._scroll = 0
|
|
59
|
+
self._message = ""
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def level(self) -> McpPanelLevel:
|
|
63
|
+
return self._level
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def server(self) -> str | None:
|
|
67
|
+
return self._server
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def tool(self) -> str | None:
|
|
71
|
+
return self._tool
|
|
72
|
+
|
|
73
|
+
def view(self, capacity: int) -> McpPanelView:
|
|
74
|
+
"""按终端可容纳的行数截取当前层级的内容。"""
|
|
75
|
+
body, selected = self._body()
|
|
76
|
+
hint = self._hint()
|
|
77
|
+
size = max(3, capacity)
|
|
78
|
+
if len(body) <= size:
|
|
79
|
+
lines = body
|
|
80
|
+
index = selected
|
|
81
|
+
else:
|
|
82
|
+
start = min(self._scroll, len(body) - size) if selected < 0 else selected - size // 2
|
|
83
|
+
start = max(0, min(start, len(body) - size))
|
|
84
|
+
lines = body[start : start + size]
|
|
85
|
+
index = selected - start if selected >= 0 else -1
|
|
86
|
+
hint = f"{hint} · 第 {start + 1}-{start + size}/{len(body)} 行"
|
|
87
|
+
return McpPanelView(
|
|
88
|
+
title=self._title(),
|
|
89
|
+
lines=tuple(lines),
|
|
90
|
+
selected=index,
|
|
91
|
+
hint=hint,
|
|
92
|
+
message=self._message,
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def move(self, delta: int) -> None:
|
|
96
|
+
"""列表内移动光标;Schema 与历史视图里改为滚动。"""
|
|
97
|
+
if self._level in ("schema", "history"):
|
|
98
|
+
self._scroll = max(0, self._scroll + delta)
|
|
99
|
+
return
|
|
100
|
+
rows = self._rows()
|
|
101
|
+
if not rows:
|
|
102
|
+
self._cursor = 0
|
|
103
|
+
return
|
|
104
|
+
self._cursor = (self._cursor + delta) % len(rows)
|
|
105
|
+
|
|
106
|
+
def page(self, delta: int, size: int) -> None:
|
|
107
|
+
"""整页翻动。``size`` 是当前可见行数。"""
|
|
108
|
+
step = max(1, size)
|
|
109
|
+
if self._level in ("schema", "history"):
|
|
110
|
+
self._scroll = max(0, self._scroll + delta * step)
|
|
111
|
+
return
|
|
112
|
+
rows = self._rows()
|
|
113
|
+
if not rows:
|
|
114
|
+
return
|
|
115
|
+
self._cursor = max(0, min(len(rows) - 1, self._cursor + delta * step))
|
|
116
|
+
|
|
117
|
+
def back(self) -> bool:
|
|
118
|
+
"""返回上一层。已经位于服务器列表时返回 ``False``,由 TUI 关闭浮层。"""
|
|
119
|
+
if self._level == "schema":
|
|
120
|
+
self._level = "server"
|
|
121
|
+
self._tool = None
|
|
122
|
+
self._scroll = 0
|
|
123
|
+
self._message = ""
|
|
124
|
+
return True
|
|
125
|
+
if self._level in ("server", "history"):
|
|
126
|
+
self._level = "servers"
|
|
127
|
+
self._server = None
|
|
128
|
+
self._scroll = 0
|
|
129
|
+
self._message = ""
|
|
130
|
+
return True
|
|
131
|
+
return False
|
|
132
|
+
|
|
133
|
+
def activate(self) -> McpPanelAction | None:
|
|
134
|
+
"""Enter:进入下一层,或返回需要运行时执行的动作。"""
|
|
135
|
+
row = self._current_row()
|
|
136
|
+
if row is None:
|
|
137
|
+
return None
|
|
138
|
+
if self._level == "servers" and row.kind == "server":
|
|
139
|
+
self._server = row.value
|
|
140
|
+
self._level = "server"
|
|
141
|
+
# 默认落在第一个工具上:进入详情后按 Enter 打开 Schema,
|
|
142
|
+
# 不会误触顶部的断开与重连动作。
|
|
143
|
+
self._cursor = _ACTION_ROWS if len(self._rows()) > _ACTION_ROWS else 0
|
|
144
|
+
self._message = ""
|
|
145
|
+
return None
|
|
146
|
+
if self._level != "server":
|
|
147
|
+
return None
|
|
148
|
+
if row.kind == "tool":
|
|
149
|
+
self._tool = row.value
|
|
150
|
+
self._level = "schema"
|
|
151
|
+
self._scroll = 0
|
|
152
|
+
self._message = ""
|
|
153
|
+
return None
|
|
154
|
+
match row.value:
|
|
155
|
+
case "toggle":
|
|
156
|
+
return McpPanelAction("toggle", self._server)
|
|
157
|
+
case "reconnect":
|
|
158
|
+
return McpPanelAction("reconnect", self._server)
|
|
159
|
+
case "refresh":
|
|
160
|
+
return McpPanelAction("refresh", self._server)
|
|
161
|
+
case "history":
|
|
162
|
+
self._level = "history"
|
|
163
|
+
self._scroll = 0
|
|
164
|
+
self._message = ""
|
|
165
|
+
return None
|
|
166
|
+
case "back":
|
|
167
|
+
self.back()
|
|
168
|
+
case _:
|
|
169
|
+
pass
|
|
170
|
+
return None
|
|
171
|
+
|
|
172
|
+
def shortcut(self, key: str) -> McpPanelAction | None:
|
|
173
|
+
"""单键操作。返回动作时由 TUI 异步执行,其余情况面板已就地更新。"""
|
|
174
|
+
if self._runtime is None:
|
|
175
|
+
return None
|
|
176
|
+
if key == "L":
|
|
177
|
+
return McpPanelAction("reload")
|
|
178
|
+
if self._level == "schema":
|
|
179
|
+
if key == "l":
|
|
180
|
+
self._load(self._tool)
|
|
181
|
+
return None
|
|
182
|
+
if self._level == "history":
|
|
183
|
+
return None
|
|
184
|
+
server = self._active_server()
|
|
185
|
+
if server is None:
|
|
186
|
+
return None
|
|
187
|
+
match key:
|
|
188
|
+
case "e":
|
|
189
|
+
return McpPanelAction("toggle", server)
|
|
190
|
+
case "r":
|
|
191
|
+
return McpPanelAction("reconnect", server)
|
|
192
|
+
case "f":
|
|
193
|
+
return McpPanelAction("refresh", server)
|
|
194
|
+
case "h":
|
|
195
|
+
self._level = "history"
|
|
196
|
+
self._server = server
|
|
197
|
+
self._scroll = 0
|
|
198
|
+
self._message = ""
|
|
199
|
+
return None
|
|
200
|
+
case "l":
|
|
201
|
+
row = self._current_row()
|
|
202
|
+
if row is not None and row.kind == "tool":
|
|
203
|
+
self._load(row.value)
|
|
204
|
+
case _:
|
|
205
|
+
pass
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
def set_message(self, text: str) -> None:
|
|
209
|
+
self._message = text
|
|
210
|
+
|
|
211
|
+
def refresh(self) -> None:
|
|
212
|
+
"""配置重载或连接状态变化后,丢弃已经不存在的服务器与工具。"""
|
|
213
|
+
if self._runtime is None:
|
|
214
|
+
self._level = "servers"
|
|
215
|
+
self._server = None
|
|
216
|
+
self._tool = None
|
|
217
|
+
return
|
|
218
|
+
names = {status.name for status in self._runtime.statuses()}
|
|
219
|
+
if self._server is not None and self._server not in names:
|
|
220
|
+
self._level = "servers"
|
|
221
|
+
self._server = None
|
|
222
|
+
self._tool = None
|
|
223
|
+
if self._tool is not None and self._runtime.catalog.get(self._tool) is None:
|
|
224
|
+
self._level = "server" if self._level == "schema" else self._level
|
|
225
|
+
self._tool = None
|
|
226
|
+
self._cursor = min(self._cursor, max(0, len(self._rows()) - 1))
|
|
227
|
+
self._scroll = max(0, self._scroll)
|
|
228
|
+
|
|
229
|
+
def _active_server(self) -> str | None:
|
|
230
|
+
if self._level == "server":
|
|
231
|
+
return self._server
|
|
232
|
+
row = self._current_row()
|
|
233
|
+
if row is not None and row.kind == "server":
|
|
234
|
+
return row.value
|
|
235
|
+
return None
|
|
236
|
+
|
|
237
|
+
def _load(self, provider_name: str | None) -> None:
|
|
238
|
+
if provider_name is None or self._runtime is None:
|
|
239
|
+
return
|
|
240
|
+
entry = self._runtime.catalog.get(provider_name)
|
|
241
|
+
if entry is None:
|
|
242
|
+
self._message = f"未知工具:{provider_name}"
|
|
243
|
+
return
|
|
244
|
+
if entry.loading == "eager":
|
|
245
|
+
self._message = f"{provider_name} 是预加载工具,已经可用"
|
|
246
|
+
return
|
|
247
|
+
self._runtime.load_tool(provider_name)
|
|
248
|
+
self._message = f"已载入 {provider_name},下一回合模型可见"
|
|
249
|
+
|
|
250
|
+
def _current_row(self) -> _Row | None:
|
|
251
|
+
rows = self._rows()
|
|
252
|
+
if not rows:
|
|
253
|
+
return None
|
|
254
|
+
return rows[min(self._cursor, len(rows) - 1)]
|
|
255
|
+
|
|
256
|
+
def _body(self) -> tuple[list[str], int]:
|
|
257
|
+
runtime = self._runtime
|
|
258
|
+
if runtime is None:
|
|
259
|
+
return (
|
|
260
|
+
[
|
|
261
|
+
"没有配置 MCP 服务器。",
|
|
262
|
+
"",
|
|
263
|
+
"在 ~/.braid/mcp.json 或 <工作目录>/.braid/mcp.json 添加服务器,",
|
|
264
|
+
"再用 `braid mcp reload` 或重启会话。",
|
|
265
|
+
],
|
|
266
|
+
-1,
|
|
267
|
+
)
|
|
268
|
+
if self._level == "schema":
|
|
269
|
+
return self._schema_body()
|
|
270
|
+
if self._level == "history":
|
|
271
|
+
return self._history_body()
|
|
272
|
+
rows = self._rows()
|
|
273
|
+
header = self._header()
|
|
274
|
+
if not rows:
|
|
275
|
+
return [*header, " 没有可选项"], -1
|
|
276
|
+
index = min(self._cursor, len(rows) - 1)
|
|
277
|
+
if self._level == "server":
|
|
278
|
+
actions = rows[:_ACTION_ROWS]
|
|
279
|
+
tools = rows[_ACTION_ROWS:]
|
|
280
|
+
body = [
|
|
281
|
+
*header,
|
|
282
|
+
"动作",
|
|
283
|
+
*(row.label for row in actions),
|
|
284
|
+
"",
|
|
285
|
+
f"工具({len(tools)})",
|
|
286
|
+
*(row.label for row in tools),
|
|
287
|
+
]
|
|
288
|
+
if index < _ACTION_ROWS:
|
|
289
|
+
selected = len(header) + 1 + index
|
|
290
|
+
else:
|
|
291
|
+
selected = len(header) + 1 + _ACTION_ROWS + 2 + (index - _ACTION_ROWS)
|
|
292
|
+
return body, selected
|
|
293
|
+
return [*header, *(row.label for row in rows)], len(header) + index
|
|
294
|
+
|
|
295
|
+
def _header(self) -> list[str]:
|
|
296
|
+
runtime = self._runtime
|
|
297
|
+
if runtime is None:
|
|
298
|
+
return []
|
|
299
|
+
if self._level == "servers":
|
|
300
|
+
statuses = runtime.statuses()
|
|
301
|
+
lazy = sum(1 for entry in runtime.catalog.entries if entry.loading == "lazy")
|
|
302
|
+
return [
|
|
303
|
+
f"{len(statuses)} 个服务器 · 默认加载 {runtime.settings.loading} · "
|
|
304
|
+
f"工具 {len(runtime.catalog.entries)} 个(延迟 {lazy})",
|
|
305
|
+
"",
|
|
306
|
+
]
|
|
307
|
+
server = self._server
|
|
308
|
+
if server is None:
|
|
309
|
+
return []
|
|
310
|
+
status = runtime.status(server)
|
|
311
|
+
connection = runtime.connection(server)
|
|
312
|
+
config = connection.config
|
|
313
|
+
lines = [
|
|
314
|
+
f"{status.name} [{status.transport}] {status.state}",
|
|
315
|
+
f"地址:{config.endpoint}",
|
|
316
|
+
f"启用:{'是' if config.enabled else '否'} · "
|
|
317
|
+
f"信任:{'是' if config.trusted else '否'} · "
|
|
318
|
+
f"调用超时 {connection.call_timeout_s:g} 秒",
|
|
319
|
+
f"工具 {status.tool_count} · 资源 {status.resource_count} · "
|
|
320
|
+
f"提示词 {status.prompt_count}",
|
|
321
|
+
]
|
|
322
|
+
if status.error:
|
|
323
|
+
lines.append(f"最近错误:{_one_line(status.error)}")
|
|
324
|
+
if status.state == "needs_auth":
|
|
325
|
+
lines.append(f"认证:在终端运行 braid mcp login {status.name}")
|
|
326
|
+
lines.append("")
|
|
327
|
+
return lines
|
|
328
|
+
|
|
329
|
+
def _schema_body(self) -> tuple[list[str], int]:
|
|
330
|
+
runtime = self._runtime
|
|
331
|
+
assert runtime is not None
|
|
332
|
+
entry = runtime.catalog.get(self._tool) if self._tool else None
|
|
333
|
+
if entry is None:
|
|
334
|
+
return [f"未知工具:{self._tool or '(未选择)'}"], -1
|
|
335
|
+
loaded = entry.provider_name in runtime.loaded_tools
|
|
336
|
+
lines = [
|
|
337
|
+
entry.provider_name,
|
|
338
|
+
f"服务器:{entry.server} · 远端名称:{entry.tool.name} · "
|
|
339
|
+
f"加载:{entry.loading} · 已载入:{'是' if loaded else '否'}",
|
|
340
|
+
"",
|
|
341
|
+
entry.tool.description or "(没有描述)",
|
|
342
|
+
"",
|
|
343
|
+
"参数 Schema:",
|
|
344
|
+
]
|
|
345
|
+
lines.extend(json.dumps(entry.tool.input_schema, ensure_ascii=False, indent=2).splitlines())
|
|
346
|
+
tokens = estimate_tokens(json.dumps(entry.tool.input_schema, ensure_ascii=False))
|
|
347
|
+
lines.extend(("", f"Schema 约 {tokens} Token"))
|
|
348
|
+
return lines, -1
|
|
349
|
+
|
|
350
|
+
def _history_body(self) -> tuple[list[str], int]:
|
|
351
|
+
runtime = self._runtime
|
|
352
|
+
assert runtime is not None
|
|
353
|
+
records = runtime.history()
|
|
354
|
+
if self._server is not None and self._level == "history":
|
|
355
|
+
records = [record for record in records if record.server == self._server]
|
|
356
|
+
if not records:
|
|
357
|
+
return ["还没有工具调用记录"], -1
|
|
358
|
+
lines = [f"最近的 MCP 调用({len(records)} 条)", ""]
|
|
359
|
+
for record in records:
|
|
360
|
+
marker = "错误" if record.is_error else "完成"
|
|
361
|
+
lines.append(
|
|
362
|
+
f"{record.at} {record.server}/{record.tool} {marker} "
|
|
363
|
+
f"{record.duration_ms:.0f} 毫秒"
|
|
364
|
+
)
|
|
365
|
+
lines.append(f" 参数:{_one_line(record.arguments)}")
|
|
366
|
+
lines.append(f" 结果:{_one_line(record.result)}")
|
|
367
|
+
lines.append("")
|
|
368
|
+
return lines[:-1], -1
|
|
369
|
+
|
|
370
|
+
def _rows(self) -> list[_Row]:
|
|
371
|
+
runtime = self._runtime
|
|
372
|
+
if runtime is None:
|
|
373
|
+
return []
|
|
374
|
+
if self._level == "servers":
|
|
375
|
+
return [
|
|
376
|
+
_Row("server", _server_line(status), status.name) for status in runtime.statuses()
|
|
377
|
+
]
|
|
378
|
+
if self._level == "server" and self._server is not None:
|
|
379
|
+
status = runtime.status(self._server)
|
|
380
|
+
rows = [
|
|
381
|
+
_Row(
|
|
382
|
+
"action",
|
|
383
|
+
"启用并连接" if status.state == "disabled" else "断开并禁用",
|
|
384
|
+
"toggle",
|
|
385
|
+
),
|
|
386
|
+
_Row("action", "重新连接", "reconnect"),
|
|
387
|
+
_Row("action", "刷新能力", "refresh"),
|
|
388
|
+
_Row("action", "查看调用历史", "history"),
|
|
389
|
+
_Row("action", "返回服务器列表", "back"),
|
|
390
|
+
]
|
|
391
|
+
loaded = runtime.loaded_tools
|
|
392
|
+
rows.extend(
|
|
393
|
+
_Row(
|
|
394
|
+
"tool",
|
|
395
|
+
_tool_line(entry, loaded=entry.provider_name in loaded),
|
|
396
|
+
entry.provider_name,
|
|
397
|
+
)
|
|
398
|
+
for entry in runtime.catalog.by_server(self._server)
|
|
399
|
+
)
|
|
400
|
+
return rows
|
|
401
|
+
return []
|
|
402
|
+
|
|
403
|
+
def _title(self) -> str:
|
|
404
|
+
if self._level == "server":
|
|
405
|
+
return f"MCP 服务器 · {self._server}"
|
|
406
|
+
if self._level == "schema":
|
|
407
|
+
entry = self._runtime.catalog.get(self._tool) if self._runtime and self._tool else None
|
|
408
|
+
return f"MCP 工具 · {entry.tool.name if entry is not None else self._tool}"
|
|
409
|
+
if self._level == "history":
|
|
410
|
+
return f"MCP 调用历史 · {self._server}" if self._server else "MCP 调用历史"
|
|
411
|
+
return "MCP 服务器"
|
|
412
|
+
|
|
413
|
+
def _hint(self) -> str:
|
|
414
|
+
if self._level == "servers":
|
|
415
|
+
return "↑↓ 移动 · Enter 详情 · e 启停 · r 重连 · f 刷新 · h 历史 · L 重载 · Esc 关闭"
|
|
416
|
+
if self._level == "server":
|
|
417
|
+
return "↑↓ 移动 · Enter 执行 · e 启停 · r 重连 · f 刷新 · h 历史 · l 载入 · Esc 返回"
|
|
418
|
+
if self._level == "schema":
|
|
419
|
+
return "↑↓ 滚动 · PgUp/PgDn 翻页 · l 载入 · Esc 返回"
|
|
420
|
+
return "↑↓ 滚动 · PgUp/PgDn 翻页 · Esc 返回"
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _server_line(status: McpServerStatus) -> str:
|
|
424
|
+
error = " · 最近错误" if status.error else ""
|
|
425
|
+
return (
|
|
426
|
+
f"{status.name:<16} {status.transport:<5} {status.state:<12} "
|
|
427
|
+
f"{status.tool_count:>2} 工具{error}"
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _tool_line(entry: ToolEntry, *, loaded: bool) -> str:
|
|
432
|
+
marks = [entry.loading]
|
|
433
|
+
if entry.loading == "lazy":
|
|
434
|
+
marks.append("已载入" if loaded else "未载入")
|
|
435
|
+
description = _one_line(entry.tool.description or "")
|
|
436
|
+
suffix = f" — {description}" if description else ""
|
|
437
|
+
return f" {entry.provider_name} [{' · '.join(marks)}]{suffix}"
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _one_line(text: str) -> str:
|
|
441
|
+
return " ".join(text.split())
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
__all__ = ["McpPanel", "McpPanelAction", "McpPanelLevel", "McpPanelView"]
|