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,230 @@
|
|
|
1
|
+
"""工具目录缓存:``~/.braid/mcp_cache.json``。
|
|
2
|
+
|
|
3
|
+
缓存解决两个具体问题:
|
|
4
|
+
|
|
5
|
+
1. ``braid mcp get`` 与 ``/mcp show`` 不必为了显示工具名去启动服务器;
|
|
6
|
+
2. 服务器暂时连不上时,诊断里仍能看到"上次发现到了什么"。
|
|
7
|
+
|
|
8
|
+
缓存带服务器指纹。命令参数、地址或请求头变了,旧目录立刻失效——把上一份配置
|
|
9
|
+
的工具名展示给用户,比没有缓存更容易误导。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from datetime import datetime
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from braid_ai.types import JsonValue
|
|
22
|
+
from braid_mcp import McpPrompt, McpResource, McpResourceTemplate, McpTool
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
#: 缓存文件名(相对 ``~/.braid``)。
|
|
27
|
+
CACHE_FILE_NAME = "mcp_cache.json"
|
|
28
|
+
#: 缓存结构版本。字段不兼容时直接丢弃旧文件。
|
|
29
|
+
CACHE_VERSION = 1
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(slots=True)
|
|
33
|
+
class CachedServer:
|
|
34
|
+
"""一个服务器的上次发现结果。"""
|
|
35
|
+
|
|
36
|
+
fingerprint: str
|
|
37
|
+
tools: list[dict[str, JsonValue]] = field(default_factory=list[dict[str, JsonValue]])
|
|
38
|
+
resources: list[dict[str, JsonValue]] = field(default_factory=list[dict[str, JsonValue]])
|
|
39
|
+
resource_templates: list[dict[str, JsonValue]] = field(
|
|
40
|
+
default_factory=list[dict[str, JsonValue]]
|
|
41
|
+
)
|
|
42
|
+
prompts: list[dict[str, JsonValue]] = field(default_factory=list[dict[str, JsonValue]])
|
|
43
|
+
updated_at: str = ""
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def tool_names(self) -> list[str]:
|
|
47
|
+
return [str(item.get("name", "")) for item in self.tools if item.get("name")]
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def resource_uris(self) -> list[str]:
|
|
51
|
+
return [str(item.get("uri", "")) for item in self.resources if item.get("uri")]
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def prompt_names(self) -> list[str]:
|
|
55
|
+
return [str(item.get("name", "")) for item in self.prompts if item.get("name")]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class CatalogCache:
|
|
59
|
+
"""缓存文件的读写。结构坏了按空缓存处理。"""
|
|
60
|
+
|
|
61
|
+
def __init__(self, agent_dir: Path) -> None:
|
|
62
|
+
self.path = agent_dir / CACHE_FILE_NAME
|
|
63
|
+
|
|
64
|
+
def load(self) -> dict[str, CachedServer]:
|
|
65
|
+
if not self.path.is_file():
|
|
66
|
+
return {}
|
|
67
|
+
try:
|
|
68
|
+
payload: JsonValue = json.loads(self.path.read_text(encoding="utf-8-sig"))
|
|
69
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
70
|
+
logger.warning("忽略无法读取的 MCP 缓存 %s:%s", self.path, exc)
|
|
71
|
+
return {}
|
|
72
|
+
if not isinstance(payload, dict) or payload.get("version") != CACHE_VERSION:
|
|
73
|
+
return {}
|
|
74
|
+
raw_servers = payload.get("servers")
|
|
75
|
+
if not isinstance(raw_servers, dict):
|
|
76
|
+
return {}
|
|
77
|
+
servers: dict[str, CachedServer] = {}
|
|
78
|
+
for name, raw in raw_servers.items():
|
|
79
|
+
if not isinstance(raw, dict) or not isinstance(raw.get("fingerprint"), str):
|
|
80
|
+
continue
|
|
81
|
+
servers[str(name)] = CachedServer(
|
|
82
|
+
fingerprint=str(raw["fingerprint"]),
|
|
83
|
+
tools=_dict_list(raw.get("tools")),
|
|
84
|
+
resources=_dict_list(raw.get("resources")),
|
|
85
|
+
resource_templates=_dict_list(raw.get("resource_templates")),
|
|
86
|
+
prompts=_dict_list(raw.get("prompts")),
|
|
87
|
+
updated_at=str(raw.get("updated_at", "")),
|
|
88
|
+
)
|
|
89
|
+
return servers
|
|
90
|
+
|
|
91
|
+
def get(self, name: str, fingerprint: str) -> CachedServer | None:
|
|
92
|
+
cached = self.load().get(name)
|
|
93
|
+
if cached is None or cached.fingerprint != fingerprint:
|
|
94
|
+
return None
|
|
95
|
+
return cached
|
|
96
|
+
|
|
97
|
+
def save(
|
|
98
|
+
self,
|
|
99
|
+
name: str,
|
|
100
|
+
fingerprint: str,
|
|
101
|
+
*,
|
|
102
|
+
tools: list[McpTool],
|
|
103
|
+
resources: list[McpResource],
|
|
104
|
+
resource_templates: list[McpResourceTemplate],
|
|
105
|
+
prompts: list[McpPrompt],
|
|
106
|
+
) -> None:
|
|
107
|
+
servers = self.load()
|
|
108
|
+
servers[name] = CachedServer(
|
|
109
|
+
fingerprint=fingerprint,
|
|
110
|
+
tools=[_tool_to_json(tool) for tool in tools],
|
|
111
|
+
resources=[_resource_to_json(resource) for resource in resources],
|
|
112
|
+
resource_templates=[_template_to_json(template) for template in resource_templates],
|
|
113
|
+
prompts=[_prompt_to_json(prompt) for prompt in prompts],
|
|
114
|
+
updated_at=datetime.now().astimezone().isoformat(timespec="seconds"),
|
|
115
|
+
)
|
|
116
|
+
payload = {
|
|
117
|
+
"version": CACHE_VERSION,
|
|
118
|
+
"servers": {key: _server_to_json(value) for key, value in sorted(servers.items())},
|
|
119
|
+
}
|
|
120
|
+
temporary = self.path.with_name(self.path.name + ".tmp")
|
|
121
|
+
try:
|
|
122
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
123
|
+
temporary.write_text(
|
|
124
|
+
json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
|
125
|
+
)
|
|
126
|
+
os.replace(temporary, self.path)
|
|
127
|
+
except OSError as exc:
|
|
128
|
+
logger.warning("无法写入 MCP 缓存 %s:%s", self.path, exc)
|
|
129
|
+
temporary.unlink(missing_ok=True)
|
|
130
|
+
|
|
131
|
+
def remove(self, name: str) -> None:
|
|
132
|
+
servers = self.load()
|
|
133
|
+
if servers.pop(name, None) is None:
|
|
134
|
+
return
|
|
135
|
+
payload = {
|
|
136
|
+
"version": CACHE_VERSION,
|
|
137
|
+
"servers": {key: _server_to_json(value) for key, value in sorted(servers.items())},
|
|
138
|
+
}
|
|
139
|
+
try:
|
|
140
|
+
self.path.write_text(
|
|
141
|
+
json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
|
142
|
+
)
|
|
143
|
+
except OSError as exc:
|
|
144
|
+
logger.warning("无法写入 MCP 缓存 %s:%s", self.path, exc)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _dict_list(value: JsonValue | None) -> list[dict[str, JsonValue]]:
|
|
148
|
+
if not isinstance(value, list):
|
|
149
|
+
return []
|
|
150
|
+
return [dict(item) for item in value if isinstance(item, dict)]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _tool_to_json(tool: McpTool) -> dict[str, JsonValue]:
|
|
154
|
+
entry: dict[str, JsonValue] = {"name": tool.name, "inputSchema": dict(tool.input_schema)}
|
|
155
|
+
if tool.description is not None:
|
|
156
|
+
entry["description"] = tool.description
|
|
157
|
+
return entry
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _resource_to_json(resource: McpResource) -> dict[str, JsonValue]:
|
|
161
|
+
entry: dict[str, JsonValue] = {"uri": resource.uri, "name": resource.name}
|
|
162
|
+
if resource.description is not None:
|
|
163
|
+
entry["description"] = resource.description
|
|
164
|
+
if resource.mime_type is not None:
|
|
165
|
+
entry["mimeType"] = resource.mime_type
|
|
166
|
+
if resource.size is not None:
|
|
167
|
+
entry["size"] = resource.size
|
|
168
|
+
return entry
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _template_to_json(template: McpResourceTemplate) -> dict[str, JsonValue]:
|
|
172
|
+
entry: dict[str, JsonValue] = {
|
|
173
|
+
"uriTemplate": template.uri_template,
|
|
174
|
+
"name": template.name,
|
|
175
|
+
}
|
|
176
|
+
if template.description is not None:
|
|
177
|
+
entry["description"] = template.description
|
|
178
|
+
if template.mime_type is not None:
|
|
179
|
+
entry["mimeType"] = template.mime_type
|
|
180
|
+
return entry
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _prompt_to_json(prompt: McpPrompt) -> dict[str, JsonValue]:
|
|
184
|
+
entry: dict[str, JsonValue] = {"name": prompt.name}
|
|
185
|
+
if prompt.description is not None:
|
|
186
|
+
entry["description"] = prompt.description
|
|
187
|
+
if prompt.arguments:
|
|
188
|
+
entry["arguments"] = [
|
|
189
|
+
{"name": argument.name, "required": argument.required} for argument in prompt.arguments
|
|
190
|
+
]
|
|
191
|
+
return entry
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _server_to_json(server: CachedServer) -> dict[str, JsonValue]:
|
|
195
|
+
return {
|
|
196
|
+
"fingerprint": server.fingerprint,
|
|
197
|
+
"tools": list(server.tools),
|
|
198
|
+
"resources": list(server.resources),
|
|
199
|
+
"resource_templates": list(server.resource_templates),
|
|
200
|
+
"prompts": list(server.prompts),
|
|
201
|
+
"updated_at": server.updated_at,
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def tool_from_json(item: dict[str, JsonValue]) -> McpTool | None:
|
|
206
|
+
"""把缓存里的一条工具记录还原成 ``McpTool``。
|
|
207
|
+
|
|
208
|
+
缓存是上一进程写下的外部数据。名字或参数 Schema 缺失时跳过这一条,调用方
|
|
209
|
+
继续使用其余记录;整个缓存坏掉由 :meth:`CatalogCache.load` 统一处理。
|
|
210
|
+
"""
|
|
211
|
+
name = item.get("name")
|
|
212
|
+
schema = item.get("inputSchema")
|
|
213
|
+
if not isinstance(name, str) or not name or not isinstance(schema, dict):
|
|
214
|
+
logger.warning("忽略 MCP 缓存里结构不完整的工具记录:%r", item)
|
|
215
|
+
return None
|
|
216
|
+
description = item.get("description")
|
|
217
|
+
return McpTool(
|
|
218
|
+
name=name,
|
|
219
|
+
input_schema={str(key): value for key, value in schema.items()},
|
|
220
|
+
description=description if isinstance(description, str) else None,
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
__all__ = [
|
|
225
|
+
"CACHE_FILE_NAME",
|
|
226
|
+
"CACHE_VERSION",
|
|
227
|
+
"CachedServer",
|
|
228
|
+
"CatalogCache",
|
|
229
|
+
"tool_from_json",
|
|
230
|
+
]
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""MCP 工具目录:Eager 与 Lazy 两种注册策略共用的唯一事实源。
|
|
2
|
+
|
|
3
|
+
发现结果先进入目录,注册只是目录的一个视图。这样 ``tools/list_changed`` 之后
|
|
4
|
+
搜索、加载、权限判定与提示词目录都从同一份数据派生,不会出现"搜索能搜到、
|
|
5
|
+
调用却报未注册"的错位。
|
|
6
|
+
|
|
7
|
+
``loading`` 在目录里已经解析成最终值:单工具设置优先于服务器设置,服务器设置
|
|
8
|
+
优先于全局设置。注册逻辑不再重复这套优先级。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Literal
|
|
16
|
+
|
|
17
|
+
from braid_mcp import McpTool
|
|
18
|
+
|
|
19
|
+
type LoadingMode = Literal["lazy", "eager"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def estimate_tokens(text: str) -> int:
|
|
23
|
+
"""粗略 Token 估算:四个字符一个 Token。只用于预算裁剪,不用于计费。"""
|
|
24
|
+
return max(1, math.ceil(len(text) / 4))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(slots=True, frozen=True)
|
|
28
|
+
class ToolEntry:
|
|
29
|
+
"""目录里的一项。``provider_name`` 是模型看到的工具名。"""
|
|
30
|
+
|
|
31
|
+
server: str
|
|
32
|
+
tool: McpTool
|
|
33
|
+
provider_name: str
|
|
34
|
+
loading: LoadingMode
|
|
35
|
+
permission: str | None = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ToolCatalog:
|
|
39
|
+
"""全部服务器发现出来的工具,按服务器分组保存。"""
|
|
40
|
+
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
self._by_server: dict[str, list[ToolEntry]] = {}
|
|
43
|
+
self._by_name: dict[str, ToolEntry] = {}
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def entries(self) -> list[ToolEntry]:
|
|
47
|
+
return [entry for entries in self._by_server.values() for entry in entries]
|
|
48
|
+
|
|
49
|
+
def replace_server(self, server: str, entries: list[ToolEntry]) -> None:
|
|
50
|
+
for entry in self._by_server.get(server, []):
|
|
51
|
+
self._by_name.pop(entry.provider_name, None)
|
|
52
|
+
self._by_server[server] = list(entries)
|
|
53
|
+
for entry in entries:
|
|
54
|
+
self._by_name[entry.provider_name] = entry
|
|
55
|
+
|
|
56
|
+
def remove_server(self, server: str) -> None:
|
|
57
|
+
for entry in self._by_server.pop(server, []):
|
|
58
|
+
self._by_name.pop(entry.provider_name, None)
|
|
59
|
+
|
|
60
|
+
def get(self, provider_name: str) -> ToolEntry | None:
|
|
61
|
+
return self._by_name.get(provider_name)
|
|
62
|
+
|
|
63
|
+
def by_server(self, server: str) -> list[ToolEntry]:
|
|
64
|
+
return list(self._by_server.get(server, []))
|
|
65
|
+
|
|
66
|
+
def lazy(self) -> list[ToolEntry]:
|
|
67
|
+
return [entry for entry in self.entries if entry.loading == "lazy"]
|
|
68
|
+
|
|
69
|
+
def search(self, query: str, *, server: str | None = None, limit: int = 10) -> list[ToolEntry]:
|
|
70
|
+
"""按名字与描述打分。空查询返回前 ``limit`` 项。"""
|
|
71
|
+
candidates = self.by_server(server) if server is not None else self.entries
|
|
72
|
+
text = query.strip().lower()
|
|
73
|
+
if not text:
|
|
74
|
+
return candidates[:limit]
|
|
75
|
+
tokens = [token for token in text.split() if token]
|
|
76
|
+
scored: list[tuple[int, int, ToolEntry]] = []
|
|
77
|
+
for index, entry in enumerate(candidates):
|
|
78
|
+
haystack = " ".join(
|
|
79
|
+
(
|
|
80
|
+
entry.provider_name,
|
|
81
|
+
entry.tool.name,
|
|
82
|
+
entry.server,
|
|
83
|
+
entry.tool.description or "",
|
|
84
|
+
)
|
|
85
|
+
).lower()
|
|
86
|
+
score = _score(text, tokens, haystack, entry)
|
|
87
|
+
if score:
|
|
88
|
+
scored.append((score, -index, entry))
|
|
89
|
+
scored.sort(reverse=True)
|
|
90
|
+
return [entry for _, _, entry in scored[:limit]]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _score(text: str, tokens: list[str], haystack: str, entry: ToolEntry) -> int:
|
|
94
|
+
raw = entry.tool.name.lower()
|
|
95
|
+
provider = entry.provider_name.lower()
|
|
96
|
+
if text in (raw, provider):
|
|
97
|
+
return 100
|
|
98
|
+
if raw.startswith(text) or provider.startswith(text):
|
|
99
|
+
return 70
|
|
100
|
+
if text in raw or text in provider:
|
|
101
|
+
return 50
|
|
102
|
+
hits = sum(1 for token in tokens if token in haystack)
|
|
103
|
+
if hits == len(tokens):
|
|
104
|
+
return 30 + hits
|
|
105
|
+
return 10 + hits if hits else 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
__all__ = ["LoadingMode", "ToolCatalog", "ToolEntry", "estimate_tokens"]
|