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,1060 @@
|
|
|
1
|
+
"""MCP 运行时:连接服务器、发现能力,并把它们接进模型可调用的工具集合。
|
|
2
|
+
|
|
3
|
+
这一层是 ``braid_mcp``(协议客户端)与 ``braid_agent``(工具协议)之间的适配者,
|
|
4
|
+
两个包都不该知道对方的存在。
|
|
5
|
+
|
|
6
|
+
## 状态机
|
|
7
|
+
|
|
8
|
+
```text
|
|
9
|
+
disabled
|
|
10
|
+
disconnected ──connect()──► connecting ──成功──► discovering ──成功──► ready
|
|
11
|
+
▲ │ │
|
|
12
|
+
│ ├──认证失败──► needs_auth
|
|
13
|
+
│ └──其它失败──► failed
|
|
14
|
+
└──────────────close() / 连接断开──────────┘
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
``connect`` 幂等,失败不抛异常:状态记在连接上,``/mcp`` 能显示原因,下一次调用会
|
|
18
|
+
重试。``enabled: false`` 的服务器直接显示为 ``disabled``。
|
|
19
|
+
|
|
20
|
+
## 工具名
|
|
21
|
+
|
|
22
|
+
``mcp__<server>__<tool>``,非 ``[A-Za-z0-9_]`` 的字符替换成 ``_``,超过 64 字符时
|
|
23
|
+
截断并加 8 位哈希后缀。名字一旦定下就不再变化。
|
|
24
|
+
|
|
25
|
+
## 延迟加载
|
|
26
|
+
|
|
27
|
+
默认只向模型提供搜索与加载工具,完整描述与参数 Schema 留在目录里;
|
|
28
|
+
``mcp_load_tool`` 之后下一回合才出现原生工具声明。``loading: "eager"`` 或单工具的
|
|
29
|
+
``eager: true`` 直接注册。
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import asyncio
|
|
35
|
+
import hashlib
|
|
36
|
+
import logging
|
|
37
|
+
import os
|
|
38
|
+
import re
|
|
39
|
+
from collections.abc import Callable, Collection, Sequence
|
|
40
|
+
from dataclasses import dataclass, field
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
from typing import Literal
|
|
43
|
+
|
|
44
|
+
from braid_ai.cancel import CancelToken
|
|
45
|
+
from braid_ai.types import JsonValue
|
|
46
|
+
from braid_coding_agent.extensions import (
|
|
47
|
+
BeforeAgentStartEvent,
|
|
48
|
+
BeforeAgentStartPatch,
|
|
49
|
+
ExtensionAPI,
|
|
50
|
+
)
|
|
51
|
+
from braid_coding_agent.mcp.cache import CatalogCache, tool_from_json
|
|
52
|
+
from braid_coding_agent.mcp.catalog import ToolCatalog, ToolEntry, estimate_tokens
|
|
53
|
+
from braid_coding_agent.mcp.config import McpServerConfig, load_mcp_config
|
|
54
|
+
from braid_coding_agent.mcp.inspector import CallInspector, CallRecord
|
|
55
|
+
from braid_coding_agent.mcp.tools import (
|
|
56
|
+
HELPER_TOOL_NAMES,
|
|
57
|
+
MAX_TOOL_DESCRIPTION_CHARS,
|
|
58
|
+
build_agent_tool,
|
|
59
|
+
first_line,
|
|
60
|
+
helper_tools,
|
|
61
|
+
)
|
|
62
|
+
from braid_coding_agent.mcp.trust import is_trusted, load_trust, server_fingerprint
|
|
63
|
+
from braid_coding_agent.permissions.model import PermissionAction
|
|
64
|
+
from braid_coding_agent.settings import McpSettings
|
|
65
|
+
from braid_coding_agent.tools.output_store import ToolOutputStore
|
|
66
|
+
from braid_mcp import (
|
|
67
|
+
JSON_RPC_ERROR_CODES,
|
|
68
|
+
CallToolResult,
|
|
69
|
+
GetPromptResult,
|
|
70
|
+
McpAuthRequiredError,
|
|
71
|
+
McpClient,
|
|
72
|
+
McpClientOptions,
|
|
73
|
+
McpError,
|
|
74
|
+
McpPrompt,
|
|
75
|
+
McpRequestOptions,
|
|
76
|
+
McpResource,
|
|
77
|
+
McpResourceTemplate,
|
|
78
|
+
McpSessionExpiredError,
|
|
79
|
+
McpTool,
|
|
80
|
+
McpTransport,
|
|
81
|
+
OAuthTokenProvider,
|
|
82
|
+
ReadResourceResult,
|
|
83
|
+
Root,
|
|
84
|
+
SseTransport,
|
|
85
|
+
SseTransportOptions,
|
|
86
|
+
StdioTransport,
|
|
87
|
+
StdioTransportOptions,
|
|
88
|
+
StreamableHttpTransport,
|
|
89
|
+
StreamableHttpTransportOptions,
|
|
90
|
+
WebSocketTransport,
|
|
91
|
+
WebSocketTransportOptions,
|
|
92
|
+
token_store,
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
logger = logging.getLogger(__name__)
|
|
96
|
+
|
|
97
|
+
#: 扩展名。``session_shutdown`` 的分发按它归因错误,``/mcp`` 的说明也用它。
|
|
98
|
+
MCP_EXTENSION_NAME = "mcp"
|
|
99
|
+
#: 工具名前缀,也是模型侧"这是外部工具"的唯一线索。
|
|
100
|
+
TOOL_NAME_PREFIX = "mcp__"
|
|
101
|
+
#: Provider 侧工具名长度上限(OpenAI 兼容端点与 Anthropic 都是 64)。
|
|
102
|
+
MAX_TOOL_NAME_LENGTH = 64
|
|
103
|
+
#: 服务端工具列表变化时发的通知方法名。
|
|
104
|
+
TOOLS_LIST_CHANGED = "notifications/tools/list_changed"
|
|
105
|
+
#: 延迟加载目录注入的系统提示词分节名。
|
|
106
|
+
MCP_PROMPT_SECTION = "mcp"
|
|
107
|
+
#: 服务器说明进入提示词时的长度上限。
|
|
108
|
+
MAX_INSTRUCTIONS_CHARS = 512
|
|
109
|
+
|
|
110
|
+
_SANITIZE = re.compile(r"[^A-Za-z0-9_]")
|
|
111
|
+
|
|
112
|
+
type McpServerState = Literal[
|
|
113
|
+
"disabled",
|
|
114
|
+
"disconnected",
|
|
115
|
+
"connecting",
|
|
116
|
+
"discovering",
|
|
117
|
+
"ready",
|
|
118
|
+
"needs_auth",
|
|
119
|
+
"failed",
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass(slots=True)
|
|
124
|
+
class McpServerStatus:
|
|
125
|
+
"""一个服务器的当前状态。``/mcp`` 与 ``mcp_status`` 都读它。"""
|
|
126
|
+
|
|
127
|
+
name: str
|
|
128
|
+
state: McpServerState
|
|
129
|
+
#: ``stdio`` / ``http`` / ``sse`` / ``ws``。
|
|
130
|
+
transport: str = "stdio"
|
|
131
|
+
tool_count: int = 0
|
|
132
|
+
tools: list[str] = field(default_factory=list[str])
|
|
133
|
+
resource_count: int = 0
|
|
134
|
+
prompt_count: int = 0
|
|
135
|
+
#: 已经通过 ``mcp_load_tool`` 载入的工具数。
|
|
136
|
+
loaded_tools: int = 0
|
|
137
|
+
#: 最近一次错误。成功连接与成功调用会清掉它。
|
|
138
|
+
error: str | None = None
|
|
139
|
+
#: 当前工具目录来自上次发现的缓存,服务器尚未连上。
|
|
140
|
+
cached: bool = False
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def mcp_tool_name(server: str, tool: str, *, is_taken: Callable[[str], bool] | None = None) -> str:
|
|
144
|
+
"""``mcp__<server>__<tool>`` 的规范化形式。"""
|
|
145
|
+
taken = is_taken if is_taken is not None else _never_taken
|
|
146
|
+
plain = _SANITIZE.sub("_", f"{TOOL_NAME_PREFIX}{server}__{tool}")
|
|
147
|
+
if len(plain) <= MAX_TOOL_NAME_LENGTH and not taken(plain):
|
|
148
|
+
return plain
|
|
149
|
+
digest = hashlib.sha256(f"{server}\0{tool}".encode()).hexdigest()[:8]
|
|
150
|
+
return f"{plain[: MAX_TOOL_NAME_LENGTH - len(digest) - 1]}_{digest}"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _never_taken(name: str) -> bool:
|
|
154
|
+
del name
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class McpServerConnection:
|
|
159
|
+
"""一个配置项对应的一条连接。"""
|
|
160
|
+
|
|
161
|
+
def __init__(
|
|
162
|
+
self,
|
|
163
|
+
config: McpServerConfig,
|
|
164
|
+
*,
|
|
165
|
+
cwd: str,
|
|
166
|
+
agent_dir: Path,
|
|
167
|
+
connect_timeout_s: float,
|
|
168
|
+
call_timeout_s: float,
|
|
169
|
+
) -> None:
|
|
170
|
+
self.config = config
|
|
171
|
+
self._cwd = cwd
|
|
172
|
+
self._agent_dir = agent_dir
|
|
173
|
+
self._connect_timeout_s = connect_timeout_s
|
|
174
|
+
self._call_timeout_s = call_timeout_s
|
|
175
|
+
self._client: McpClient | None = None
|
|
176
|
+
self._state: McpServerState = "disabled" if not config.enabled else "disconnected"
|
|
177
|
+
self._error: str | None = None
|
|
178
|
+
self._capabilities: frozenset[str] = frozenset()
|
|
179
|
+
self._server_name: str | None = None
|
|
180
|
+
self._tools: list[McpTool] = []
|
|
181
|
+
self._resources: list[McpResource] = []
|
|
182
|
+
self._resource_templates: list[McpResourceTemplate] = []
|
|
183
|
+
self._prompts: list[McpPrompt] = []
|
|
184
|
+
self._cached = False
|
|
185
|
+
self._instructions: str | None = None
|
|
186
|
+
self._lock = asyncio.Lock()
|
|
187
|
+
self._refresh_task: asyncio.Task[None] | None = None
|
|
188
|
+
#: 发现完成或工具表变化后的回调,由 :class:`McpRuntime` 挂上。
|
|
189
|
+
self.on_tools_changed: Callable[[McpServerConnection], None] | None = None
|
|
190
|
+
|
|
191
|
+
# ------------------------------------------------------------- 只读状态
|
|
192
|
+
|
|
193
|
+
@property
|
|
194
|
+
def name(self) -> str:
|
|
195
|
+
"""配置里的服务器名。"""
|
|
196
|
+
return self.config.name
|
|
197
|
+
|
|
198
|
+
@property
|
|
199
|
+
def state(self) -> McpServerState:
|
|
200
|
+
"""连接状态。"""
|
|
201
|
+
return self._state
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def error(self) -> str | None:
|
|
205
|
+
"""最近一次错误文本。"""
|
|
206
|
+
return self._error
|
|
207
|
+
|
|
208
|
+
@property
|
|
209
|
+
def capabilities(self) -> frozenset[str]:
|
|
210
|
+
"""服务端声明的能力名。"""
|
|
211
|
+
return self._capabilities
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def server_name(self) -> str | None:
|
|
215
|
+
"""服务端在 ``initialize`` 里报出的名字。"""
|
|
216
|
+
return self._server_name
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
def tools(self) -> list[McpTool]:
|
|
220
|
+
"""服务端上次声明出来的工具。"""
|
|
221
|
+
return list(self._tools)
|
|
222
|
+
|
|
223
|
+
@property
|
|
224
|
+
def resources(self) -> list[McpResource]:
|
|
225
|
+
"""服务端上次声明出来的资源。"""
|
|
226
|
+
return list(self._resources)
|
|
227
|
+
|
|
228
|
+
@property
|
|
229
|
+
def resource_templates(self) -> list[McpResourceTemplate]:
|
|
230
|
+
"""服务端上次声明出来的资源模板。"""
|
|
231
|
+
return list(self._resource_templates)
|
|
232
|
+
|
|
233
|
+
@property
|
|
234
|
+
def prompts(self) -> list[McpPrompt]:
|
|
235
|
+
"""服务端上次声明出来的提示词模板。"""
|
|
236
|
+
return list(self._prompts)
|
|
237
|
+
|
|
238
|
+
@property
|
|
239
|
+
def instructions(self) -> str | None:
|
|
240
|
+
"""握手时服务端给的使用说明。"""
|
|
241
|
+
return self._instructions
|
|
242
|
+
|
|
243
|
+
@property
|
|
244
|
+
def cached(self) -> bool:
|
|
245
|
+
"""工具目录是否来自缓存。连接成功并完成发现后回到 ``False``。"""
|
|
246
|
+
return self._cached
|
|
247
|
+
|
|
248
|
+
@property
|
|
249
|
+
def call_timeout_s(self) -> float:
|
|
250
|
+
"""单次调用与单个发现请求使用的超时。"""
|
|
251
|
+
return self._call_timeout_s
|
|
252
|
+
|
|
253
|
+
def load_cached_tools(self, tools: Sequence[McpTool]) -> None:
|
|
254
|
+
"""在连接之前装入上次发现的工具元信息。"""
|
|
255
|
+
if self._client is not None:
|
|
256
|
+
return
|
|
257
|
+
self._tools = list(tools)
|
|
258
|
+
self._cached = True
|
|
259
|
+
|
|
260
|
+
# --------------------------------------------------------------- 连接
|
|
261
|
+
|
|
262
|
+
async def connect(self) -> None:
|
|
263
|
+
"""建立连接并发现能力。已连接时直接返回。"""
|
|
264
|
+
if not self.config.enabled:
|
|
265
|
+
self._state = "disabled"
|
|
266
|
+
return
|
|
267
|
+
async with self._lock:
|
|
268
|
+
if self._state == "ready" and self._client is not None:
|
|
269
|
+
return
|
|
270
|
+
self._state = "connecting"
|
|
271
|
+
self._error = None
|
|
272
|
+
transport = self._create_transport()
|
|
273
|
+
client = McpClient(
|
|
274
|
+
McpClientOptions(
|
|
275
|
+
name="braid",
|
|
276
|
+
version=_client_version(),
|
|
277
|
+
request_timeout_ms=self._call_timeout_s * 1000,
|
|
278
|
+
roots=[Root(uri=Path(self._cwd).as_uri(), name=Path(self._cwd).name)],
|
|
279
|
+
)
|
|
280
|
+
)
|
|
281
|
+
client.on_error(self._record_error)
|
|
282
|
+
try:
|
|
283
|
+
await asyncio.wait_for(client.connect(transport), self._connect_timeout_s)
|
|
284
|
+
except TimeoutError:
|
|
285
|
+
self._state = "failed"
|
|
286
|
+
self._error = f"连接超时({self._connect_timeout_s:g} 秒)"
|
|
287
|
+
await client.close()
|
|
288
|
+
return
|
|
289
|
+
except McpAuthRequiredError as exc:
|
|
290
|
+
self._state = "needs_auth"
|
|
291
|
+
self._error = f"需要授权:{_describe(exc)}"
|
|
292
|
+
await client.close()
|
|
293
|
+
return
|
|
294
|
+
except Exception as exc:
|
|
295
|
+
self._state = "failed"
|
|
296
|
+
stderr = transport.stderr.strip() if isinstance(transport, StdioTransport) else ""
|
|
297
|
+
self._error = _with_stderr(_describe(exc), stderr)
|
|
298
|
+
await client.close()
|
|
299
|
+
return
|
|
300
|
+
client.on_close(lambda: self._on_transport_closed(client))
|
|
301
|
+
client.on_notification(TOOLS_LIST_CHANGED, self._on_tools_list_changed)
|
|
302
|
+
self._client = client
|
|
303
|
+
self._instructions = client.instructions
|
|
304
|
+
self._server_name = client.server_info.name if client.server_info is not None else None
|
|
305
|
+
self._state = "discovering"
|
|
306
|
+
try:
|
|
307
|
+
await self._discover(client)
|
|
308
|
+
except Exception as exc:
|
|
309
|
+
self._client = None
|
|
310
|
+
self._state = "failed"
|
|
311
|
+
self._error = f"能力发现失败:{_describe(exc)}"
|
|
312
|
+
await client.close()
|
|
313
|
+
return
|
|
314
|
+
if client.connection_state != "connected":
|
|
315
|
+
self._state = "disconnected"
|
|
316
|
+
self._error = "连接已断开"
|
|
317
|
+
return
|
|
318
|
+
self._state = "ready"
|
|
319
|
+
self._error = None
|
|
320
|
+
self._cached = False
|
|
321
|
+
self._notify_changed()
|
|
322
|
+
|
|
323
|
+
async def call_tool(
|
|
324
|
+
self,
|
|
325
|
+
tool: str,
|
|
326
|
+
arguments: dict[str, JsonValue],
|
|
327
|
+
signal: CancelToken | None,
|
|
328
|
+
) -> CallToolResult:
|
|
329
|
+
"""调用一个工具。取消令牌直接交给 MCP 客户端。"""
|
|
330
|
+
client = await self._require_client()
|
|
331
|
+
try:
|
|
332
|
+
return await client.call_tool(
|
|
333
|
+
tool,
|
|
334
|
+
arguments,
|
|
335
|
+
McpRequestOptions(timeout_ms=self._call_timeout_s * 1000, cancel=signal),
|
|
336
|
+
)
|
|
337
|
+
except McpSessionExpiredError:
|
|
338
|
+
await self.close()
|
|
339
|
+
client = await self._require_client()
|
|
340
|
+
return await client.call_tool(
|
|
341
|
+
tool,
|
|
342
|
+
arguments,
|
|
343
|
+
McpRequestOptions(timeout_ms=self._call_timeout_s * 1000, cancel=signal),
|
|
344
|
+
)
|
|
345
|
+
except Exception as exc:
|
|
346
|
+
self._error = _describe(exc)
|
|
347
|
+
raise
|
|
348
|
+
|
|
349
|
+
async def read_resource(
|
|
350
|
+
self, uri: str, signal: CancelToken | None = None
|
|
351
|
+
) -> ReadResourceResult:
|
|
352
|
+
"""读取一个资源。"""
|
|
353
|
+
client = await self._require_client()
|
|
354
|
+
try:
|
|
355
|
+
return await client.read_resource(
|
|
356
|
+
uri, McpRequestOptions(timeout_ms=self._call_timeout_s * 1000, cancel=signal)
|
|
357
|
+
)
|
|
358
|
+
except Exception as exc:
|
|
359
|
+
self._error = _describe(exc)
|
|
360
|
+
raise
|
|
361
|
+
|
|
362
|
+
async def get_prompt(
|
|
363
|
+
self,
|
|
364
|
+
name: str,
|
|
365
|
+
arguments: dict[str, JsonValue] | None,
|
|
366
|
+
signal: CancelToken | None = None,
|
|
367
|
+
) -> GetPromptResult:
|
|
368
|
+
"""取出一条提示词模板的完整消息。"""
|
|
369
|
+
client = await self._require_client()
|
|
370
|
+
try:
|
|
371
|
+
return await client.get_prompt(
|
|
372
|
+
name,
|
|
373
|
+
arguments,
|
|
374
|
+
McpRequestOptions(timeout_ms=self._call_timeout_s * 1000, cancel=signal),
|
|
375
|
+
)
|
|
376
|
+
except Exception as exc:
|
|
377
|
+
self._error = _describe(exc)
|
|
378
|
+
raise
|
|
379
|
+
|
|
380
|
+
async def refresh_tools(self) -> None:
|
|
381
|
+
"""重读能力并通知运行时重新注册。"""
|
|
382
|
+
await self.refresh()
|
|
383
|
+
|
|
384
|
+
async def refresh(self) -> None:
|
|
385
|
+
"""重新发现全部能力。连接不在时先连上。"""
|
|
386
|
+
if not self.config.enabled:
|
|
387
|
+
return
|
|
388
|
+
if self._client is None:
|
|
389
|
+
await self.connect()
|
|
390
|
+
return
|
|
391
|
+
client = self._client
|
|
392
|
+
self._state = "discovering"
|
|
393
|
+
try:
|
|
394
|
+
await self._discover(client)
|
|
395
|
+
except Exception as exc:
|
|
396
|
+
self._state = "failed"
|
|
397
|
+
self._error = f"刷新能力失败:{_describe(exc)}"
|
|
398
|
+
return
|
|
399
|
+
self._state = "ready"
|
|
400
|
+
self._error = None
|
|
401
|
+
self._notify_changed()
|
|
402
|
+
|
|
403
|
+
async def close(self) -> None:
|
|
404
|
+
"""断开连接。幂等;之后仍可再次 ``connect``。"""
|
|
405
|
+
if self._refresh_task is not None:
|
|
406
|
+
self._refresh_task.cancel()
|
|
407
|
+
self._refresh_task = None
|
|
408
|
+
client, self._client = self._client, None
|
|
409
|
+
self._state = "disabled" if not self.config.enabled else "disconnected"
|
|
410
|
+
self._capabilities = frozenset()
|
|
411
|
+
self._tools = []
|
|
412
|
+
self._resources = []
|
|
413
|
+
self._resource_templates = []
|
|
414
|
+
self._prompts = []
|
|
415
|
+
self._cached = False
|
|
416
|
+
self._instructions = None
|
|
417
|
+
self._server_name = None
|
|
418
|
+
if client is not None:
|
|
419
|
+
await client.close()
|
|
420
|
+
|
|
421
|
+
def mark_untrusted(self) -> None:
|
|
422
|
+
"""记成未确认信任。用于配置重载时跳过新出现的服务器。"""
|
|
423
|
+
self._state = "failed"
|
|
424
|
+
self._error = '未确认信任:在终端运行 braid mcp list 后确认,或在该条目写 "trusted": true'
|
|
425
|
+
|
|
426
|
+
# --------------------------------------------------------------- 内部
|
|
427
|
+
|
|
428
|
+
def _create_transport(self) -> McpTransport:
|
|
429
|
+
"""按配置造一条传输。远程传输的 OAuth 令牌每次请求前重新求值。"""
|
|
430
|
+
if self.config.transport in ("http", "sse", "ws"):
|
|
431
|
+
url = self.config.url
|
|
432
|
+
assert url is not None
|
|
433
|
+
auth = (
|
|
434
|
+
OAuthTokenProvider(token_store(self._agent_dir), self.config.name)
|
|
435
|
+
if self.config.oauth is not None
|
|
436
|
+
else None
|
|
437
|
+
)
|
|
438
|
+
headers = dict(self.config.headers)
|
|
439
|
+
if self.config.transport == "http":
|
|
440
|
+
return StreamableHttpTransport(
|
|
441
|
+
StreamableHttpTransportOptions(
|
|
442
|
+
url=url,
|
|
443
|
+
headers=headers,
|
|
444
|
+
timeout_ms=self._call_timeout_s * 1000,
|
|
445
|
+
auth=auth,
|
|
446
|
+
)
|
|
447
|
+
)
|
|
448
|
+
if self.config.transport == "sse":
|
|
449
|
+
return SseTransport(
|
|
450
|
+
SseTransportOptions(
|
|
451
|
+
url=url,
|
|
452
|
+
headers=headers,
|
|
453
|
+
timeout_ms=self._call_timeout_s * 1000,
|
|
454
|
+
auth=auth,
|
|
455
|
+
)
|
|
456
|
+
)
|
|
457
|
+
return WebSocketTransport(
|
|
458
|
+
WebSocketTransportOptions(
|
|
459
|
+
url=url,
|
|
460
|
+
headers=headers,
|
|
461
|
+
timeout_ms=self._call_timeout_s * 1000,
|
|
462
|
+
auth=auth,
|
|
463
|
+
)
|
|
464
|
+
)
|
|
465
|
+
return StdioTransport(
|
|
466
|
+
StdioTransportOptions(
|
|
467
|
+
command=os.path.expanduser(self.config.command or ""),
|
|
468
|
+
args=[os.path.expanduser(arg) for arg in self.config.args],
|
|
469
|
+
cwd=self._resolve_cwd(),
|
|
470
|
+
env=dict(self.config.env),
|
|
471
|
+
)
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
def _resolve_cwd(self) -> str | None:
|
|
475
|
+
"""配置里的 ``cwd`` 相对会话工作目录解析;绝对路径原样用。"""
|
|
476
|
+
configured = self.config.cwd
|
|
477
|
+
if configured is None:
|
|
478
|
+
return None
|
|
479
|
+
return os.path.join(self._cwd, os.path.expanduser(configured))
|
|
480
|
+
|
|
481
|
+
async def _require_client(self) -> McpClient:
|
|
482
|
+
client = self._client
|
|
483
|
+
if client is not None and client.connection_state == "connected":
|
|
484
|
+
return client
|
|
485
|
+
await self.connect()
|
|
486
|
+
client = self._client
|
|
487
|
+
if client is None:
|
|
488
|
+
raise RuntimeError(f"MCP 服务器 {self.name} 未连接:{self._error or '原因未知'}")
|
|
489
|
+
return client
|
|
490
|
+
|
|
491
|
+
async def _discover(self, client: McpClient) -> None:
|
|
492
|
+
"""按服务端声明的能力分别发现工具、资源与提示词。"""
|
|
493
|
+
capabilities = frozenset(client.server_capabilities)
|
|
494
|
+
options = McpRequestOptions(timeout_ms=self._call_timeout_s * 1000)
|
|
495
|
+
tools = await self._list_tools(client, options) if "tools" in capabilities else []
|
|
496
|
+
resources: list[McpResource] = []
|
|
497
|
+
templates: list[McpResourceTemplate] = []
|
|
498
|
+
prompts: list[McpPrompt] = []
|
|
499
|
+
if "resources" in capabilities:
|
|
500
|
+
resources = await client.list_resources(options)
|
|
501
|
+
templates = await _optional_list(client.list_resource_templates(options))
|
|
502
|
+
if "prompts" in capabilities:
|
|
503
|
+
prompts = await client.list_prompts(options)
|
|
504
|
+
self._capabilities = capabilities
|
|
505
|
+
self._tools = tools
|
|
506
|
+
self._resources = resources
|
|
507
|
+
self._resource_templates = templates
|
|
508
|
+
self._prompts = prompts
|
|
509
|
+
|
|
510
|
+
async def _list_tools(
|
|
511
|
+
self, client: McpClient, options: McpRequestOptions | None = None
|
|
512
|
+
) -> list[McpTool]:
|
|
513
|
+
"""声明了 tools 能力的服务端才问工具列表。"""
|
|
514
|
+
if "tools" not in client.server_capabilities:
|
|
515
|
+
return []
|
|
516
|
+
return await client.list_tools(
|
|
517
|
+
options or McpRequestOptions(timeout_ms=self._call_timeout_s * 1000)
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
def _record_error(self, error: Exception) -> None:
|
|
521
|
+
"""传输层与协议层的非致命错误(坏行、未知 id)。"""
|
|
522
|
+
self._error = _describe(error)
|
|
523
|
+
|
|
524
|
+
def _on_transport_closed(self, client: McpClient) -> None:
|
|
525
|
+
"""连接断了:下一次调用重连。主动 ``close`` 时这里已经换过指针。"""
|
|
526
|
+
if self._client is not client:
|
|
527
|
+
return
|
|
528
|
+
self._client = None
|
|
529
|
+
self._state = "disabled" if not self.config.enabled else "disconnected"
|
|
530
|
+
self._error = "连接已断开"
|
|
531
|
+
|
|
532
|
+
def _on_tools_list_changed(self, params: JsonValue | None) -> None:
|
|
533
|
+
del params
|
|
534
|
+
if self._refresh_task is not None and not self._refresh_task.done():
|
|
535
|
+
return
|
|
536
|
+
self._refresh_task = asyncio.get_running_loop().create_task(self.refresh())
|
|
537
|
+
|
|
538
|
+
def _notify_changed(self) -> None:
|
|
539
|
+
if self.on_tools_changed is not None:
|
|
540
|
+
self.on_tools_changed(self)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
async def _optional_list(value: object) -> list[McpResourceTemplate]:
|
|
544
|
+
"""把 ``-32601`` 当作空列表,其余错误照常抛出。"""
|
|
545
|
+
try:
|
|
546
|
+
return await value # type: ignore[misc]
|
|
547
|
+
except McpError as exc:
|
|
548
|
+
if exc.code == JSON_RPC_ERROR_CODES["method_not_found"]:
|
|
549
|
+
return []
|
|
550
|
+
raise
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
class McpRuntime:
|
|
554
|
+
"""全部 MCP 服务器的容器,同时是一个扩展。"""
|
|
555
|
+
|
|
556
|
+
name: str = MCP_EXTENSION_NAME
|
|
557
|
+
|
|
558
|
+
def __init__(
|
|
559
|
+
self,
|
|
560
|
+
configs: Sequence[McpServerConfig],
|
|
561
|
+
*,
|
|
562
|
+
cwd: str,
|
|
563
|
+
agent_dir: Path,
|
|
564
|
+
close_on_session_shutdown: bool = True,
|
|
565
|
+
output_store: ToolOutputStore | None = None,
|
|
566
|
+
settings: McpSettings | None = None,
|
|
567
|
+
) -> None:
|
|
568
|
+
self._cwd = cwd
|
|
569
|
+
self._agent_dir = agent_dir
|
|
570
|
+
self._settings = settings or McpSettings()
|
|
571
|
+
self._connections = [
|
|
572
|
+
McpServerConnection(
|
|
573
|
+
config,
|
|
574
|
+
cwd=cwd,
|
|
575
|
+
agent_dir=agent_dir,
|
|
576
|
+
connect_timeout_s=config.connect_timeout_s or self._settings.connect_timeout_s,
|
|
577
|
+
call_timeout_s=(
|
|
578
|
+
config.timeout_s if config.timeout_explicit else self._settings.call_timeout_s
|
|
579
|
+
),
|
|
580
|
+
)
|
|
581
|
+
for config in configs
|
|
582
|
+
]
|
|
583
|
+
self._catalog = ToolCatalog()
|
|
584
|
+
self._cache = CatalogCache(agent_dir) if self._settings.cache else None
|
|
585
|
+
self._inspector = CallInspector()
|
|
586
|
+
self._api: ExtensionAPI | None = None
|
|
587
|
+
self._close_on_session_shutdown = close_on_session_shutdown
|
|
588
|
+
self._output_store = (
|
|
589
|
+
output_store
|
|
590
|
+
if output_store is not None
|
|
591
|
+
else ToolOutputStore(os.path.join(str(agent_dir), "mcp-outputs"))
|
|
592
|
+
)
|
|
593
|
+
#: 工具名 → 拥有者键(``server\0tool``)。名字一旦分配就不再变。
|
|
594
|
+
self._owners: dict[str, str] = {}
|
|
595
|
+
self._names: dict[str, str] = {}
|
|
596
|
+
self._registered: dict[str, set[str]] = {}
|
|
597
|
+
self._helper_tools: set[str] = set()
|
|
598
|
+
#: 通过 ``mcp_load_tool`` 载入的工具(Provider 侧名字)。
|
|
599
|
+
self._loaded: set[str] = set()
|
|
600
|
+
self._tool_filter: set[str] | None = None
|
|
601
|
+
|
|
602
|
+
# ------------------------------------------------------------- 只读状态
|
|
603
|
+
|
|
604
|
+
@property
|
|
605
|
+
def connections(self) -> list[McpServerConnection]:
|
|
606
|
+
"""按配置顺序的服务器列表。"""
|
|
607
|
+
return list(self._connections)
|
|
608
|
+
|
|
609
|
+
@property
|
|
610
|
+
def output_store(self) -> ToolOutputStore:
|
|
611
|
+
"""截断全文与二进制资源的落盘目录。"""
|
|
612
|
+
return self._output_store
|
|
613
|
+
|
|
614
|
+
@property
|
|
615
|
+
def catalog(self) -> ToolCatalog:
|
|
616
|
+
"""发现出来的工具目录。"""
|
|
617
|
+
return self._catalog
|
|
618
|
+
|
|
619
|
+
@property
|
|
620
|
+
def inspector(self) -> CallInspector:
|
|
621
|
+
"""有界调用历史。"""
|
|
622
|
+
return self._inspector
|
|
623
|
+
|
|
624
|
+
@property
|
|
625
|
+
def loaded_tools(self) -> frozenset[str]:
|
|
626
|
+
"""已经载入的延迟加载工具名。"""
|
|
627
|
+
return frozenset(self._loaded)
|
|
628
|
+
|
|
629
|
+
@property
|
|
630
|
+
def settings(self) -> McpSettings:
|
|
631
|
+
"""全局 MCP 设置。"""
|
|
632
|
+
return self._settings
|
|
633
|
+
|
|
634
|
+
def statuses(self) -> list[McpServerStatus]:
|
|
635
|
+
"""每个服务器的状态快照。"""
|
|
636
|
+
return [
|
|
637
|
+
McpServerStatus(
|
|
638
|
+
name=connection.name,
|
|
639
|
+
state=connection.state,
|
|
640
|
+
transport=connection.config.transport,
|
|
641
|
+
tool_count=len(connection.tools),
|
|
642
|
+
tools=[self.name_for(connection.name, tool.name) for tool in connection.tools],
|
|
643
|
+
resource_count=len(connection.resources),
|
|
644
|
+
prompt_count=len(connection.prompts),
|
|
645
|
+
loaded_tools=sum(
|
|
646
|
+
1
|
|
647
|
+
for entry in self._catalog.by_server(connection.name)
|
|
648
|
+
if entry.provider_name in self._loaded
|
|
649
|
+
),
|
|
650
|
+
error=connection.error,
|
|
651
|
+
cached=connection.cached,
|
|
652
|
+
)
|
|
653
|
+
for connection in self._connections
|
|
654
|
+
]
|
|
655
|
+
|
|
656
|
+
def status(self, name: str) -> McpServerStatus:
|
|
657
|
+
"""按名字取一个状态快照;不存在时抛 ``KeyError``。"""
|
|
658
|
+
return self._status_of(name)
|
|
659
|
+
|
|
660
|
+
def tool_names(self) -> list[str]:
|
|
661
|
+
"""当前配置会暴露给模型的全部工具名,按服务器与工具声明顺序。"""
|
|
662
|
+
names = [entry.provider_name for entry in self._catalog.entries]
|
|
663
|
+
if self._connections:
|
|
664
|
+
names.extend(HELPER_TOOL_NAMES)
|
|
665
|
+
return names
|
|
666
|
+
|
|
667
|
+
def name_for(self, server: str, tool: str) -> str:
|
|
668
|
+
"""服务器工具 → Provider 侧工具名。"""
|
|
669
|
+
owner = f"{server}\0{tool}"
|
|
670
|
+
existing = self._names.get(owner)
|
|
671
|
+
if existing is not None:
|
|
672
|
+
return existing
|
|
673
|
+
name = mcp_tool_name(
|
|
674
|
+
server,
|
|
675
|
+
tool,
|
|
676
|
+
is_taken=lambda candidate: self._owners.get(candidate, owner) != owner,
|
|
677
|
+
)
|
|
678
|
+
self._names[owner] = name
|
|
679
|
+
self._owners[name] = owner
|
|
680
|
+
return name
|
|
681
|
+
|
|
682
|
+
def connection(self, name: str) -> McpServerConnection:
|
|
683
|
+
"""按名字取一条连接;不存在时抛 ``KeyError``。"""
|
|
684
|
+
for connection in self._connections:
|
|
685
|
+
if connection.name == name:
|
|
686
|
+
return connection
|
|
687
|
+
known = ", ".join(connection.name for connection in self._connections) or "(没有服务器)"
|
|
688
|
+
raise KeyError(f"未知 MCP 服务器: {name}(可用: {known})")
|
|
689
|
+
|
|
690
|
+
def history(self, limit: int | None = None) -> list[CallRecord]:
|
|
691
|
+
"""最近的工具调用记录。"""
|
|
692
|
+
return list(self._inspector.recent(limit))
|
|
693
|
+
|
|
694
|
+
def cached_server(self, name: str) -> object | None:
|
|
695
|
+
"""上次发现结果(来自 ``mcp_cache.json``),指纹不匹配时返回 ``None``。"""
|
|
696
|
+
if self._cache is None:
|
|
697
|
+
return None
|
|
698
|
+
return self._cache.get(name, server_fingerprint(self.connection(name).config))
|
|
699
|
+
|
|
700
|
+
def permission_rules(self) -> dict[str, PermissionAction]:
|
|
701
|
+
"""服务器级与工具级策略 → 精确到 Provider 工具名的规则。"""
|
|
702
|
+
rules: dict[str, PermissionAction] = {}
|
|
703
|
+
for connection in self._connections:
|
|
704
|
+
permissions = connection.config.permissions
|
|
705
|
+
if permissions is None:
|
|
706
|
+
continue
|
|
707
|
+
action_patterns: tuple[tuple[PermissionAction, tuple[str, ...]], ...] = (
|
|
708
|
+
("allow", permissions.allow),
|
|
709
|
+
("ask", permissions.ask),
|
|
710
|
+
("deny", permissions.deny),
|
|
711
|
+
)
|
|
712
|
+
entries = self._catalog.by_server(connection.name)
|
|
713
|
+
if not entries:
|
|
714
|
+
# 服务器还没发现过工具时也要先把策略装进权限引擎:后台连接完成后
|
|
715
|
+
# 注册出来的工具不能绕过服务器条目里写下的 deny / ask。
|
|
716
|
+
for action, patterns in action_patterns:
|
|
717
|
+
for pattern in patterns:
|
|
718
|
+
rules[_provider_pattern(connection.name, pattern)] = action
|
|
719
|
+
continue
|
|
720
|
+
for entry in entries:
|
|
721
|
+
for action, patterns in action_patterns:
|
|
722
|
+
if any(
|
|
723
|
+
_matches(entry.tool.name, entry.provider_name, pattern)
|
|
724
|
+
for pattern in patterns
|
|
725
|
+
):
|
|
726
|
+
rules[entry.provider_name] = action
|
|
727
|
+
return rules
|
|
728
|
+
|
|
729
|
+
# --------------------------------------------------------------- 装配
|
|
730
|
+
|
|
731
|
+
def set_tool_filter(self, allowed: Collection[str] | None) -> None:
|
|
732
|
+
"""限定注册哪些工具。``None`` 表示全部。"""
|
|
733
|
+
self._tool_filter = None if allowed is None else set(allowed)
|
|
734
|
+
|
|
735
|
+
def hydrate_cache(self) -> int:
|
|
736
|
+
"""把缓存里的工具目录装进运行时,返回命中的服务器数。
|
|
737
|
+
|
|
738
|
+
这一步只读 ``~/.braid/mcp_cache.json``,不启动任何子进程。命中时工具
|
|
739
|
+
元信息立刻进入目录与扩展注册表,首次界面不必等任何服务器。
|
|
740
|
+
"""
|
|
741
|
+
if self._cache is None:
|
|
742
|
+
return 0
|
|
743
|
+
cached_servers = self._cache.load()
|
|
744
|
+
hydrated = 0
|
|
745
|
+
for connection in self._connections:
|
|
746
|
+
if not connection.config.enabled:
|
|
747
|
+
continue
|
|
748
|
+
cached = cached_servers.get(connection.name)
|
|
749
|
+
if cached is None or cached.fingerprint != server_fingerprint(connection.config):
|
|
750
|
+
continue
|
|
751
|
+
tools = [tool for item in cached.tools if (tool := tool_from_json(item)) is not None]
|
|
752
|
+
connection.load_cached_tools(tools)
|
|
753
|
+
self._catalog.replace_server(connection.name, self._entries_for(connection))
|
|
754
|
+
hydrated += 1
|
|
755
|
+
return hydrated
|
|
756
|
+
|
|
757
|
+
async def connect(self) -> None:
|
|
758
|
+
"""并发连接全部服务器。每个连接自己记账,失败不影响其它服务器。"""
|
|
759
|
+
if not self._connections:
|
|
760
|
+
return
|
|
761
|
+
await asyncio.gather(
|
|
762
|
+
*(self.connect_server(connection.name) for connection in self._connections)
|
|
763
|
+
)
|
|
764
|
+
|
|
765
|
+
async def connect_server(self, name: str) -> McpServerStatus:
|
|
766
|
+
"""连接一个服务器并刷新它的目录。启动后台任务按服务器逐个调用。"""
|
|
767
|
+
connection = self.connection(name)
|
|
768
|
+
await connection.connect()
|
|
769
|
+
self._register_helpers()
|
|
770
|
+
self._refresh_catalog(connection)
|
|
771
|
+
return self._status_of(name)
|
|
772
|
+
|
|
773
|
+
async def activate(self, api: ExtensionAPI) -> None:
|
|
774
|
+
"""扩展激活:注册工具,并接管会话释放与提示词目录。"""
|
|
775
|
+
self._api = api
|
|
776
|
+
for connection in self._connections:
|
|
777
|
+
connection.on_tools_changed = self._refresh_catalog
|
|
778
|
+
for connection in self._connections:
|
|
779
|
+
self._refresh_catalog(connection)
|
|
780
|
+
self._register_helpers()
|
|
781
|
+
api.on("before_agent_start", self._on_before_agent_start)
|
|
782
|
+
api.on("session_shutdown", self._on_session_shutdown)
|
|
783
|
+
|
|
784
|
+
async def enable(self, name: str) -> McpServerStatus:
|
|
785
|
+
"""连接一个服务器并把它的工具注册给模型。"""
|
|
786
|
+
connection = self.connection(name)
|
|
787
|
+
connection.config.enabled = True
|
|
788
|
+
await connection.connect()
|
|
789
|
+
self._register_helpers()
|
|
790
|
+
self._refresh_catalog(connection)
|
|
791
|
+
return self._status_of(name)
|
|
792
|
+
|
|
793
|
+
async def disable(self, name: str) -> McpServerStatus:
|
|
794
|
+
"""断开一个服务器并撤下它的工具。"""
|
|
795
|
+
connection = self.connection(name)
|
|
796
|
+
connection.config.enabled = False
|
|
797
|
+
await connection.close()
|
|
798
|
+
self._refresh_catalog(connection)
|
|
799
|
+
return self._status_of(name)
|
|
800
|
+
|
|
801
|
+
async def reconnect(self, name: str) -> McpServerStatus:
|
|
802
|
+
"""断开后重新连接一个服务器。"""
|
|
803
|
+
connection = self.connection(name)
|
|
804
|
+
connection.config.enabled = True
|
|
805
|
+
await connection.close()
|
|
806
|
+
await connection.connect()
|
|
807
|
+
self._register_helpers()
|
|
808
|
+
self._refresh_catalog(connection)
|
|
809
|
+
return self._status_of(name)
|
|
810
|
+
|
|
811
|
+
async def refresh(self, name: str) -> McpServerStatus:
|
|
812
|
+
"""重新发现一个服务器的能力。"""
|
|
813
|
+
connection = self.connection(name)
|
|
814
|
+
await connection.refresh()
|
|
815
|
+
self._refresh_catalog(connection)
|
|
816
|
+
return self._status_of(name)
|
|
817
|
+
|
|
818
|
+
async def reload(self) -> None:
|
|
819
|
+
"""重新读取两份配置文件,关闭旧连接并连接仍然受信任的服务器。"""
|
|
820
|
+
loaded = load_mcp_config(self._agent_dir, self._cwd)
|
|
821
|
+
records = load_trust(self._agent_dir)
|
|
822
|
+
await self.close()
|
|
823
|
+
self._connections = [
|
|
824
|
+
McpServerConnection(
|
|
825
|
+
config,
|
|
826
|
+
cwd=self._cwd,
|
|
827
|
+
agent_dir=self._agent_dir,
|
|
828
|
+
connect_timeout_s=config.connect_timeout_s or self._settings.connect_timeout_s,
|
|
829
|
+
call_timeout_s=(
|
|
830
|
+
config.timeout_s if config.timeout_explicit else self._settings.call_timeout_s
|
|
831
|
+
),
|
|
832
|
+
)
|
|
833
|
+
for config in loaded.servers.values()
|
|
834
|
+
]
|
|
835
|
+
for connection in self._connections:
|
|
836
|
+
connection.on_tools_changed = self._refresh_catalog
|
|
837
|
+
if connection.config.trusted or is_trusted(records, connection.config):
|
|
838
|
+
await connection.connect()
|
|
839
|
+
else:
|
|
840
|
+
connection.mark_untrusted()
|
|
841
|
+
self._refresh_catalog(connection)
|
|
842
|
+
self._register_helpers()
|
|
843
|
+
|
|
844
|
+
def load_tool(self, provider_name: str) -> ToolEntry:
|
|
845
|
+
"""把一个延迟加载的工具加入原生工具声明。"""
|
|
846
|
+
entry = self._catalog.get(provider_name)
|
|
847
|
+
if entry is None:
|
|
848
|
+
known = ", ".join(item.provider_name for item in self._catalog.entries[:20])
|
|
849
|
+
raise KeyError(f"未知 MCP 工具: {provider_name}(可用: {known or '(没有工具)'})")
|
|
850
|
+
self._loaded.add(provider_name)
|
|
851
|
+
self._register_server(self.connection(entry.server))
|
|
852
|
+
return entry
|
|
853
|
+
|
|
854
|
+
def _status_of(self, name: str) -> McpServerStatus:
|
|
855
|
+
for status in self.statuses():
|
|
856
|
+
if status.name == name:
|
|
857
|
+
return status
|
|
858
|
+
raise KeyError(f"未知 MCP 服务器: {name}")
|
|
859
|
+
|
|
860
|
+
async def close(self) -> None:
|
|
861
|
+
"""关闭全部连接。幂等;会话释放与进程退出都会走到这里。"""
|
|
862
|
+
await asyncio.gather(
|
|
863
|
+
*(connection.close() for connection in self._connections), return_exceptions=True
|
|
864
|
+
)
|
|
865
|
+
|
|
866
|
+
# --------------------------------------------------------------- 内部
|
|
867
|
+
|
|
868
|
+
async def _on_session_shutdown(self, event: object) -> None:
|
|
869
|
+
"""会话释放:子进程与管道在这里收掉。"""
|
|
870
|
+
del event
|
|
871
|
+
if not self._close_on_session_shutdown:
|
|
872
|
+
return
|
|
873
|
+
await self.close()
|
|
874
|
+
|
|
875
|
+
def _on_before_agent_start(self, event: BeforeAgentStartEvent) -> BeforeAgentStartPatch:
|
|
876
|
+
"""把服务器说明与延迟加载目录注入提示词。"""
|
|
877
|
+
del event
|
|
878
|
+
text = self._prompt_section_text()
|
|
879
|
+
return BeforeAgentStartPatch(sections={MCP_PROMPT_SECTION: text or None})
|
|
880
|
+
|
|
881
|
+
def _prompt_section_text(self) -> str:
|
|
882
|
+
parts: list[str] = []
|
|
883
|
+
for connection in self._connections:
|
|
884
|
+
instructions = (connection.instructions or "").strip()
|
|
885
|
+
if not instructions:
|
|
886
|
+
continue
|
|
887
|
+
clipped = instructions[:MAX_INSTRUCTIONS_CHARS].rstrip()
|
|
888
|
+
if len(instructions) > MAX_INSTRUCTIONS_CHARS:
|
|
889
|
+
clipped += "…"
|
|
890
|
+
parts.append(f"[{connection.name}] {clipped}")
|
|
891
|
+
|
|
892
|
+
budget = self._settings.tool_token_budget
|
|
893
|
+
lazy = self._catalog.lazy()
|
|
894
|
+
if lazy and budget > 0:
|
|
895
|
+
header = (
|
|
896
|
+
"以下 MCP 工具按需加载:先用 mcp_search_tools 搜索,"
|
|
897
|
+
"再用 mcp_load_tool 载入完整参数,然后调用。"
|
|
898
|
+
)
|
|
899
|
+
lines: list[str] = []
|
|
900
|
+
used = estimate_tokens(header)
|
|
901
|
+
for entry in lazy:
|
|
902
|
+
description = first_line(entry.tool.description)
|
|
903
|
+
line = (
|
|
904
|
+
f"- {entry.provider_name}: {description}"
|
|
905
|
+
if description
|
|
906
|
+
else f"- {entry.provider_name}"
|
|
907
|
+
)
|
|
908
|
+
cost = estimate_tokens(line) + 1
|
|
909
|
+
if used + cost > budget:
|
|
910
|
+
break
|
|
911
|
+
used += cost
|
|
912
|
+
lines.append(line)
|
|
913
|
+
remaining = len(lazy) - len(lines)
|
|
914
|
+
if remaining > 0:
|
|
915
|
+
lines.append(f"(另有 {remaining} 个工具,用 mcp_search_tools 搜索)")
|
|
916
|
+
parts.append("\n".join([header, *lines]))
|
|
917
|
+
if not parts:
|
|
918
|
+
return ""
|
|
919
|
+
return f"<{MCP_PROMPT_SECTION}>\n" + "\n\n".join(parts) + f"\n</{MCP_PROMPT_SECTION}>"
|
|
920
|
+
|
|
921
|
+
def _refresh_catalog(self, connection: McpServerConnection) -> None:
|
|
922
|
+
"""从连接当前的能力表重建目录,再按注册策略落成工具。"""
|
|
923
|
+
self._catalog.replace_server(connection.name, self._entries_for(connection))
|
|
924
|
+
self._save_cache(connection)
|
|
925
|
+
self._register_server(connection)
|
|
926
|
+
|
|
927
|
+
def _entries_for(self, connection: McpServerConnection) -> list[ToolEntry]:
|
|
928
|
+
"""一个连接当前能力表对应的目录项。连接前后共用同一套加载策略。"""
|
|
929
|
+
entries: list[ToolEntry] = []
|
|
930
|
+
for tool in connection.tools:
|
|
931
|
+
setting = connection.config.tool_settings.get(tool.name)
|
|
932
|
+
if setting is not None and not setting.enabled:
|
|
933
|
+
continue
|
|
934
|
+
entries.append(
|
|
935
|
+
ToolEntry(
|
|
936
|
+
server=connection.name,
|
|
937
|
+
tool=tool,
|
|
938
|
+
provider_name=self.name_for(connection.name, tool.name),
|
|
939
|
+
loading=self._resolve_loading(
|
|
940
|
+
connection.config, setting.eager if setting else None
|
|
941
|
+
),
|
|
942
|
+
)
|
|
943
|
+
)
|
|
944
|
+
return entries
|
|
945
|
+
|
|
946
|
+
def _resolve_loading(
|
|
947
|
+
self, config: McpServerConfig, tool_eager: bool | None
|
|
948
|
+
) -> Literal["lazy", "eager"]:
|
|
949
|
+
if tool_eager is not None:
|
|
950
|
+
return "eager" if tool_eager else "lazy"
|
|
951
|
+
if config.loading is not None:
|
|
952
|
+
return config.loading
|
|
953
|
+
return self._settings.loading
|
|
954
|
+
|
|
955
|
+
def _save_cache(self, connection: McpServerConnection) -> None:
|
|
956
|
+
if self._cache is None or connection.state != "ready":
|
|
957
|
+
return
|
|
958
|
+
self._cache.save(
|
|
959
|
+
connection.name,
|
|
960
|
+
server_fingerprint(connection.config),
|
|
961
|
+
tools=connection.tools,
|
|
962
|
+
resources=connection.resources,
|
|
963
|
+
resource_templates=connection.resource_templates,
|
|
964
|
+
prompts=connection.prompts,
|
|
965
|
+
)
|
|
966
|
+
|
|
967
|
+
def _register_server(self, connection: McpServerConnection) -> None:
|
|
968
|
+
"""按目录里的加载策略注册或撤下工具。"""
|
|
969
|
+
api = self._api
|
|
970
|
+
if api is None:
|
|
971
|
+
return
|
|
972
|
+
previous = self._registered.get(connection.name, set())
|
|
973
|
+
current: set[str] = set()
|
|
974
|
+
for entry in self._catalog.by_server(connection.name):
|
|
975
|
+
if self._tool_filter is not None:
|
|
976
|
+
if entry.provider_name not in self._tool_filter:
|
|
977
|
+
continue
|
|
978
|
+
elif entry.loading == "lazy" and entry.provider_name not in self._loaded:
|
|
979
|
+
continue
|
|
980
|
+
api.register_tool(
|
|
981
|
+
build_agent_tool(
|
|
982
|
+
connection,
|
|
983
|
+
entry.tool,
|
|
984
|
+
entry.provider_name,
|
|
985
|
+
self._output_store,
|
|
986
|
+
self._inspector,
|
|
987
|
+
)
|
|
988
|
+
)
|
|
989
|
+
current.add(entry.provider_name)
|
|
990
|
+
for name in previous - current:
|
|
991
|
+
api.unregister_tool(name)
|
|
992
|
+
self._registered[connection.name] = current
|
|
993
|
+
|
|
994
|
+
def _register_helpers(self) -> None:
|
|
995
|
+
api = self._api
|
|
996
|
+
if api is None:
|
|
997
|
+
return
|
|
998
|
+
if not self._catalog.entries and not any(
|
|
999
|
+
connection.state == "ready" for connection in self._connections
|
|
1000
|
+
):
|
|
1001
|
+
return
|
|
1002
|
+
for tool in helper_tools(self):
|
|
1003
|
+
if self._tool_filter is not None and tool.name not in self._tool_filter:
|
|
1004
|
+
continue
|
|
1005
|
+
api.register_tool(tool)
|
|
1006
|
+
self._helper_tools.add(tool.name)
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
def _client_version() -> str:
|
|
1010
|
+
from braid_coding_agent import __version__
|
|
1011
|
+
|
|
1012
|
+
return __version__
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
def _describe(error: BaseException) -> str:
|
|
1016
|
+
return str(error) or type(error).__name__
|
|
1017
|
+
|
|
1018
|
+
|
|
1019
|
+
def _with_stderr(message: str, stderr: str) -> str:
|
|
1020
|
+
"""错误文本带上服务端 stderr 尾部。"""
|
|
1021
|
+
return f"{message}\n{stderr}" if stderr else message
|
|
1022
|
+
|
|
1023
|
+
|
|
1024
|
+
def _matches(tool_name: str, provider_name: str, pattern: str) -> bool:
|
|
1025
|
+
from fnmatch import fnmatchcase
|
|
1026
|
+
|
|
1027
|
+
return fnmatchcase(tool_name, pattern) or fnmatchcase(provider_name, pattern)
|
|
1028
|
+
|
|
1029
|
+
|
|
1030
|
+
_GLOB_CHARS = frozenset("*?[")
|
|
1031
|
+
_PATTERN_SAFE = re.compile(r"[^A-Za-z0-9_*?\[\]!-]")
|
|
1032
|
+
|
|
1033
|
+
|
|
1034
|
+
def _provider_pattern(server: str, pattern: str) -> str:
|
|
1035
|
+
"""把服务器条目的工具匹配模式换算成 Provider 侧工具名模式。
|
|
1036
|
+
|
|
1037
|
+
没有通配符的名字走与真实工具名相同的规范化函数;带通配符的名字只清理不合法
|
|
1038
|
+
字符,保留 ``*``、``?`` 与字符组。缓存缺失时权限规则先按这个模式生效。
|
|
1039
|
+
"""
|
|
1040
|
+
if not (_GLOB_CHARS & set(pattern)):
|
|
1041
|
+
return mcp_tool_name(server, pattern)
|
|
1042
|
+
server_part = _SANITIZE.sub("_", server)
|
|
1043
|
+
tool_part = _PATTERN_SAFE.sub("_", pattern)
|
|
1044
|
+
return f"{TOOL_NAME_PREFIX}{server_part}__{tool_part}"
|
|
1045
|
+
|
|
1046
|
+
|
|
1047
|
+
__all__ = [
|
|
1048
|
+
"HELPER_TOOL_NAMES",
|
|
1049
|
+
"MAX_TOOL_DESCRIPTION_CHARS",
|
|
1050
|
+
"MAX_TOOL_NAME_LENGTH",
|
|
1051
|
+
"MCP_EXTENSION_NAME",
|
|
1052
|
+
"MCP_PROMPT_SECTION",
|
|
1053
|
+
"TOOLS_LIST_CHANGED",
|
|
1054
|
+
"TOOL_NAME_PREFIX",
|
|
1055
|
+
"McpRuntime",
|
|
1056
|
+
"McpServerConnection",
|
|
1057
|
+
"McpServerState",
|
|
1058
|
+
"McpServerStatus",
|
|
1059
|
+
"mcp_tool_name",
|
|
1060
|
+
]
|