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,142 @@
|
|
|
1
|
+
"""``mcp.json`` 的写入:``braid mcp add`` 与 ``braid mcp remove`` 共用。
|
|
2
|
+
|
|
3
|
+
读取侧在 :mod:`.config`:它把两个文件合并成有效配置,并把单条错误降级成诊断。
|
|
4
|
+
写入侧必须保留文件里其它客户端认识的字段,因此这里只改 ``mcpServers`` 下的一项,
|
|
5
|
+
其余顶层键原样写回。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Literal
|
|
15
|
+
|
|
16
|
+
from braid_ai.types import JsonValue
|
|
17
|
+
from braid_coding_agent.mcp.config import GLOBAL_CONFIG_NAME, PROJECT_CONFIG_DIR
|
|
18
|
+
|
|
19
|
+
type McpScope = Literal["global", "project"]
|
|
20
|
+
|
|
21
|
+
SERVERS_KEY = "mcpServers"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ConfigStoreError(ValueError):
|
|
25
|
+
"""配置文件无法读取或写入。消息带路径。"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(slots=True, frozen=True)
|
|
29
|
+
class ScopeDocument:
|
|
30
|
+
"""一个作用域的原始文档与它的 ``mcpServers``。"""
|
|
31
|
+
|
|
32
|
+
scope: McpScope
|
|
33
|
+
path: Path
|
|
34
|
+
servers: dict[str, JsonValue]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def config_path(agent_dir: Path, cwd: str, scope: McpScope) -> Path:
|
|
38
|
+
"""全局写 ``~/.braid/mcp.json``,项目写 ``<cwd>/.braid/mcp.json``。"""
|
|
39
|
+
if scope == "global":
|
|
40
|
+
return agent_dir / GLOBAL_CONFIG_NAME
|
|
41
|
+
if scope == "project":
|
|
42
|
+
return Path(cwd) / PROJECT_CONFIG_DIR / GLOBAL_CONFIG_NAME
|
|
43
|
+
raise ConfigStoreError(f"未知作用域: {scope}(可用: global / project)")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def read_document(path: Path) -> dict[str, JsonValue]:
|
|
47
|
+
"""读取整个文档。文件不存在时返回一份空文档。"""
|
|
48
|
+
if not path.is_file():
|
|
49
|
+
return {SERVERS_KEY: {}}
|
|
50
|
+
try:
|
|
51
|
+
payload: JsonValue = json.loads(path.read_text(encoding="utf-8-sig"))
|
|
52
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
53
|
+
raise ConfigStoreError(f"{path}: 无法读取 MCP 配置:{exc}") from exc
|
|
54
|
+
if not isinstance(payload, dict):
|
|
55
|
+
raise ConfigStoreError(f"{path}: MCP 配置必须是 JSON 对象")
|
|
56
|
+
raw_servers = payload.get(SERVERS_KEY, {})
|
|
57
|
+
if not isinstance(raw_servers, dict):
|
|
58
|
+
raise ConfigStoreError(f"{path}: {SERVERS_KEY} 必须是 JSON 对象")
|
|
59
|
+
payload[SERVERS_KEY] = raw_servers
|
|
60
|
+
return payload
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def write_document(path: Path, document: dict[str, JsonValue]) -> None:
|
|
64
|
+
"""原子写入。文件里有请求头或客户端密钥,权限收成 0600。"""
|
|
65
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
66
|
+
temporary = path.with_name(path.name + ".tmp")
|
|
67
|
+
body = json.dumps(document, ensure_ascii=False, indent=2) + "\n"
|
|
68
|
+
try:
|
|
69
|
+
temporary.write_text(body, encoding="utf-8")
|
|
70
|
+
os.replace(temporary, path)
|
|
71
|
+
path.chmod(0o600)
|
|
72
|
+
except OSError as exc:
|
|
73
|
+
temporary.unlink(missing_ok=True)
|
|
74
|
+
raise ConfigStoreError(f"{path}: 无法写入 MCP 配置:{exc}") from exc
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def upsert_server(
|
|
78
|
+
agent_dir: Path,
|
|
79
|
+
cwd: str,
|
|
80
|
+
scope: McpScope,
|
|
81
|
+
name: str,
|
|
82
|
+
entry: dict[str, JsonValue],
|
|
83
|
+
*,
|
|
84
|
+
replace: bool,
|
|
85
|
+
) -> Path:
|
|
86
|
+
"""写入或替换一个服务器条目,返回文件路径。"""
|
|
87
|
+
path = config_path(agent_dir, cwd, scope)
|
|
88
|
+
document = read_document(path)
|
|
89
|
+
servers = _servers(document, path)
|
|
90
|
+
if name in servers and not replace:
|
|
91
|
+
raise ConfigStoreError(f"{path} 里已存在服务器 {name};要覆盖请加 --force")
|
|
92
|
+
servers[name] = entry
|
|
93
|
+
write_document(path, document)
|
|
94
|
+
return path
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def remove_server(agent_dir: Path, cwd: str, scope: McpScope, name: str) -> bool:
|
|
98
|
+
"""删除一个条目。文件或条目不存在时返回 ``False``。"""
|
|
99
|
+
path = config_path(agent_dir, cwd, scope)
|
|
100
|
+
if not path.is_file():
|
|
101
|
+
return False
|
|
102
|
+
document = read_document(path)
|
|
103
|
+
servers = _servers(document, path)
|
|
104
|
+
if name not in servers:
|
|
105
|
+
return False
|
|
106
|
+
del servers[name]
|
|
107
|
+
write_document(path, document)
|
|
108
|
+
return True
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def read_scope_documents(agent_dir: Path, cwd: str) -> list[ScopeDocument]:
|
|
112
|
+
"""按全局、项目的顺序读取两份文档;不存在的文件跳过。"""
|
|
113
|
+
documents: list[ScopeDocument] = []
|
|
114
|
+
for scope in ("global", "project"):
|
|
115
|
+
path = config_path(agent_dir, cwd, scope)
|
|
116
|
+
if not path.is_file():
|
|
117
|
+
continue
|
|
118
|
+
documents.append(
|
|
119
|
+
ScopeDocument(scope=scope, path=path, servers=_servers(read_document(path), path))
|
|
120
|
+
)
|
|
121
|
+
return documents
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _servers(document: dict[str, JsonValue], path: Path) -> dict[str, JsonValue]:
|
|
125
|
+
raw = document.get(SERVERS_KEY, {})
|
|
126
|
+
if not isinstance(raw, dict):
|
|
127
|
+
raise ConfigStoreError(f"{path}: {SERVERS_KEY} 必须是 JSON 对象")
|
|
128
|
+
return raw
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
__all__ = [
|
|
132
|
+
"SERVERS_KEY",
|
|
133
|
+
"ConfigStoreError",
|
|
134
|
+
"McpScope",
|
|
135
|
+
"ScopeDocument",
|
|
136
|
+
"config_path",
|
|
137
|
+
"read_document",
|
|
138
|
+
"read_scope_documents",
|
|
139
|
+
"remove_server",
|
|
140
|
+
"upsert_server",
|
|
141
|
+
"write_document",
|
|
142
|
+
]
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""MCP 调用记录:``/mcp history`` 与 TUI 面板读取的有界历史。
|
|
2
|
+
|
|
3
|
+
记录只保存参数与结果的摘要。完整结果可能很大,也可能含外部服务返回的敏感内容;
|
|
4
|
+
排查"为什么这次调用超时"不需要把它们整份复制进内存。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from collections import deque
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
|
|
14
|
+
from braid_ai.types import JsonValue
|
|
15
|
+
|
|
16
|
+
#: 摘要长度上限。
|
|
17
|
+
ARGUMENT_SUMMARY_CHARS = 500
|
|
18
|
+
RESULT_SUMMARY_CHARS = 300
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(slots=True, frozen=True)
|
|
22
|
+
class CallRecord:
|
|
23
|
+
"""一次工具调用。``duration_ms`` 从参数校验之后开始计时。"""
|
|
24
|
+
|
|
25
|
+
server: str
|
|
26
|
+
tool: str
|
|
27
|
+
arguments: str
|
|
28
|
+
result: str
|
|
29
|
+
duration_ms: float
|
|
30
|
+
is_error: bool
|
|
31
|
+
at: str
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class CallInspector:
|
|
35
|
+
"""进程级的有界调用历史。"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, limit: int = 50) -> None:
|
|
38
|
+
self._records: deque[CallRecord] = deque(maxlen=limit)
|
|
39
|
+
|
|
40
|
+
def record(
|
|
41
|
+
self,
|
|
42
|
+
*,
|
|
43
|
+
server: str,
|
|
44
|
+
tool: str,
|
|
45
|
+
arguments: JsonValue,
|
|
46
|
+
result: str,
|
|
47
|
+
duration_ms: float,
|
|
48
|
+
is_error: bool,
|
|
49
|
+
) -> None:
|
|
50
|
+
self._records.append(
|
|
51
|
+
CallRecord(
|
|
52
|
+
server=server,
|
|
53
|
+
tool=tool,
|
|
54
|
+
arguments=_summarize(arguments, ARGUMENT_SUMMARY_CHARS),
|
|
55
|
+
result=_summarize_text(result, RESULT_SUMMARY_CHARS),
|
|
56
|
+
duration_ms=duration_ms,
|
|
57
|
+
is_error=is_error,
|
|
58
|
+
at=datetime.now().astimezone().isoformat(timespec="seconds"),
|
|
59
|
+
)
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
def recent(self, limit: int | None = None) -> list[CallRecord]:
|
|
63
|
+
records = list(self._records)
|
|
64
|
+
if limit is not None:
|
|
65
|
+
records = records[-limit:]
|
|
66
|
+
return records
|
|
67
|
+
|
|
68
|
+
def clear(self) -> None:
|
|
69
|
+
self._records.clear()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _summarize(value: JsonValue, limit: int) -> str:
|
|
73
|
+
try:
|
|
74
|
+
text = json.dumps(value, ensure_ascii=False, sort_keys=True)
|
|
75
|
+
except (TypeError, ValueError):
|
|
76
|
+
text = str(value)
|
|
77
|
+
return _summarize_text(text, limit)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _summarize_text(text: str, limit: int) -> str:
|
|
81
|
+
collapsed = " ".join(text.split())
|
|
82
|
+
return collapsed if len(collapsed) <= limit else collapsed[:limit] + "…"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
__all__: list[str] = ["CallInspector", "CallRecord"]
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""``/mcp`` 面板:查看服务器状态、工具 Schema、调用历史与管理连接。
|
|
2
|
+
|
|
3
|
+
面板是一组纯文本行。REPL 直接逐行打印,TUI 交给 Markdown 渲染器;两条路径
|
|
4
|
+
共用同一份格式化逻辑,避免同一个状态在两种界面里显示成不同的样子。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
from braid_coding_agent.mcp.catalog import ToolEntry, estimate_tokens
|
|
12
|
+
from braid_coding_agent.mcp.runtime import McpRuntime, McpServerStatus
|
|
13
|
+
|
|
14
|
+
USAGE = """用法:/mcp [子命令]
|
|
15
|
+
/mcp 服务器状态与工具数量
|
|
16
|
+
/mcp show <服务器> 配置、能力与最近错误
|
|
17
|
+
/mcp tools [服务器] 工具目录与加载方式
|
|
18
|
+
/mcp schema <工具> 完整参数 Schema
|
|
19
|
+
/mcp load <工具> 载入一个延迟加载的工具
|
|
20
|
+
/mcp history [条数] 最近的工具调用
|
|
21
|
+
/mcp enable <服务器> 连接并启用
|
|
22
|
+
/mcp disable <服务器> 断开并撤下工具
|
|
23
|
+
/mcp reconnect <服务器> 断开后重新连接
|
|
24
|
+
/mcp refresh <服务器> 重新发现工具、资源与提示词
|
|
25
|
+
/mcp reload 重新读取两份 mcp.json 并重连"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
async def run_panel(runtime: McpRuntime | None, args: str) -> str:
|
|
29
|
+
"""执行一条 ``/mcp`` 命令并返回要显示的文本。"""
|
|
30
|
+
if runtime is None:
|
|
31
|
+
return "没有配置 MCP 服务器(~/.braid/mcp.json 或 <工作目录>/.braid/mcp.json)"
|
|
32
|
+
words = args.split()
|
|
33
|
+
if not words:
|
|
34
|
+
return render_overview(runtime)
|
|
35
|
+
verb, rest = words[0], words[1:]
|
|
36
|
+
if verb in ("list", "status"):
|
|
37
|
+
return render_overview(runtime)
|
|
38
|
+
if verb == "show":
|
|
39
|
+
if not rest:
|
|
40
|
+
return "用法:/mcp show <服务器>"
|
|
41
|
+
return render_server(runtime, rest[0])
|
|
42
|
+
if verb == "tools":
|
|
43
|
+
return render_tools(runtime, rest[0] if rest else None)
|
|
44
|
+
if verb == "schema":
|
|
45
|
+
if not rest:
|
|
46
|
+
return "用法:/mcp schema <工具名>"
|
|
47
|
+
return render_schema(runtime, rest[0])
|
|
48
|
+
if verb == "load":
|
|
49
|
+
if not rest:
|
|
50
|
+
return "用法:/mcp load <工具名>"
|
|
51
|
+
try:
|
|
52
|
+
entry = runtime.load_tool(rest[0])
|
|
53
|
+
except KeyError as error:
|
|
54
|
+
return _key_error(error)
|
|
55
|
+
return f"已载入 {entry.provider_name}({entry.server} / {entry.tool.name})"
|
|
56
|
+
if verb == "history":
|
|
57
|
+
limit: int | None = None
|
|
58
|
+
if rest:
|
|
59
|
+
try:
|
|
60
|
+
limit = max(1, int(rest[0]))
|
|
61
|
+
except ValueError:
|
|
62
|
+
return "用法:/mcp history [条数]"
|
|
63
|
+
return render_history(runtime, limit)
|
|
64
|
+
if verb in ("enable", "disable", "reconnect", "refresh"):
|
|
65
|
+
if not rest:
|
|
66
|
+
return f"用法:/mcp {verb} <服务器>"
|
|
67
|
+
try:
|
|
68
|
+
status = await getattr(runtime, verb)(rest[0])
|
|
69
|
+
except KeyError as error:
|
|
70
|
+
return _key_error(error)
|
|
71
|
+
return _status_line(status) + _error_line(status)
|
|
72
|
+
if verb == "reload":
|
|
73
|
+
await runtime.reload()
|
|
74
|
+
return "已重新读取配置。\n\n" + render_overview(runtime)
|
|
75
|
+
return USAGE
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def render_overview(runtime: McpRuntime) -> str:
|
|
79
|
+
"""服务器列表、状态与目录规模。"""
|
|
80
|
+
statuses = runtime.statuses()
|
|
81
|
+
if not statuses:
|
|
82
|
+
return "没有配置 MCP 服务器(~/.braid/mcp.json 或 <工作目录>/.braid/mcp.json)"
|
|
83
|
+
settings = runtime.settings
|
|
84
|
+
loaded = runtime.loaded_tools
|
|
85
|
+
lazy = [entry for entry in runtime.catalog.entries if entry.loading == "lazy"]
|
|
86
|
+
eager = [entry for entry in runtime.catalog.entries if entry.loading == "eager"]
|
|
87
|
+
lines = [
|
|
88
|
+
f"MCP 服务器({len(statuses)} 个)",
|
|
89
|
+
f"加载:默认 {settings.loading} · 延迟目录预算 {settings.tool_token_budget} Token",
|
|
90
|
+
f"目录:{len(eager)} 个预加载 · {len(lazy)} 个延迟加载 · 已载入 {len(loaded)} 个延迟工具",
|
|
91
|
+
"",
|
|
92
|
+
]
|
|
93
|
+
for status in statuses:
|
|
94
|
+
lines.append(_status_line(status))
|
|
95
|
+
lines.append(
|
|
96
|
+
f" 工具 {status.tool_count} · 资源 {status.resource_count} · "
|
|
97
|
+
f"提示词 {status.prompt_count} · 延迟已载入 {status.loaded_tools}"
|
|
98
|
+
)
|
|
99
|
+
if status.error:
|
|
100
|
+
lines.append(f" 最近错误:{_one_line(status.error)}")
|
|
101
|
+
lines.extend(("", "工具名形如 mcp__<服务器>__<工具>;/mcp schema 查看参数。"))
|
|
102
|
+
return "\n".join(lines)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def render_server(runtime: McpRuntime, name: str) -> str:
|
|
106
|
+
"""单个服务器的配置、能力与工具清单。"""
|
|
107
|
+
try:
|
|
108
|
+
status = runtime.status(name)
|
|
109
|
+
connection = runtime.connection(name)
|
|
110
|
+
except KeyError as error:
|
|
111
|
+
return _key_error(error)
|
|
112
|
+
config = connection.config
|
|
113
|
+
lines = [
|
|
114
|
+
f"{status.name} [{status.transport}] {status.state}",
|
|
115
|
+
f" 地址:{config.endpoint}",
|
|
116
|
+
f" 启用:{'是' if config.enabled else '否'} · "
|
|
117
|
+
f"信任:{'是' if config.trusted else '否'} · "
|
|
118
|
+
f"超时:调用 {connection.call_timeout_s:g} 秒",
|
|
119
|
+
_capabilities_line(connection.capabilities),
|
|
120
|
+
_instructions_line(connection.instructions),
|
|
121
|
+
]
|
|
122
|
+
if status.error:
|
|
123
|
+
lines.append(f" 最近错误:{_one_line(status.error)}")
|
|
124
|
+
catalogue = runtime.catalog.by_server(name)
|
|
125
|
+
if catalogue:
|
|
126
|
+
lines.extend(("", "工具:"))
|
|
127
|
+
for entry in catalogue:
|
|
128
|
+
lines.append(_tool_line(entry, loaded=entry.provider_name in runtime.loaded_tools))
|
|
129
|
+
else:
|
|
130
|
+
lines.extend(("", "工具:无"))
|
|
131
|
+
if status.resource_count:
|
|
132
|
+
lines.extend(("", "资源:" + ", ".join(resource.uri for resource in connection.resources)))
|
|
133
|
+
if status.prompt_count:
|
|
134
|
+
lines.extend(("", "提示词:" + ", ".join(prompt.name for prompt in connection.prompts)))
|
|
135
|
+
return "\n".join(lines)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def render_tools(runtime: McpRuntime, server: str | None = None) -> str:
|
|
139
|
+
"""按服务器列出工具目录。"""
|
|
140
|
+
entries = runtime.catalog.by_server(server) if server else runtime.catalog.entries
|
|
141
|
+
if not entries:
|
|
142
|
+
if server:
|
|
143
|
+
return f"{server} 没有发现工具"
|
|
144
|
+
return "还没有发现工具,先连接服务器或用 /mcp reload 重试"
|
|
145
|
+
lines = [f"MCP 工具({len(entries)} 个)"]
|
|
146
|
+
current = ""
|
|
147
|
+
for entry in entries:
|
|
148
|
+
if entry.server != current:
|
|
149
|
+
current = entry.server
|
|
150
|
+
lines.extend(("", f"[{current}]"))
|
|
151
|
+
lines.append(_tool_line(entry, loaded=entry.provider_name in runtime.loaded_tools))
|
|
152
|
+
return "\n".join(lines)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def render_schema(runtime: McpRuntime, query: str) -> str:
|
|
156
|
+
"""打印工具完整说明与 JSON Schema。"""
|
|
157
|
+
entry = _resolve_tool(runtime, query)
|
|
158
|
+
if isinstance(entry, str):
|
|
159
|
+
return entry
|
|
160
|
+
schema = entry.tool.input_schema
|
|
161
|
+
lines = [
|
|
162
|
+
f"{entry.provider_name}",
|
|
163
|
+
f"服务器:{entry.server} · 远端名称:{entry.tool.name} · "
|
|
164
|
+
f"加载:{entry.loading} · "
|
|
165
|
+
f"已载入:{'是' if entry.provider_name in runtime.loaded_tools else '否'}",
|
|
166
|
+
"",
|
|
167
|
+
entry.tool.description or "(没有描述)",
|
|
168
|
+
"",
|
|
169
|
+
"参数 Schema:",
|
|
170
|
+
json.dumps(schema, ensure_ascii=False, indent=2),
|
|
171
|
+
]
|
|
172
|
+
return "\n".join(lines)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def render_history(runtime: McpRuntime, limit: int | None = None) -> str:
|
|
176
|
+
"""最近的工具调用、耗时与结果摘要。"""
|
|
177
|
+
records = runtime.history(limit)
|
|
178
|
+
if not records:
|
|
179
|
+
return "还没有工具调用记录"
|
|
180
|
+
lines = [f"最近的 MCP 调用({len(records)} 条)"]
|
|
181
|
+
for record in records:
|
|
182
|
+
marker = "错误" if record.is_error else "完成"
|
|
183
|
+
lines.append(
|
|
184
|
+
f" {record.at} {record.server}/{record.tool} {marker} {record.duration_ms:.0f} 毫秒"
|
|
185
|
+
)
|
|
186
|
+
lines.append(f" 参数:{record.arguments}")
|
|
187
|
+
lines.append(f" 结果:{_one_line(record.result)}")
|
|
188
|
+
return "\n".join(lines)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _resolve_tool(runtime: McpRuntime, query: str) -> ToolEntry | str:
|
|
192
|
+
entry = runtime.catalog.get(query)
|
|
193
|
+
if entry is not None:
|
|
194
|
+
return entry
|
|
195
|
+
server, _, tool = query.partition(":")
|
|
196
|
+
if tool:
|
|
197
|
+
for candidate in runtime.catalog.by_server(server):
|
|
198
|
+
if candidate.tool.name == tool:
|
|
199
|
+
return candidate
|
|
200
|
+
matches = [item for item in runtime.catalog.entries if item.tool.name == query]
|
|
201
|
+
if len(matches) == 1:
|
|
202
|
+
return matches[0]
|
|
203
|
+
if len(matches) > 1:
|
|
204
|
+
names = ", ".join(item.provider_name for item in matches)
|
|
205
|
+
return f"有多个工具叫 {query}:{names};请用完整工具名"
|
|
206
|
+
return f"未知 MCP 工具: {query}"
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _status_line(status: McpServerStatus) -> str:
|
|
210
|
+
return f" {status.name:<18} {status.transport:<5} {status.state}"
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _error_line(status: McpServerStatus) -> str:
|
|
214
|
+
return f"\n 最近错误:{_one_line(status.error)}" if status.error else ""
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _tool_line(entry: ToolEntry, *, loaded: bool) -> str:
|
|
218
|
+
marks = [entry.loading]
|
|
219
|
+
if entry.loading == "lazy":
|
|
220
|
+
marks.append("已载入" if loaded else "未载入")
|
|
221
|
+
schema_tokens = estimate_tokens(json.dumps(entry.tool.input_schema, ensure_ascii=False))
|
|
222
|
+
marks.append(f"约 {schema_tokens} Token")
|
|
223
|
+
description = _one_line(entry.tool.description or "")
|
|
224
|
+
suffix = f" — {description}" if description else ""
|
|
225
|
+
return f" {entry.provider_name} [{' · '.join(marks)}]{suffix}"
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _capabilities_line(capabilities: frozenset[str]) -> str:
|
|
229
|
+
return " 能力:" + (", ".join(sorted(capabilities)) if capabilities else "无")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _instructions_line(instructions: str | None) -> str:
|
|
233
|
+
if not instructions:
|
|
234
|
+
return " 说明:无"
|
|
235
|
+
return f" 说明:{_one_line(instructions)[:200]}"
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _one_line(text: str) -> str:
|
|
239
|
+
return " ".join(text.split())
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _key_error(error: KeyError) -> str:
|
|
243
|
+
return str(error.args[0]) if error.args else "未知 MCP 服务器"
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
__all__ = [
|
|
247
|
+
"USAGE",
|
|
248
|
+
"render_history",
|
|
249
|
+
"render_overview",
|
|
250
|
+
"render_schema",
|
|
251
|
+
"render_server",
|
|
252
|
+
"render_tools",
|
|
253
|
+
"run_panel",
|
|
254
|
+
]
|