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,928 @@
|
|
|
1
|
+
"""``braid mcp``:配置服务器、查看状态与处理 OAuth 授权。
|
|
2
|
+
|
|
3
|
+
```bash
|
|
4
|
+
braid mcp add fs -- npx -y @modelcontextprotocol/server-filesystem .
|
|
5
|
+
braid mcp list
|
|
6
|
+
braid mcp get fs
|
|
7
|
+
braid mcp remove fs
|
|
8
|
+
braid mcp login issue-tracker
|
|
9
|
+
braid mcp logout issue-tracker
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
``add`` 与 ``remove`` 只改 ``mcp.json`` 里的一项,保留其它顶层字段;``list`` 默认
|
|
13
|
+
只读配置与缓存,``--check`` 才会启动进程或连接远程服务。``login`` 需要浏览器与
|
|
14
|
+
回环回调,它不能塞进会话启动路径,所以是一条显式命令。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import asyncio
|
|
21
|
+
import copy
|
|
22
|
+
import json
|
|
23
|
+
import secrets
|
|
24
|
+
import sys
|
|
25
|
+
import threading
|
|
26
|
+
import webbrowser
|
|
27
|
+
from collections.abc import Sequence
|
|
28
|
+
from datetime import datetime
|
|
29
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from types import TracebackType
|
|
32
|
+
from typing import NoReturn, TextIO
|
|
33
|
+
from urllib.parse import parse_qs, urlparse
|
|
34
|
+
|
|
35
|
+
import httpx
|
|
36
|
+
|
|
37
|
+
from braid_ai.types import JsonValue
|
|
38
|
+
from braid_coding_agent.commands import CommandError
|
|
39
|
+
from braid_coding_agent.mcp.cache import CatalogCache
|
|
40
|
+
from braid_coding_agent.mcp.config import (
|
|
41
|
+
LoadedMcpConfig,
|
|
42
|
+
McpServerConfig,
|
|
43
|
+
load_mcp_config,
|
|
44
|
+
validate_remote_url,
|
|
45
|
+
)
|
|
46
|
+
from braid_coding_agent.mcp.config_store import (
|
|
47
|
+
SERVERS_KEY,
|
|
48
|
+
ConfigStoreError,
|
|
49
|
+
McpScope,
|
|
50
|
+
config_path,
|
|
51
|
+
read_document,
|
|
52
|
+
remove_server,
|
|
53
|
+
upsert_server,
|
|
54
|
+
)
|
|
55
|
+
from braid_coding_agent.mcp.runtime import McpRuntime
|
|
56
|
+
from braid_coding_agent.mcp.trust import (
|
|
57
|
+
is_trusted,
|
|
58
|
+
load_trust,
|
|
59
|
+
save_trust,
|
|
60
|
+
server_fingerprint,
|
|
61
|
+
)
|
|
62
|
+
from braid_coding_agent.settings import McpSettings
|
|
63
|
+
from braid_mcp import (
|
|
64
|
+
AuthorizationServerMetadata,
|
|
65
|
+
ClientRegistration,
|
|
66
|
+
OAuthError,
|
|
67
|
+
StoredAuthorization,
|
|
68
|
+
TokenStore,
|
|
69
|
+
build_authorization_url,
|
|
70
|
+
create_pkce_pair,
|
|
71
|
+
discover,
|
|
72
|
+
exchange_authorization_code,
|
|
73
|
+
register_client,
|
|
74
|
+
token_store,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
USAGE = """braid mcp <子命令> [服务器] [选项]
|
|
78
|
+
管理 MCP 服务器:添加、查看、删除与 OAuth 授权
|
|
79
|
+
|
|
80
|
+
子命令:
|
|
81
|
+
add <服务器> 写入一个服务器条目
|
|
82
|
+
list 列出已配置服务器(status 同义)
|
|
83
|
+
get <服务器> 查看配置、缓存与令牌状态
|
|
84
|
+
remove <服务器> 删除条目,并清理令牌、信任记录与缓存
|
|
85
|
+
login <服务器> 浏览器完成 OAuth 授权,把令牌写到本机
|
|
86
|
+
logout <服务器> 删除本机保存的令牌
|
|
87
|
+
|
|
88
|
+
add 的传输:
|
|
89
|
+
--command CMD --arg VALUE ... stdio:启动本机进程(也可用 `-- CMD ARG...`)
|
|
90
|
+
--url URL http / sse:远程 Streamable HTTP 或旧版 SSE
|
|
91
|
+
--transport ws --url ws://... WebSocket
|
|
92
|
+
|
|
93
|
+
add 的其它选项:
|
|
94
|
+
--scope global|project 写入 ~/.braid/mcp.json 或 <cwd>/.braid/mcp.json
|
|
95
|
+
--env KEY=VALUE stdio 进程环境,可重复
|
|
96
|
+
--header "Name: value" 远程请求头,可重复
|
|
97
|
+
--oauth 启用 OAuth(http / sse)
|
|
98
|
+
--oauth-scope SCOPE 请求的 scope,可重复
|
|
99
|
+
--loading lazy|eager 全局加载方式
|
|
100
|
+
--eager-tool NAME 单个工具预加载,可重复
|
|
101
|
+
--disable-tool NAME 单个工具不注册,可重复
|
|
102
|
+
--allow / --ask / --deny PATTERN 调用策略,可重复
|
|
103
|
+
--timeout 秒 / --connect-timeout 秒
|
|
104
|
+
--trusted 跳过首次连接的风险确认
|
|
105
|
+
--disabled 写入但默认不连接
|
|
106
|
+
--force 覆盖同名条目
|
|
107
|
+
|
|
108
|
+
list / get:
|
|
109
|
+
--check 连接一次并显示真实状态
|
|
110
|
+
--trust --check 时连接未信任的服务器
|
|
111
|
+
|
|
112
|
+
通用:
|
|
113
|
+
--cwd PATH 工作目录(决定读哪个项目的 mcp.json)
|
|
114
|
+
-h, --help 显示本帮助"""
|
|
115
|
+
|
|
116
|
+
#: 等待浏览器回调的默认超时。
|
|
117
|
+
LOGIN_TIMEOUT_S = 300.0
|
|
118
|
+
#: 授权页与令牌端点的网络超时。
|
|
119
|
+
OAUTH_HTTP_TIMEOUT_S = 30.0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class _Parser(argparse.ArgumentParser):
|
|
123
|
+
"""参数错误抛 :class:`CommandError`,由 CLI 统一翻成退出码。"""
|
|
124
|
+
|
|
125
|
+
def error(self, message: str) -> NoReturn:
|
|
126
|
+
raise CommandError(message)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def run(argv: Sequence[str], *, agent_dir: Path, cwd: str, out: TextIO | None = None) -> int:
|
|
130
|
+
"""子命令入口。返回退出码;错误抛 :class:`CommandError`。"""
|
|
131
|
+
stream = out if out is not None else sys.stdout
|
|
132
|
+
values = list(argv)
|
|
133
|
+
if not values or values[0] in ("-h", "--help"):
|
|
134
|
+
print(USAGE, file=stream)
|
|
135
|
+
return 0
|
|
136
|
+
trailing: list[str] = []
|
|
137
|
+
if "--" in values:
|
|
138
|
+
index = values.index("--")
|
|
139
|
+
trailing = values[index + 1 :]
|
|
140
|
+
values = values[:index]
|
|
141
|
+
values = _keep_dashed_values(values)
|
|
142
|
+
args = _parser().parse_args(values)
|
|
143
|
+
if getattr(args, "help", False) or args.command is None:
|
|
144
|
+
print(USAGE, file=stream)
|
|
145
|
+
return 0
|
|
146
|
+
target_cwd = args.cwd or cwd
|
|
147
|
+
if args.command == "add":
|
|
148
|
+
_run_add(args, trailing, agent_dir=agent_dir, cwd=target_cwd, out=stream)
|
|
149
|
+
return 0
|
|
150
|
+
if args.command in ("list", "status"):
|
|
151
|
+
await _run_list(args, agent_dir=agent_dir, cwd=target_cwd, out=stream)
|
|
152
|
+
return 0
|
|
153
|
+
if args.command == "get":
|
|
154
|
+
await _run_get(args, agent_dir=agent_dir, cwd=target_cwd, out=stream)
|
|
155
|
+
return 0
|
|
156
|
+
if args.command == "remove":
|
|
157
|
+
_run_remove(args, agent_dir=agent_dir, cwd=target_cwd, out=stream)
|
|
158
|
+
return 0
|
|
159
|
+
if args.command == "logout":
|
|
160
|
+
removed = token_store(agent_dir).remove(args.name)
|
|
161
|
+
print(
|
|
162
|
+
f"已删除 {args.name} 的本地令牌" if removed else f"{args.name} 没有保存过令牌",
|
|
163
|
+
file=stream,
|
|
164
|
+
)
|
|
165
|
+
return 0
|
|
166
|
+
await _run_login(
|
|
167
|
+
args,
|
|
168
|
+
agent_dir=agent_dir,
|
|
169
|
+
cwd=target_cwd,
|
|
170
|
+
out=stream,
|
|
171
|
+
)
|
|
172
|
+
return 0
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _parser() -> argparse.ArgumentParser:
|
|
176
|
+
parser = _Parser(prog="braid mcp", add_help=False, allow_abbrev=False)
|
|
177
|
+
sub = parser.add_subparsers(dest="command")
|
|
178
|
+
|
|
179
|
+
add = sub.add_parser("add", add_help=False, allow_abbrev=False)
|
|
180
|
+
add.add_argument("name")
|
|
181
|
+
add.add_argument("--transport", choices=("stdio", "http", "sse", "ws"))
|
|
182
|
+
add.add_argument("--command", dest="server_command")
|
|
183
|
+
add.add_argument("--arg", dest="server_args", action="append", default=[])
|
|
184
|
+
add.add_argument("--url")
|
|
185
|
+
add.add_argument("--env", action="append", default=[])
|
|
186
|
+
add.add_argument("--header", action="append", default=[])
|
|
187
|
+
add.add_argument("--scope", choices=("global", "project"), default="global")
|
|
188
|
+
add.add_argument("--loading", choices=("lazy", "eager"))
|
|
189
|
+
add.add_argument("--timeout", type=_positive_number)
|
|
190
|
+
add.add_argument("--connect-timeout", type=_positive_number)
|
|
191
|
+
add.add_argument("--description")
|
|
192
|
+
add.add_argument("--server-cwd")
|
|
193
|
+
add.add_argument("--trusted", action="store_true")
|
|
194
|
+
add.add_argument("--disabled", action="store_true")
|
|
195
|
+
add.add_argument("--oauth", action="store_true")
|
|
196
|
+
add.add_argument("--oauth-client-id")
|
|
197
|
+
add.add_argument("--oauth-client-secret")
|
|
198
|
+
add.add_argument("--oauth-scope", action="append", default=[])
|
|
199
|
+
add.add_argument("--oauth-server")
|
|
200
|
+
add.add_argument("--disable-tool", action="append", default=[])
|
|
201
|
+
add.add_argument("--eager-tool", action="append", default=[])
|
|
202
|
+
add.add_argument("--allow", action="append", default=[])
|
|
203
|
+
add.add_argument("--ask", action="append", default=[])
|
|
204
|
+
add.add_argument("--deny", action="append", default=[])
|
|
205
|
+
add.add_argument("--force", action="store_true")
|
|
206
|
+
_add_common(add)
|
|
207
|
+
|
|
208
|
+
for name in ("list", "status"):
|
|
209
|
+
listing = sub.add_parser(name, add_help=False, allow_abbrev=False)
|
|
210
|
+
listing.add_argument("--check", action="store_true")
|
|
211
|
+
listing.add_argument("--trust", action="store_true")
|
|
212
|
+
_add_common(listing)
|
|
213
|
+
|
|
214
|
+
get = sub.add_parser("get", add_help=False, allow_abbrev=False)
|
|
215
|
+
get.add_argument("name")
|
|
216
|
+
get.add_argument("--check", action="store_true")
|
|
217
|
+
get.add_argument("--trust", action="store_true")
|
|
218
|
+
_add_common(get)
|
|
219
|
+
|
|
220
|
+
remove = sub.add_parser("remove", add_help=False, allow_abbrev=False)
|
|
221
|
+
remove.add_argument("name")
|
|
222
|
+
remove.add_argument("--scope", choices=("global", "project"))
|
|
223
|
+
_add_common(remove)
|
|
224
|
+
|
|
225
|
+
login = sub.add_parser("login", add_help=False, allow_abbrev=False)
|
|
226
|
+
login.add_argument("name")
|
|
227
|
+
login.add_argument("--no-browser", action="store_true")
|
|
228
|
+
login.add_argument("--timeout", type=_positive_number, default=LOGIN_TIMEOUT_S)
|
|
229
|
+
_add_common(login)
|
|
230
|
+
|
|
231
|
+
logout = sub.add_parser("logout", add_help=False, allow_abbrev=False)
|
|
232
|
+
logout.add_argument("name")
|
|
233
|
+
_add_common(logout)
|
|
234
|
+
return parser
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
#: 这些选项后面的值可能以连字符开头(例如 ``--arg -y``),argparse 会当成新选项。
|
|
238
|
+
_VALUE_FLAGS = ("--arg", "--env", "--header")
|
|
239
|
+
#: 出现在值位置说明用户漏了参数,留给 argparse 报错。
|
|
240
|
+
_OPTION_NAMES = frozenset(
|
|
241
|
+
{
|
|
242
|
+
"--transport",
|
|
243
|
+
"--command",
|
|
244
|
+
"--arg",
|
|
245
|
+
"--url",
|
|
246
|
+
"--env",
|
|
247
|
+
"--header",
|
|
248
|
+
"--scope",
|
|
249
|
+
"--loading",
|
|
250
|
+
"--timeout",
|
|
251
|
+
"--connect-timeout",
|
|
252
|
+
"--description",
|
|
253
|
+
"--server-cwd",
|
|
254
|
+
"--trusted",
|
|
255
|
+
"--disabled",
|
|
256
|
+
"--oauth",
|
|
257
|
+
"--oauth-client-id",
|
|
258
|
+
"--oauth-client-secret",
|
|
259
|
+
"--oauth-scope",
|
|
260
|
+
"--oauth-server",
|
|
261
|
+
"--disable-tool",
|
|
262
|
+
"--eager-tool",
|
|
263
|
+
"--allow",
|
|
264
|
+
"--ask",
|
|
265
|
+
"--deny",
|
|
266
|
+
"--force",
|
|
267
|
+
"--cwd",
|
|
268
|
+
"--check",
|
|
269
|
+
"--trust",
|
|
270
|
+
"--no-browser",
|
|
271
|
+
"-h",
|
|
272
|
+
"--help",
|
|
273
|
+
}
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _keep_dashed_values(values: list[str]) -> list[str]:
|
|
278
|
+
"""把 ``--arg -y`` 改写成 ``--arg=-y``,让以连字符开头的值原样进入配置。"""
|
|
279
|
+
result: list[str] = []
|
|
280
|
+
index = 0
|
|
281
|
+
while index < len(values):
|
|
282
|
+
item = values[index]
|
|
283
|
+
if (
|
|
284
|
+
item in _VALUE_FLAGS
|
|
285
|
+
and index + 1 < len(values)
|
|
286
|
+
and values[index + 1] not in _OPTION_NAMES
|
|
287
|
+
):
|
|
288
|
+
result.append(f"{item}={values[index + 1]}")
|
|
289
|
+
index += 2
|
|
290
|
+
continue
|
|
291
|
+
result.append(item)
|
|
292
|
+
index += 1
|
|
293
|
+
return result
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _add_common(parser: argparse.ArgumentParser) -> None:
|
|
297
|
+
parser.add_argument("--cwd")
|
|
298
|
+
parser.add_argument("-h", "--help", action="store_true")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _positive_number(text: str) -> float:
|
|
302
|
+
try:
|
|
303
|
+
value = float(text)
|
|
304
|
+
except ValueError as error:
|
|
305
|
+
raise argparse.ArgumentTypeError(f"需要一个数字,收到 {text!r}") from error
|
|
306
|
+
if value <= 0:
|
|
307
|
+
raise argparse.ArgumentTypeError("超时必须大于 0")
|
|
308
|
+
return value
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
# ------------------------------------------------------------------ 添加
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _run_add(
|
|
315
|
+
args: argparse.Namespace,
|
|
316
|
+
trailing: list[str],
|
|
317
|
+
*,
|
|
318
|
+
agent_dir: Path,
|
|
319
|
+
cwd: str,
|
|
320
|
+
out: TextIO,
|
|
321
|
+
) -> None:
|
|
322
|
+
"""构造一条 ``mcpServers`` 条目并写回配置文件。"""
|
|
323
|
+
command: str | None = args.server_command
|
|
324
|
+
url: str | None = args.url
|
|
325
|
+
transport: str | None = args.transport
|
|
326
|
+
arguments = list(args.server_args)
|
|
327
|
+
|
|
328
|
+
if trailing:
|
|
329
|
+
if command is not None or url is not None:
|
|
330
|
+
raise CommandError("`--` 后面的命令与 --command / --url 只能给一种")
|
|
331
|
+
command = trailing[0]
|
|
332
|
+
arguments.extend(trailing[1:])
|
|
333
|
+
if command is not None and url is not None:
|
|
334
|
+
raise CommandError("command(stdio)与 url(远程)只能给一个")
|
|
335
|
+
if command is None and url is None:
|
|
336
|
+
raise CommandError("缺少 --command 或 --url(也可用 `-- CMD ARG...`)")
|
|
337
|
+
|
|
338
|
+
if command is not None:
|
|
339
|
+
if not command.strip():
|
|
340
|
+
raise CommandError("--command 不能为空")
|
|
341
|
+
if transport not in (None, "stdio"):
|
|
342
|
+
raise CommandError(f"command 只能配 stdio,收到 {transport}")
|
|
343
|
+
transport = "stdio"
|
|
344
|
+
else:
|
|
345
|
+
if transport is None:
|
|
346
|
+
transport = "http"
|
|
347
|
+
if transport == "stdio":
|
|
348
|
+
raise CommandError("url 不能配 stdio;请用 http、sse 或 ws")
|
|
349
|
+
|
|
350
|
+
entry: dict[str, JsonValue] = {"type": transport}
|
|
351
|
+
if transport == "stdio":
|
|
352
|
+
entry["command"] = command
|
|
353
|
+
if arguments:
|
|
354
|
+
entry["args"] = [str(item) for item in arguments]
|
|
355
|
+
if args.server_cwd is not None:
|
|
356
|
+
entry["cwd"] = args.server_cwd
|
|
357
|
+
if args.header or args.oauth or args.oauth_scope or args.oauth_client_id:
|
|
358
|
+
raise CommandError("headers 与 oauth 只用于远程服务器")
|
|
359
|
+
env = _pairs(args.env, separator="=", flag="--env")
|
|
360
|
+
if env:
|
|
361
|
+
entry["env"] = env
|
|
362
|
+
else:
|
|
363
|
+
if arguments:
|
|
364
|
+
raise CommandError("--arg 只用于 stdio;远程服务器没有启动参数")
|
|
365
|
+
if args.env or args.server_cwd is not None:
|
|
366
|
+
raise CommandError("--env 与 --server-cwd 只用于 stdio")
|
|
367
|
+
assert url is not None
|
|
368
|
+
problem = validate_remote_url(url, transport) # type: ignore[arg-type]
|
|
369
|
+
if problem is not None:
|
|
370
|
+
raise CommandError(problem)
|
|
371
|
+
entry["url"] = url
|
|
372
|
+
headers = _headers(args.header)
|
|
373
|
+
if headers:
|
|
374
|
+
entry["headers"] = headers
|
|
375
|
+
oauth = _oauth_entry(args, transport)
|
|
376
|
+
if oauth is not None:
|
|
377
|
+
entry["oauth"] = oauth
|
|
378
|
+
|
|
379
|
+
if args.loading is not None:
|
|
380
|
+
entry["loading"] = args.loading
|
|
381
|
+
if args.timeout is not None:
|
|
382
|
+
entry["timeout"] = _json_number(args.timeout)
|
|
383
|
+
if args.connect_timeout is not None:
|
|
384
|
+
entry["connectTimeout"] = _json_number(args.connect_timeout)
|
|
385
|
+
if args.description:
|
|
386
|
+
entry["description"] = args.description
|
|
387
|
+
if args.trusted:
|
|
388
|
+
entry["trusted"] = True
|
|
389
|
+
if args.disabled:
|
|
390
|
+
entry["enabled"] = False
|
|
391
|
+
tools = _tool_settings(args.disable_tool, args.eager_tool)
|
|
392
|
+
if tools:
|
|
393
|
+
entry["tools"] = tools
|
|
394
|
+
permissions = _permissions(args.allow, args.ask, args.deny)
|
|
395
|
+
if permissions:
|
|
396
|
+
entry["permissions"] = permissions
|
|
397
|
+
|
|
398
|
+
scope: McpScope = args.scope
|
|
399
|
+
try:
|
|
400
|
+
path = upsert_server(agent_dir, cwd, scope, args.name, entry, replace=args.force)
|
|
401
|
+
except ConfigStoreError as exc:
|
|
402
|
+
raise CommandError(str(exc)) from exc
|
|
403
|
+
print(f"已添加 {args.name} [{transport}]({scope}):{path}", file=out)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _oauth_entry(args: argparse.Namespace, transport: str) -> dict[str, JsonValue] | None:
|
|
407
|
+
wants = args.oauth or bool(
|
|
408
|
+
args.oauth_client_id or args.oauth_client_secret or args.oauth_scope or args.oauth_server
|
|
409
|
+
)
|
|
410
|
+
if not wants:
|
|
411
|
+
return None
|
|
412
|
+
if transport == "ws":
|
|
413
|
+
raise CommandError("WebSocket 传输的 OAuth 尚未接线;请改用 http 或 sse")
|
|
414
|
+
oauth: dict[str, JsonValue] = {}
|
|
415
|
+
if args.oauth_client_id:
|
|
416
|
+
oauth["client_id"] = args.oauth_client_id
|
|
417
|
+
if args.oauth_client_secret:
|
|
418
|
+
oauth["client_secret"] = args.oauth_client_secret
|
|
419
|
+
if args.oauth_scope:
|
|
420
|
+
oauth["scopes"] = [str(scope) for scope in args.oauth_scope]
|
|
421
|
+
if args.oauth_server:
|
|
422
|
+
oauth["authorization_server"] = args.oauth_server
|
|
423
|
+
return oauth
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _pairs(values: list[str], *, separator: str, flag: str) -> dict[str, JsonValue]:
|
|
427
|
+
result: dict[str, JsonValue] = {}
|
|
428
|
+
for item in values:
|
|
429
|
+
key, found, value = item.partition(separator)
|
|
430
|
+
if not found or not key.strip():
|
|
431
|
+
raise CommandError(f"{flag} 需要 KEY{separator}VALUE,收到 {item!r}")
|
|
432
|
+
result[key.strip()] = value
|
|
433
|
+
return result
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _headers(values: list[str]) -> dict[str, JsonValue]:
|
|
437
|
+
result: dict[str, JsonValue] = {}
|
|
438
|
+
for item in values:
|
|
439
|
+
name, found, value = item.partition(":")
|
|
440
|
+
if not found or not name.strip():
|
|
441
|
+
raise CommandError(f'--header 需要 "Name: value",收到 {item!r}')
|
|
442
|
+
result[name.strip()] = value.strip()
|
|
443
|
+
return result
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _tool_settings(disabled: list[str], eager: list[str]) -> dict[str, JsonValue]:
|
|
447
|
+
tools: dict[str, JsonValue] = {}
|
|
448
|
+
for name in disabled:
|
|
449
|
+
if not name:
|
|
450
|
+
raise CommandError("--disable-tool 需要一个工具名")
|
|
451
|
+
tools[name] = {"enabled": False}
|
|
452
|
+
for name in eager:
|
|
453
|
+
if not name:
|
|
454
|
+
raise CommandError("--eager-tool 需要一个工具名")
|
|
455
|
+
current = tools.get(name)
|
|
456
|
+
if isinstance(current, dict):
|
|
457
|
+
current["eager"] = True
|
|
458
|
+
else:
|
|
459
|
+
tools[name] = {"eager": True}
|
|
460
|
+
return tools
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _permissions(allow: list[str], ask: list[str], deny: list[str]) -> dict[str, JsonValue]:
|
|
464
|
+
result: dict[str, JsonValue] = {}
|
|
465
|
+
if allow:
|
|
466
|
+
result["allow"] = [str(pattern) for pattern in allow]
|
|
467
|
+
if ask:
|
|
468
|
+
result["ask"] = [str(pattern) for pattern in ask]
|
|
469
|
+
if deny:
|
|
470
|
+
result["deny"] = [str(pattern) for pattern in deny]
|
|
471
|
+
return result
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _json_number(value: float) -> int | float:
|
|
475
|
+
return int(value) if value.is_integer() else value
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
# ------------------------------------------------------------------ 列表与详情
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
async def _run_list(args: argparse.Namespace, *, agent_dir: Path, cwd: str, out: TextIO) -> None:
|
|
482
|
+
loaded = _load_effective(agent_dir, cwd)
|
|
483
|
+
scopes = _scope_entries(agent_dir, cwd)
|
|
484
|
+
if not loaded.servers:
|
|
485
|
+
print(
|
|
486
|
+
"没有配置 MCP 服务器(~/.braid/mcp.json 或 <工作目录>/.braid/mcp.json)",
|
|
487
|
+
file=out,
|
|
488
|
+
)
|
|
489
|
+
return
|
|
490
|
+
store = token_store(agent_dir)
|
|
491
|
+
records = load_trust(agent_dir)
|
|
492
|
+
cache = CatalogCache(agent_dir)
|
|
493
|
+
names = sorted(loaded.servers)
|
|
494
|
+
print(f"MCP 服务器({len(names)} 个):", file=out)
|
|
495
|
+
for name in names:
|
|
496
|
+
server = loaded.servers[name]
|
|
497
|
+
scope = scopes[name][0] if name in scopes else "global"
|
|
498
|
+
enabled = "启用" if server.enabled else "禁用"
|
|
499
|
+
print(f" {name} [{server.transport}] {scope} {enabled}", file=out)
|
|
500
|
+
print(f" {server.endpoint}", file=out)
|
|
501
|
+
trust = (
|
|
502
|
+
"已信任"
|
|
503
|
+
if server.trusted or is_trusted(records, server)
|
|
504
|
+
else "未信任(首次连接会询问)"
|
|
505
|
+
)
|
|
506
|
+
print(f" 信任:{trust}", file=out)
|
|
507
|
+
if server.transport in ("http", "sse") and server.oauth is not None:
|
|
508
|
+
print(f" OAuth:{_token_summary(store, name)}", file=out)
|
|
509
|
+
elif server.transport in ("http", "sse", "ws"):
|
|
510
|
+
print(" OAuth:未配置", file=out)
|
|
511
|
+
_print_cache(cache, server, out=out)
|
|
512
|
+
if args.check:
|
|
513
|
+
await _check_servers(
|
|
514
|
+
list(loaded.servers.values()),
|
|
515
|
+
agent_dir=agent_dir,
|
|
516
|
+
cwd=cwd,
|
|
517
|
+
trust_all=args.trust,
|
|
518
|
+
out=out,
|
|
519
|
+
)
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
async def _run_get(args: argparse.Namespace, *, agent_dir: Path, cwd: str, out: TextIO) -> None:
|
|
523
|
+
loaded = _load_effective(agent_dir, cwd)
|
|
524
|
+
server = loaded.servers.get(args.name)
|
|
525
|
+
if server is None:
|
|
526
|
+
known = ", ".join(sorted(loaded.servers)) or "(配置里没有服务器)"
|
|
527
|
+
raise CommandError(f"未知 MCP 服务器: {args.name}(可用: {known})")
|
|
528
|
+
scopes = _scope_entries(agent_dir, cwd)
|
|
529
|
+
scope, path, raw = scopes.get(args.name, ("global", config_path(agent_dir, cwd, "global"), {}))
|
|
530
|
+
print(f"{args.name} [{server.transport}] 来源:{path}({scope})", file=out)
|
|
531
|
+
print(f" 地址:{server.endpoint}", file=out)
|
|
532
|
+
print(f" 启用:{'是' if server.enabled else '否'}", file=out)
|
|
533
|
+
print(
|
|
534
|
+
f" 超时:调用 {server.timeout_s:g} 秒"
|
|
535
|
+
+ (
|
|
536
|
+
f" · 连接 {server.connect_timeout_s:g} 秒"
|
|
537
|
+
if server.connect_timeout_s is not None
|
|
538
|
+
else ""
|
|
539
|
+
),
|
|
540
|
+
file=out,
|
|
541
|
+
)
|
|
542
|
+
print(f" 配置:\n{json.dumps(_redact_entry(raw), ensure_ascii=False, indent=4)}", file=out)
|
|
543
|
+
_print_cache(CatalogCache(agent_dir), server, out=out)
|
|
544
|
+
if server.transport in ("http", "sse") and server.oauth is not None:
|
|
545
|
+
print(f" OAuth:{_token_summary(token_store(agent_dir), args.name)}", file=out)
|
|
546
|
+
if args.check:
|
|
547
|
+
await _check_servers(
|
|
548
|
+
[server],
|
|
549
|
+
agent_dir=agent_dir,
|
|
550
|
+
cwd=cwd,
|
|
551
|
+
trust_all=args.trust,
|
|
552
|
+
out=out,
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _print_cache(cache: CatalogCache, server: McpServerConfig, *, out: TextIO) -> None:
|
|
557
|
+
cached = cache.get(server.name, server_fingerprint(server))
|
|
558
|
+
if cached is None:
|
|
559
|
+
print(" 缓存:无(连接成功后写入工具目录)", file=out)
|
|
560
|
+
return
|
|
561
|
+
print(
|
|
562
|
+
f" 缓存:{len(cached.tool_names)} 个工具 · "
|
|
563
|
+
f"{len(cached.resource_uris)} 个资源 · {len(cached.prompt_names)} 个提示词"
|
|
564
|
+
+ (f"({cached.updated_at})" if cached.updated_at else ""),
|
|
565
|
+
file=out,
|
|
566
|
+
)
|
|
567
|
+
if cached.tool_names:
|
|
568
|
+
print(f" 工具:{', '.join(cached.tool_names)}", file=out)
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
async def _check_servers(
|
|
572
|
+
servers: Sequence[McpServerConfig],
|
|
573
|
+
*,
|
|
574
|
+
agent_dir: Path,
|
|
575
|
+
cwd: str,
|
|
576
|
+
trust_all: bool,
|
|
577
|
+
out: TextIO,
|
|
578
|
+
) -> None:
|
|
579
|
+
records = load_trust(agent_dir)
|
|
580
|
+
selected: list[McpServerConfig] = []
|
|
581
|
+
for server in servers:
|
|
582
|
+
if not server.enabled:
|
|
583
|
+
continue
|
|
584
|
+
if trust_all or server.trusted or is_trusted(records, server):
|
|
585
|
+
selected.append(server)
|
|
586
|
+
skipped = [
|
|
587
|
+
server.name
|
|
588
|
+
for server in servers
|
|
589
|
+
if server.enabled and not (trust_all or server.trusted or is_trusted(records, server))
|
|
590
|
+
]
|
|
591
|
+
if not selected:
|
|
592
|
+
print("连接检查:没有可检查的服务器", file=out)
|
|
593
|
+
if skipped:
|
|
594
|
+
print(f" 未信任,跳过:{', '.join(skipped)}(加 --trust)", file=out)
|
|
595
|
+
return
|
|
596
|
+
print("连接检查:", file=out)
|
|
597
|
+
runtime = McpRuntime(
|
|
598
|
+
selected,
|
|
599
|
+
cwd=cwd,
|
|
600
|
+
agent_dir=agent_dir,
|
|
601
|
+
settings=McpSettings(),
|
|
602
|
+
close_on_session_shutdown=False,
|
|
603
|
+
)
|
|
604
|
+
try:
|
|
605
|
+
await runtime.connect()
|
|
606
|
+
for status in runtime.statuses():
|
|
607
|
+
line = (
|
|
608
|
+
f" {status.name}: {status.state} · {status.tool_count} 个工具"
|
|
609
|
+
f" · {status.resource_count} 个资源 · {status.prompt_count} 个提示词"
|
|
610
|
+
)
|
|
611
|
+
if status.error:
|
|
612
|
+
line += f"\n 最近错误:{' '.join(status.error.split())}"
|
|
613
|
+
print(line, file=out)
|
|
614
|
+
finally:
|
|
615
|
+
await runtime.close()
|
|
616
|
+
if skipped:
|
|
617
|
+
print(f" 未信任,跳过:{', '.join(skipped)}(加 --trust)", file=out)
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _scope_entries(
|
|
621
|
+
agent_dir: Path, cwd: str
|
|
622
|
+
) -> dict[str, tuple[McpScope, Path, dict[str, JsonValue]]]:
|
|
623
|
+
"""服务器名 → 最高优先级文件里的原始条目。"""
|
|
624
|
+
entries: dict[str, tuple[McpScope, Path, dict[str, JsonValue]]] = {}
|
|
625
|
+
for scope in ("global", "project"):
|
|
626
|
+
path = config_path(agent_dir, cwd, scope)
|
|
627
|
+
if not path.is_file():
|
|
628
|
+
continue
|
|
629
|
+
try:
|
|
630
|
+
document = read_document(path)
|
|
631
|
+
except ConfigStoreError as exc:
|
|
632
|
+
print(str(exc), file=sys.stderr)
|
|
633
|
+
continue
|
|
634
|
+
raw = document.get(SERVERS_KEY, {})
|
|
635
|
+
if not isinstance(raw, dict):
|
|
636
|
+
continue
|
|
637
|
+
for name, entry in raw.items():
|
|
638
|
+
if isinstance(entry, dict):
|
|
639
|
+
entries[str(name)] = (scope, path, entry)
|
|
640
|
+
return entries
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _load_effective(agent_dir: Path, cwd: str) -> LoadedMcpConfig:
|
|
644
|
+
loaded = load_mcp_config(agent_dir, cwd)
|
|
645
|
+
for message in loaded.errors:
|
|
646
|
+
print(message, file=sys.stderr)
|
|
647
|
+
return loaded
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
_SENSITIVE = ("authorization", "token", "secret", "password", "api-key", "apikey", "credential")
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def _redact_entry(entry: dict[str, JsonValue]) -> dict[str, JsonValue]:
|
|
654
|
+
"""打印配置前遮住请求头、环境变量与 client_secret 里的凭证。"""
|
|
655
|
+
copy_entry = copy.deepcopy(entry)
|
|
656
|
+
headers = copy_entry.get("headers")
|
|
657
|
+
if isinstance(headers, dict):
|
|
658
|
+
for key, value in headers.items():
|
|
659
|
+
if isinstance(value, str) and _looks_secret(key, value):
|
|
660
|
+
headers[key] = "***"
|
|
661
|
+
env = copy_entry.get("env")
|
|
662
|
+
if isinstance(env, dict):
|
|
663
|
+
for key, value in env.items():
|
|
664
|
+
if isinstance(value, str) and _looks_secret(key, value):
|
|
665
|
+
env[key] = "***"
|
|
666
|
+
oauth = copy_entry.get("oauth")
|
|
667
|
+
if isinstance(oauth, dict) and isinstance(oauth.get("client_secret"), str):
|
|
668
|
+
oauth["client_secret"] = "***"
|
|
669
|
+
return copy_entry
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _looks_secret(name: str, value: str) -> bool:
|
|
673
|
+
if "${" in value:
|
|
674
|
+
return False
|
|
675
|
+
lowered = name.lower()
|
|
676
|
+
return any(word in lowered for word in _SENSITIVE)
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
# ------------------------------------------------------------------ 删除
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def _run_remove(args: argparse.Namespace, *, agent_dir: Path, cwd: str, out: TextIO) -> None:
|
|
683
|
+
scopes: tuple[McpScope, ...] = ("project", "global") if args.scope is None else (args.scope,)
|
|
684
|
+
removed: tuple[McpScope, Path] | None = None
|
|
685
|
+
for scope in scopes:
|
|
686
|
+
try:
|
|
687
|
+
path = config_path(agent_dir, cwd, scope)
|
|
688
|
+
if remove_server(agent_dir, cwd, scope, args.name):
|
|
689
|
+
removed = (scope, path)
|
|
690
|
+
break
|
|
691
|
+
except ConfigStoreError as exc:
|
|
692
|
+
raise CommandError(str(exc)) from exc
|
|
693
|
+
if removed is None:
|
|
694
|
+
raise CommandError(f"配置里没有服务器 {args.name}")
|
|
695
|
+
scope, path = removed
|
|
696
|
+
CatalogCache(agent_dir).remove(args.name)
|
|
697
|
+
token_store(agent_dir).remove(args.name)
|
|
698
|
+
records = load_trust(agent_dir)
|
|
699
|
+
if records.pop(args.name, None) is not None:
|
|
700
|
+
save_trust(agent_dir, records)
|
|
701
|
+
print(f"已删除 {args.name}({scope}):{path}", file=out)
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
# ------------------------------------------------------------------ 授权
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
async def _run_login(args: argparse.Namespace, *, agent_dir: Path, cwd: str, out: TextIO) -> None:
|
|
708
|
+
loaded = _load_effective(agent_dir, cwd)
|
|
709
|
+
server = loaded.servers.get(args.name)
|
|
710
|
+
if server is None:
|
|
711
|
+
known = ", ".join(sorted(loaded.servers)) or "(配置里没有服务器)"
|
|
712
|
+
raise CommandError(f"未知 MCP 服务器: {args.name}(可用: {known})")
|
|
713
|
+
await _login(
|
|
714
|
+
server,
|
|
715
|
+
agent_dir=agent_dir,
|
|
716
|
+
open_browser=not args.no_browser,
|
|
717
|
+
timeout=args.timeout,
|
|
718
|
+
out=out,
|
|
719
|
+
)
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def _token_summary(store: TokenStore, name: str) -> str:
|
|
723
|
+
stored = store.load(name)
|
|
724
|
+
if stored is None:
|
|
725
|
+
return "没有本地令牌(运行 braid mcp login " + name + ")"
|
|
726
|
+
tokens = stored.tokens
|
|
727
|
+
if tokens.expires_at is None:
|
|
728
|
+
return "已授权(服务端未给过期时间)"
|
|
729
|
+
if tokens.is_expired(skew_seconds=0):
|
|
730
|
+
refresh = (
|
|
731
|
+
"有 refresh_token,下次连接会尝试刷新" if tokens.refresh_token else "无 refresh_token"
|
|
732
|
+
)
|
|
733
|
+
return f"已过期({refresh})"
|
|
734
|
+
expires = datetime.fromtimestamp(tokens.expires_at).strftime("%Y-%m-%d %H:%M")
|
|
735
|
+
return f"已授权({expires} 过期)"
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
async def _login(
|
|
739
|
+
server: McpServerConfig,
|
|
740
|
+
*,
|
|
741
|
+
agent_dir: Path,
|
|
742
|
+
open_browser: bool,
|
|
743
|
+
timeout: float,
|
|
744
|
+
out: TextIO,
|
|
745
|
+
) -> None:
|
|
746
|
+
"""走完发现 → 注册 → 授权码 + PKCE → 存令牌。"""
|
|
747
|
+
oauth = server.oauth
|
|
748
|
+
if server.transport == "ws":
|
|
749
|
+
raise CommandError("WebSocket 传输的 OAuth 尚未接线;请改用 http 或 sse")
|
|
750
|
+
if server.transport not in ("http", "sse") or server.url is None:
|
|
751
|
+
raise CommandError(f"{server.name} 是本地 stdio 服务器,不需要 OAuth 授权")
|
|
752
|
+
if oauth is None:
|
|
753
|
+
raise CommandError(
|
|
754
|
+
f'{server.name} 没有配置 OAuth。在 mcp.json 的该条目里加 "oauth": true 后重试'
|
|
755
|
+
)
|
|
756
|
+
store = token_store(agent_dir)
|
|
757
|
+
existing = store.load(server.name)
|
|
758
|
+
async with httpx.AsyncClient(timeout=OAUTH_HTTP_TIMEOUT_S) as client:
|
|
759
|
+
try:
|
|
760
|
+
discovery = await discover(
|
|
761
|
+
client,
|
|
762
|
+
resource_url=server.url,
|
|
763
|
+
authorization_server=oauth.authorization_server,
|
|
764
|
+
)
|
|
765
|
+
except OAuthError as error:
|
|
766
|
+
raise CommandError(f"读取授权服务器元数据失败:{error}") from error
|
|
767
|
+
metadata = discovery.metadata
|
|
768
|
+
with _CallbackServer() as callback:
|
|
769
|
+
registration = await _resolve_registration(
|
|
770
|
+
client,
|
|
771
|
+
metadata,
|
|
772
|
+
existing=existing,
|
|
773
|
+
oauth_client_id=oauth.client_id,
|
|
774
|
+
oauth_client_secret=oauth.client_secret,
|
|
775
|
+
scopes=oauth.scopes,
|
|
776
|
+
redirect_uri=callback.redirect_uri,
|
|
777
|
+
)
|
|
778
|
+
verifier, challenge = create_pkce_pair()
|
|
779
|
+
state = secrets.token_urlsafe(16)
|
|
780
|
+
url = build_authorization_url(
|
|
781
|
+
metadata,
|
|
782
|
+
client_id=registration.client_id,
|
|
783
|
+
redirect_uri=callback.redirect_uri,
|
|
784
|
+
code_challenge=challenge,
|
|
785
|
+
state=state,
|
|
786
|
+
scopes=oauth.scopes or metadata.scopes_supported,
|
|
787
|
+
resource=server.url,
|
|
788
|
+
)
|
|
789
|
+
print(f"在浏览器里完成 {server.name} 的授权:\n{url}", file=out)
|
|
790
|
+
if open_browser:
|
|
791
|
+
webbrowser.open(url)
|
|
792
|
+
params = await callback.wait(timeout)
|
|
793
|
+
if params is None:
|
|
794
|
+
raise CommandError(
|
|
795
|
+
f"等待授权回调超时({timeout:.0f} 秒)。重新运行 braid mcp login {server.name}"
|
|
796
|
+
)
|
|
797
|
+
if "error" in params:
|
|
798
|
+
raise CommandError(f"授权被拒绝:{params['error'][0]}")
|
|
799
|
+
if params.get("state", [""])[0] != state:
|
|
800
|
+
raise CommandError("回调里的 state 不匹配,已放弃这次授权")
|
|
801
|
+
code = params.get("code", [""])[0]
|
|
802
|
+
if not code:
|
|
803
|
+
raise CommandError("回调里没有授权码")
|
|
804
|
+
try:
|
|
805
|
+
tokens = await exchange_authorization_code(
|
|
806
|
+
client,
|
|
807
|
+
metadata,
|
|
808
|
+
code=code,
|
|
809
|
+
code_verifier=verifier,
|
|
810
|
+
client_id=registration.client_id,
|
|
811
|
+
client_secret=registration.client_secret,
|
|
812
|
+
redirect_uri=callback.redirect_uri,
|
|
813
|
+
resource=server.url,
|
|
814
|
+
)
|
|
815
|
+
except OAuthError as error:
|
|
816
|
+
raise CommandError(f"换取令牌失败:{error}") from error
|
|
817
|
+
store.save(
|
|
818
|
+
server.name,
|
|
819
|
+
StoredAuthorization(
|
|
820
|
+
metadata=metadata,
|
|
821
|
+
client=registration,
|
|
822
|
+
tokens=tokens,
|
|
823
|
+
resource=server.url,
|
|
824
|
+
),
|
|
825
|
+
)
|
|
826
|
+
print(f"已保存 {server.name} 的令牌({token_store(agent_dir).path})", file=out)
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
async def _resolve_registration(
|
|
830
|
+
client: httpx.AsyncClient,
|
|
831
|
+
metadata: AuthorizationServerMetadata,
|
|
832
|
+
*,
|
|
833
|
+
existing: StoredAuthorization | None,
|
|
834
|
+
oauth_client_id: str | None,
|
|
835
|
+
oauth_client_secret: str | None,
|
|
836
|
+
scopes: tuple[str, ...],
|
|
837
|
+
redirect_uri: str,
|
|
838
|
+
) -> ClientRegistration:
|
|
839
|
+
"""已有客户端就复用,配置里写了就用配置,否则动态注册。
|
|
840
|
+
|
|
841
|
+
复用有条件:令牌文件里的注册信息必须属于同一台授权服务器。换了
|
|
842
|
+
``authorization_server`` 之后沿用旧 ``client_id`` 会被对端拒绝,错误还会发生在
|
|
843
|
+
换票那一步,很难看出原因。
|
|
844
|
+
"""
|
|
845
|
+
if oauth_client_id is not None:
|
|
846
|
+
return ClientRegistration(client_id=oauth_client_id, client_secret=oauth_client_secret)
|
|
847
|
+
if existing is not None and existing.metadata.issuer == metadata.issuer:
|
|
848
|
+
return existing.client
|
|
849
|
+
try:
|
|
850
|
+
return await register_client(
|
|
851
|
+
client,
|
|
852
|
+
metadata,
|
|
853
|
+
redirect_uris=(redirect_uri,),
|
|
854
|
+
client_name="braid",
|
|
855
|
+
scopes=scopes,
|
|
856
|
+
)
|
|
857
|
+
except OAuthError as error:
|
|
858
|
+
raise CommandError(f"动态注册失败:{error}") from error
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
class _CallbackServer:
|
|
862
|
+
"""回环地址上的单次回调接收器。"""
|
|
863
|
+
|
|
864
|
+
def __init__(self) -> None:
|
|
865
|
+
self._params: dict[str, list[str]] | None = None
|
|
866
|
+
self._ready = threading.Event()
|
|
867
|
+
self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), _callback_handler(self))
|
|
868
|
+
self._httpd.daemon_threads = True
|
|
869
|
+
self._thread = threading.Thread(
|
|
870
|
+
target=self._httpd.serve_forever, name="braid-mcp-oauth", daemon=True
|
|
871
|
+
)
|
|
872
|
+
|
|
873
|
+
@property
|
|
874
|
+
def redirect_uri(self) -> str:
|
|
875
|
+
port = int(self._httpd.server_address[1])
|
|
876
|
+
return f"http://127.0.0.1:{port}/callback"
|
|
877
|
+
|
|
878
|
+
def __enter__(self) -> _CallbackServer:
|
|
879
|
+
self._thread.start()
|
|
880
|
+
return self
|
|
881
|
+
|
|
882
|
+
def __exit__(
|
|
883
|
+
self,
|
|
884
|
+
exc_type: type[BaseException] | None,
|
|
885
|
+
exc: BaseException | None,
|
|
886
|
+
traceback: TracebackType | None,
|
|
887
|
+
) -> None:
|
|
888
|
+
self._httpd.shutdown()
|
|
889
|
+
self._httpd.server_close()
|
|
890
|
+
|
|
891
|
+
def complete(self, params: dict[str, list[str]]) -> None:
|
|
892
|
+
if self._params is None:
|
|
893
|
+
self._params = params
|
|
894
|
+
self._ready.set()
|
|
895
|
+
|
|
896
|
+
async def wait(self, timeout: float) -> dict[str, list[str]] | None:
|
|
897
|
+
await asyncio.to_thread(self._ready.wait, timeout)
|
|
898
|
+
return self._params
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def _callback_handler(owner: _CallbackServer) -> type[BaseHTTPRequestHandler]:
|
|
902
|
+
class Handler(BaseHTTPRequestHandler):
|
|
903
|
+
protocol_version = "HTTP/1.0"
|
|
904
|
+
|
|
905
|
+
def log_message(self, format: str, *args: object) -> None:
|
|
906
|
+
return
|
|
907
|
+
|
|
908
|
+
def do_GET(self) -> None:
|
|
909
|
+
parsed = urlparse(self.path)
|
|
910
|
+
if parsed.path != "/callback":
|
|
911
|
+
self.send_error(404, "not found")
|
|
912
|
+
return
|
|
913
|
+
owner.complete(parse_qs(parsed.query))
|
|
914
|
+
body = (
|
|
915
|
+
"<html><meta charset='utf-8'><body>"
|
|
916
|
+
"<h3>授权完成</h3><p>可以关闭这个页面,回到终端继续。</p>"
|
|
917
|
+
"</body></html>"
|
|
918
|
+
).encode()
|
|
919
|
+
self.send_response(200)
|
|
920
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
921
|
+
self.send_header("Content-Length", str(len(body)))
|
|
922
|
+
self.end_headers()
|
|
923
|
+
self.wfile.write(body)
|
|
924
|
+
|
|
925
|
+
return Handler
|
|
926
|
+
|
|
927
|
+
|
|
928
|
+
__all__ = ["LOGIN_TIMEOUT_S", "USAGE", "run"]
|