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.
Files changed (192) hide show
  1. braid_coding_agent/__init__.py +13 -0
  2. braid_coding_agent/assembly.py +460 -0
  3. braid_coding_agent/cancellation.py +25 -0
  4. braid_coding_agent/checkpoint/__init__.py +106 -0
  5. braid_coding_agent/checkpoint/git.py +305 -0
  6. braid_coding_agent/checkpoint/settings.py +26 -0
  7. braid_coding_agent/checkpoint/store.py +1261 -0
  8. braid_coding_agent/checkpoint/workspace.py +220 -0
  9. braid_coding_agent/cli.py +2168 -0
  10. braid_coding_agent/commands/__init__.py +50 -0
  11. braid_coding_agent/commands/auth.py +161 -0
  12. braid_coding_agent/commands/config.py +180 -0
  13. braid_coding_agent/commands/doctor.py +511 -0
  14. braid_coding_agent/commands/mcp.py +928 -0
  15. braid_coding_agent/commands/models.py +95 -0
  16. braid_coding_agent/commands/setup.py +89 -0
  17. braid_coding_agent/commands/uninstall.py +277 -0
  18. braid_coding_agent/commands/upgrade.py +381 -0
  19. braid_coding_agent/compaction/__init__.py +174 -0
  20. braid_coding_agent/compaction/prepare.py +430 -0
  21. braid_coding_agent/compaction/summarize.py +542 -0
  22. braid_coding_agent/compaction/tokens.py +204 -0
  23. braid_coding_agent/compaction/tool_results.py +196 -0
  24. braid_coding_agent/compaction/utils.py +181 -0
  25. braid_coding_agent/config.py +2776 -0
  26. braid_coding_agent/config_files.py +191 -0
  27. braid_coding_agent/credentials.py +252 -0
  28. braid_coding_agent/discovery.py +415 -0
  29. braid_coding_agent/extensions/__init__.py +77 -0
  30. braid_coding_agent/extensions/api.py +480 -0
  31. braid_coding_agent/extensions/runner.py +553 -0
  32. braid_coding_agent/formatting/__init__.py +62 -0
  33. braid_coding_agent/formatting/settings.py +87 -0
  34. braid_coding_agent/formatting/tool.py +179 -0
  35. braid_coding_agent/lsp/__init__.py +105 -0
  36. braid_coding_agent/lsp/client.py +546 -0
  37. braid_coding_agent/lsp/manager.py +187 -0
  38. braid_coding_agent/lsp/model.py +316 -0
  39. braid_coding_agent/lsp/protocol.py +105 -0
  40. braid_coding_agent/lsp/settings.py +120 -0
  41. braid_coding_agent/lsp/tool.py +429 -0
  42. braid_coding_agent/mcp/__init__.py +101 -0
  43. braid_coding_agent/mcp/cache.py +230 -0
  44. braid_coding_agent/mcp/catalog.py +108 -0
  45. braid_coding_agent/mcp/config.py +664 -0
  46. braid_coding_agent/mcp/config_store.py +142 -0
  47. braid_coding_agent/mcp/inspector.py +85 -0
  48. braid_coding_agent/mcp/panel.py +254 -0
  49. braid_coding_agent/mcp/runtime.py +1060 -0
  50. braid_coding_agent/mcp/tools.py +579 -0
  51. braid_coding_agent/mcp/trust.py +150 -0
  52. braid_coding_agent/mcp/tui_panel.py +444 -0
  53. braid_coding_agent/messages.py +152 -0
  54. braid_coding_agent/models_view.py +105 -0
  55. braid_coding_agent/modes/__init__.py +64 -0
  56. braid_coding_agent/modes/json_mode.py +480 -0
  57. braid_coding_agent/modes/lifecycle.py +217 -0
  58. braid_coding_agent/modes/print_mode.py +257 -0
  59. braid_coding_agent/modes/repl.py +2687 -0
  60. braid_coding_agent/modes/repl_commands.py +263 -0
  61. braid_coding_agent/modes/rpc.py +953 -0
  62. braid_coding_agent/modes/skill_commands.py +88 -0
  63. braid_coding_agent/modes/tui.py +2226 -0
  64. braid_coding_agent/modes/tui_control.py +90 -0
  65. braid_coding_agent/modes/tui_model.py +1043 -0
  66. braid_coding_agent/modes/tui_render.py +327 -0
  67. braid_coding_agent/modes/tui_rich.py +751 -0
  68. braid_coding_agent/modes/tui_style.py +42 -0
  69. braid_coding_agent/modes/wire.py +81 -0
  70. braid_coding_agent/netsafe.py +82 -0
  71. braid_coding_agent/network/__init__.py +20 -0
  72. braid_coding_agent/network/cache.py +77 -0
  73. braid_coding_agent/network/fetch.py +311 -0
  74. braid_coding_agent/network/html_text.py +160 -0
  75. braid_coding_agent/network/search.py +347 -0
  76. braid_coding_agent/network/settings.py +103 -0
  77. braid_coding_agent/network/urls.py +89 -0
  78. braid_coding_agent/observability/__init__.py +101 -0
  79. braid_coding_agent/observability/audit.py +124 -0
  80. braid_coding_agent/observability/collector.py +314 -0
  81. braid_coding_agent/observability/exporter.py +74 -0
  82. braid_coding_agent/observability/logging_setup.py +149 -0
  83. braid_coding_agent/observability/redaction.py +96 -0
  84. braid_coding_agent/observability/settings.py +29 -0
  85. braid_coding_agent/observability/spans.py +239 -0
  86. braid_coding_agent/permissions/__init__.py +185 -0
  87. braid_coding_agent/permissions/command.py +586 -0
  88. braid_coding_agent/permissions/engine.py +522 -0
  89. braid_coding_agent/permissions/evaluate.py +309 -0
  90. braid_coding_agent/permissions/matching.py +233 -0
  91. braid_coding_agent/permissions/model.py +278 -0
  92. braid_coding_agent/permissions/policy.py +99 -0
  93. braid_coding_agent/permissions/readonly.py +236 -0
  94. braid_coding_agent/permissions/store.py +379 -0
  95. braid_coding_agent/project_init.py +313 -0
  96. braid_coding_agent/prompt/__init__.py +98 -0
  97. braid_coding_agent/prompt/context_files.py +253 -0
  98. braid_coding_agent/prompt/project_context.py +172 -0
  99. braid_coding_agent/prompt/system_prompt.py +378 -0
  100. braid_coding_agent/questions.py +71 -0
  101. braid_coding_agent/render/__init__.py +56 -0
  102. braid_coding_agent/render/batch.py +66 -0
  103. braid_coding_agent/render/history.py +143 -0
  104. braid_coding_agent/render/stream.py +823 -0
  105. braid_coding_agent/render/theme.py +243 -0
  106. braid_coding_agent/sandbox/__init__.py +89 -0
  107. braid_coding_agent/sandbox/backend.py +184 -0
  108. braid_coding_agent/sandbox/bubblewrap.py +96 -0
  109. braid_coding_agent/sandbox/operations.py +301 -0
  110. braid_coding_agent/sandbox/policy.py +221 -0
  111. braid_coding_agent/sandbox/proxy.py +320 -0
  112. braid_coding_agent/sandbox/seatbelt.py +222 -0
  113. braid_coding_agent/sdk/__init__.py +31 -0
  114. braid_coding_agent/sdk/async_client.py +366 -0
  115. braid_coding_agent/sdk/client.py +386 -0
  116. braid_coding_agent/sdk/errors.py +52 -0
  117. braid_coding_agent/sdk/events.py +162 -0
  118. braid_coding_agent/sdk/types.py +63 -0
  119. braid_coding_agent/sdk/wire.py +59 -0
  120. braid_coding_agent/server/__init__.py +54 -0
  121. braid_coding_agent/server/errors.py +52 -0
  122. braid_coding_agent/server/http_server.py +419 -0
  123. braid_coding_agent/server/hub.py +530 -0
  124. braid_coding_agent/server/openapi.py +157 -0
  125. braid_coding_agent/server/registry.py +354 -0
  126. braid_coding_agent/server/router.py +275 -0
  127. braid_coding_agent/server/run.py +148 -0
  128. braid_coding_agent/server/schema.py +194 -0
  129. braid_coding_agent/server/service.py +975 -0
  130. braid_coding_agent/session/__init__.py +293 -0
  131. braid_coding_agent/session/agent_session.py +2706 -0
  132. braid_coding_agent/session/context_breakdown.py +302 -0
  133. braid_coding_agent/session/discovery.py +212 -0
  134. braid_coding_agent/session/entries.py +809 -0
  135. braid_coding_agent/session/evidence.py +295 -0
  136. braid_coding_agent/session/lock.py +176 -0
  137. braid_coding_agent/session/manager.py +1185 -0
  138. braid_coding_agent/session/plan.py +243 -0
  139. braid_coding_agent/session/plan_mode.py +423 -0
  140. braid_coding_agent/session/projection.py +262 -0
  141. braid_coding_agent/session/rewind.py +257 -0
  142. braid_coding_agent/session/status.py +240 -0
  143. braid_coding_agent/settings.py +94 -0
  144. braid_coding_agent/skills/__init__.py +70 -0
  145. braid_coding_agent/skills/loader.py +681 -0
  146. braid_coding_agent/startup/__init__.py +76 -0
  147. braid_coding_agent/startup/cache.py +72 -0
  148. braid_coding_agent/startup/diagnostics.py +37 -0
  149. braid_coding_agent/startup/monitor.py +245 -0
  150. braid_coding_agent/startup/phases.py +79 -0
  151. braid_coding_agent/startup/project.py +165 -0
  152. braid_coding_agent/startup/report.py +560 -0
  153. braid_coding_agent/startup/scheduler.py +347 -0
  154. braid_coding_agent/statusline.py +163 -0
  155. braid_coding_agent/subagents/__init__.py +22 -0
  156. braid_coding_agent/subagents/contract.py +75 -0
  157. braid_coding_agent/subagents/definitions.py +583 -0
  158. braid_coding_agent/subagents/registry.py +277 -0
  159. braid_coding_agent/subagents/runtime.py +610 -0
  160. braid_coding_agent/subagents/settings.py +156 -0
  161. braid_coding_agent/subagents/worktree.py +63 -0
  162. braid_coding_agent/tools/__init__.py +327 -0
  163. braid_coding_agent/tools/args.py +87 -0
  164. braid_coding_agent/tools/bash.py +359 -0
  165. braid_coding_agent/tools/edit.py +298 -0
  166. braid_coding_agent/tools/edit_diff.py +344 -0
  167. braid_coding_agent/tools/find.py +158 -0
  168. braid_coding_agent/tools/grep.py +305 -0
  169. braid_coding_agent/tools/ignore.py +198 -0
  170. braid_coding_agent/tools/ls.py +127 -0
  171. braid_coding_agent/tools/mutation_queue.py +90 -0
  172. braid_coding_agent/tools/operations.py +274 -0
  173. braid_coding_agent/tools/output_accumulator.py +282 -0
  174. braid_coding_agent/tools/output_store.py +244 -0
  175. braid_coding_agent/tools/path_utils.py +91 -0
  176. braid_coding_agent/tools/plan.py +141 -0
  177. braid_coding_agent/tools/prompt_notes.py +52 -0
  178. braid_coding_agent/tools/question.py +180 -0
  179. braid_coding_agent/tools/read.py +223 -0
  180. braid_coding_agent/tools/submit_plan.py +102 -0
  181. braid_coding_agent/tools/truncate.py +423 -0
  182. braid_coding_agent/tools/write.py +100 -0
  183. braid_coding_agent/untrusted.py +50 -0
  184. braid_coding_agent/verify/__init__.py +78 -0
  185. braid_coding_agent/verify/runner.py +260 -0
  186. braid_coding_agent/verify/settings.py +64 -0
  187. braid_coding_agent/verify/tool.py +143 -0
  188. braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
  189. braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
  190. braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
  191. braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
  192. braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,579 @@
1
+ """MCP 工具适配:原生工具、搜索与加载工具、资源与提示词工具。
2
+
3
+ 这里只回答"一个 MCP 能力长成什么形状的 :class:`~braid_agent.tools.AgentTool`"。
4
+ 连接状态、工具目录与注册策略属于 :mod:`.runtime`;把两者放在同一个文件里,
5
+ 读代码的人要在"协议结果如何映射"与"这次该注册哪些工具"之间来回跳。
6
+
7
+ ## 结果不可信
8
+
9
+ MCP 服务端是外部代码,它返回的正文用 ``<untrusted-content>`` 包起来。标注不改变
10
+ 内容,只标明来源。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import binascii
17
+ import json
18
+ import time
19
+ from collections.abc import Sequence
20
+ from typing import TYPE_CHECKING
21
+
22
+ from braid_agent.tools import AgentTool, AgentToolResult
23
+ from braid_ai.cancel import CancelToken
24
+ from braid_ai.types import ImageContent, JsonValue, TextContent
25
+ from braid_coding_agent.mcp.inspector import CallInspector
26
+ from braid_coding_agent.tools.output_store import ToolOutputStore
27
+ from braid_coding_agent.tools.truncate import (
28
+ DEFAULT_MAX_BYTES,
29
+ DEFAULT_MAX_LINES,
30
+ format_size,
31
+ truncate_middle,
32
+ )
33
+ from braid_coding_agent.untrusted import wrap_untrusted
34
+ from braid_mcp import (
35
+ AudioBlock,
36
+ BlobResourceContents,
37
+ CallToolResult,
38
+ EmbeddedResourceBlock,
39
+ GetPromptResult,
40
+ McpTool,
41
+ ReadResourceResult,
42
+ TextResourceContents,
43
+ block_to_llm_content,
44
+ to_llm_content,
45
+ )
46
+
47
+ if TYPE_CHECKING:
48
+ from braid_coding_agent.mcp.catalog import ToolEntry
49
+ from braid_coding_agent.mcp.runtime import McpRuntime, McpServerConnection
50
+
51
+ #: 工具描述的长度上限。外部服务器可以用一段十万字的描述占满上下文。
52
+ MAX_TOOL_DESCRIPTION_CHARS = 2_048
53
+ #: 延迟加载机制暴露给模型的固定工具。
54
+ HELPER_TOOL_NAMES: tuple[str, ...] = (
55
+ "mcp_search_tools",
56
+ "mcp_load_tool",
57
+ "mcp_list_resources",
58
+ "mcp_read_resource",
59
+ "mcp_list_prompts",
60
+ "mcp_get_prompt",
61
+ )
62
+
63
+
64
+ def build_agent_tool(
65
+ connection: McpServerConnection,
66
+ tool: McpTool,
67
+ name: str,
68
+ store: ToolOutputStore,
69
+ inspector: CallInspector,
70
+ ) -> AgentTool:
71
+ """一个 MCP 工具 → 一个可执行工具。"""
72
+
73
+ async def execute(
74
+ tool_call_id: str,
75
+ args: dict[str, JsonValue],
76
+ signal: CancelToken | None,
77
+ on_update: object,
78
+ ) -> AgentToolResult:
79
+ del tool_call_id, on_update
80
+ started = time.perf_counter()
81
+ try:
82
+ result = await connection.call_tool(tool.name, dict(args), signal)
83
+ except Exception as exc:
84
+ inspector.record(
85
+ server=connection.name,
86
+ tool=tool.name,
87
+ arguments=dict(args),
88
+ result=str(exc),
89
+ duration_ms=(time.perf_counter() - started) * 1000,
90
+ is_error=True,
91
+ )
92
+ raise
93
+ content: list[TextContent | ImageContent] = result_content(
94
+ connection, tool.name, result, store
95
+ )
96
+ if result.is_error and not content:
97
+ content = [TextContent(text=f"MCP 工具 {connection.name}/{tool.name} 返回了错误")]
98
+ inspector.record(
99
+ server=connection.name,
100
+ tool=tool.name,
101
+ arguments=dict(args),
102
+ result=content_summary(content),
103
+ duration_ms=(time.perf_counter() - started) * 1000,
104
+ is_error=result.is_error,
105
+ )
106
+ return AgentToolResult(
107
+ content=content,
108
+ details={"server": connection.name, "tool": tool.name},
109
+ structured_content=result.structured_content,
110
+ is_error=result.is_error,
111
+ )
112
+
113
+ return AgentTool(
114
+ name=name,
115
+ label=f"{connection.name}/{tool.name}",
116
+ description=tool_description(connection.name, tool),
117
+ parameters=tool_parameters(tool.input_schema),
118
+ execute=execute,
119
+ default_timeout_s=connection.call_timeout_s,
120
+ max_timeout_s=connection.call_timeout_s,
121
+ )
122
+
123
+
124
+ def helper_tools(runtime: McpRuntime) -> list[AgentTool]:
125
+ """搜索、加载与资源/提示词读取工具。"""
126
+ return [
127
+ _search_tool(runtime),
128
+ _load_tool(runtime),
129
+ _list_resources_tool(runtime),
130
+ _read_resource_tool(runtime),
131
+ _list_prompts_tool(runtime),
132
+ _get_prompt_tool(runtime),
133
+ ]
134
+
135
+
136
+ def _search_tool(runtime: McpRuntime) -> AgentTool:
137
+ async def execute(
138
+ tool_call_id: str,
139
+ args: dict[str, JsonValue],
140
+ signal: CancelToken | None,
141
+ on_update: object,
142
+ ) -> AgentToolResult:
143
+ del tool_call_id, signal, on_update
144
+ query = str(args.get("query") or "")
145
+ server = args.get("server")
146
+ raw_limit = args.get("limit")
147
+ limit = int(raw_limit) if isinstance(raw_limit, int) and raw_limit > 0 else 10
148
+ entries = runtime.catalog.search(
149
+ query, server=str(server) if isinstance(server, str) else None, limit=limit
150
+ )
151
+ if not entries:
152
+ return AgentToolResult(content=[TextContent(text="没有匹配的 MCP 工具")])
153
+ lines = [
154
+ _describe_entry(entry, loaded=entry.provider_name in runtime.loaded_tools)
155
+ for entry in entries
156
+ ]
157
+ return AgentToolResult(content=[TextContent(text="\n".join(lines))])
158
+
159
+ return AgentTool(
160
+ name="mcp_search_tools",
161
+ label="搜索 MCP 工具",
162
+ description="按关键词搜索已连接 MCP 服务器的工具,返回工具名与一句话描述。",
163
+ parameters={
164
+ "type": "object",
165
+ "properties": {
166
+ "query": {"type": "string", "description": "关键词;空字符串列出前若干项"},
167
+ "server": {"type": "string", "description": "只搜索这个服务器"},
168
+ "limit": {"type": "integer", "description": "最多返回多少项,默认 10"},
169
+ },
170
+ },
171
+ execute=execute,
172
+ )
173
+
174
+
175
+ def _describe_entry(entry: ToolEntry, *, loaded: bool) -> str:
176
+ description = first_line(entry.tool.description) or "无描述"
177
+ state = "已加载" if loaded else entry.loading
178
+ return f"{entry.provider_name} [{state}] {entry.server}/{entry.tool.name}:{description}"
179
+
180
+
181
+ def _load_tool(runtime: McpRuntime) -> AgentTool:
182
+ async def execute(
183
+ tool_call_id: str,
184
+ args: dict[str, JsonValue],
185
+ signal: CancelToken | None,
186
+ on_update: object,
187
+ ) -> AgentToolResult:
188
+ del tool_call_id, signal, on_update
189
+ name = args.get("name")
190
+ if not isinstance(name, str):
191
+ return AgentToolResult(
192
+ content=[TextContent(text="mcp_load_tool 需要 name 参数")], is_error=True
193
+ )
194
+ try:
195
+ entry = runtime.load_tool(name)
196
+ except KeyError as exc:
197
+ return AgentToolResult(content=[TextContent(text=str(exc))], is_error=True)
198
+ payload = {
199
+ "name": entry.provider_name,
200
+ "server": entry.server,
201
+ "tool": entry.tool.name,
202
+ "description": entry.tool.description,
203
+ "inputSchema": entry.tool.input_schema,
204
+ "note": "工具已注册,下一回合可直接调用。",
205
+ }
206
+ return AgentToolResult(
207
+ content=[TextContent(text=json.dumps(payload, ensure_ascii=False, indent=2))],
208
+ details={"server": entry.server, "tool": entry.tool.name},
209
+ )
210
+
211
+ return AgentTool(
212
+ name="mcp_load_tool",
213
+ label="加载 MCP 工具",
214
+ description="载入一个延迟加载工具的完整描述与参数 Schema,并注册为可调用工具。",
215
+ parameters={
216
+ "type": "object",
217
+ "properties": {
218
+ "name": {"type": "string", "description": "mcp_search_tools 返回的工具名"}
219
+ },
220
+ "required": ["name"],
221
+ },
222
+ execute=execute,
223
+ )
224
+
225
+
226
+ def _list_resources_tool(runtime: McpRuntime) -> AgentTool:
227
+ async def execute(
228
+ tool_call_id: str,
229
+ args: dict[str, JsonValue],
230
+ signal: CancelToken | None,
231
+ on_update: object,
232
+ ) -> AgentToolResult:
233
+ del tool_call_id, signal, on_update
234
+ server = args.get("server")
235
+ wanted = str(server) if isinstance(server, str) else None
236
+ lines: list[str] = []
237
+ for connection in runtime.connections:
238
+ if wanted is not None and connection.name != wanted:
239
+ continue
240
+ for resource in connection.resources:
241
+ description = f":{resource.description}" if resource.description else ""
242
+ mime = f" ({resource.mime_type})" if resource.mime_type else ""
243
+ lines.append(f"{connection.name} {resource.uri}{mime} {resource.name}{description}")
244
+ for template in connection.resource_templates:
245
+ lines.append(f"{connection.name} {template.uri_template} [模板] {template.name}")
246
+ body = "\n".join(lines) if lines else "没有可列出的 MCP 资源"
247
+ return AgentToolResult(content=[TextContent(text=body)])
248
+
249
+ return AgentTool(
250
+ name="mcp_list_resources",
251
+ label="列出 MCP 资源",
252
+ description="列出 MCP 服务器公开的资源与资源模板。",
253
+ parameters={
254
+ "type": "object",
255
+ "properties": {"server": {"type": "string", "description": "只看这个服务器"}},
256
+ },
257
+ execute=execute,
258
+ )
259
+
260
+
261
+ def _read_resource_tool(runtime: McpRuntime) -> AgentTool:
262
+ async def execute(
263
+ tool_call_id: str,
264
+ args: dict[str, JsonValue],
265
+ signal: CancelToken | None,
266
+ on_update: object,
267
+ ) -> AgentToolResult:
268
+ del tool_call_id, on_update
269
+ server = args.get("server")
270
+ uri = args.get("uri")
271
+ if not isinstance(server, str) or not isinstance(uri, str):
272
+ return AgentToolResult(
273
+ content=[TextContent(text="mcp_read_resource 需要 server 与 uri 参数")],
274
+ is_error=True,
275
+ )
276
+ try:
277
+ connection = runtime.connection(server)
278
+ result = await connection.read_resource(uri, signal)
279
+ except KeyError as exc:
280
+ return AgentToolResult(content=[TextContent(text=str(exc))], is_error=True)
281
+ return AgentToolResult(
282
+ content=resource_content(connection, uri, result, runtime.output_store),
283
+ details={"server": server, "uri": uri},
284
+ )
285
+
286
+ return AgentTool(
287
+ name="mcp_read_resource",
288
+ label="读取 MCP 资源",
289
+ description="读取一个 MCP 资源;文本返回正文,二进制写入文件并返回路径。",
290
+ parameters={
291
+ "type": "object",
292
+ "properties": {
293
+ "server": {"type": "string", "description": "服务器名"},
294
+ "uri": {"type": "string", "description": "mcp_list_resources 返回的 URI"},
295
+ },
296
+ "required": ["server", "uri"],
297
+ },
298
+ execute=execute,
299
+ )
300
+
301
+
302
+ def _list_prompts_tool(runtime: McpRuntime) -> AgentTool:
303
+ async def execute(
304
+ tool_call_id: str,
305
+ args: dict[str, JsonValue],
306
+ signal: CancelToken | None,
307
+ on_update: object,
308
+ ) -> AgentToolResult:
309
+ del tool_call_id, signal, on_update
310
+ server = args.get("server")
311
+ wanted = str(server) if isinstance(server, str) else None
312
+ lines: list[str] = []
313
+ for connection in runtime.connections:
314
+ if wanted is not None and connection.name != wanted:
315
+ continue
316
+ for prompt in connection.prompts:
317
+ arguments = ", ".join(
318
+ f"{argument.name}{'*' if argument.required else ''}"
319
+ for argument in prompt.arguments
320
+ )
321
+ suffix = f"(参数: {arguments})" if arguments else ""
322
+ description = f":{prompt.description}" if prompt.description else ""
323
+ lines.append(f"{connection.name} {prompt.name}{suffix}{description}")
324
+ body = "\n".join(lines) if lines else "没有可列出的 MCP 提示词"
325
+ return AgentToolResult(content=[TextContent(text=body)])
326
+
327
+ return AgentTool(
328
+ name="mcp_list_prompts",
329
+ label="列出 MCP 提示词",
330
+ description="列出 MCP 服务器公开的提示词模板与参数。",
331
+ parameters={
332
+ "type": "object",
333
+ "properties": {"server": {"type": "string", "description": "只看这个服务器"}},
334
+ },
335
+ execute=execute,
336
+ )
337
+
338
+
339
+ def _get_prompt_tool(runtime: McpRuntime) -> AgentTool:
340
+ async def execute(
341
+ tool_call_id: str,
342
+ args: dict[str, JsonValue],
343
+ signal: CancelToken | None,
344
+ on_update: object,
345
+ ) -> AgentToolResult:
346
+ del tool_call_id, on_update
347
+ server = args.get("server")
348
+ name = args.get("name")
349
+ raw_arguments = args.get("arguments")
350
+ if not isinstance(server, str) or not isinstance(name, str):
351
+ return AgentToolResult(
352
+ content=[TextContent(text="mcp_get_prompt 需要 server 与 name 参数")],
353
+ is_error=True,
354
+ )
355
+ if raw_arguments is not None and not isinstance(raw_arguments, dict):
356
+ return AgentToolResult(
357
+ content=[TextContent(text="arguments 必须是对象")], is_error=True
358
+ )
359
+ try:
360
+ connection = runtime.connection(server)
361
+ result = await connection.get_prompt(name, raw_arguments, signal)
362
+ except KeyError as exc:
363
+ return AgentToolResult(content=[TextContent(text=str(exc))], is_error=True)
364
+ return AgentToolResult(
365
+ content=prompt_content(connection, name, result, runtime.output_store),
366
+ details={"server": server, "prompt": name},
367
+ )
368
+
369
+ return AgentTool(
370
+ name="mcp_get_prompt",
371
+ label="读取 MCP 提示词",
372
+ description="取出一条 MCP 提示词模板的完整消息,按角色拼成文本。",
373
+ parameters={
374
+ "type": "object",
375
+ "properties": {
376
+ "server": {"type": "string", "description": "服务器名"},
377
+ "name": {"type": "string", "description": "mcp_list_prompts 返回的提示词名"},
378
+ "arguments": {"type": "object", "description": "提示词参数"},
379
+ },
380
+ "required": ["server", "name"],
381
+ },
382
+ execute=execute,
383
+ )
384
+
385
+
386
+ def result_content(
387
+ connection: McpServerConnection,
388
+ tool_name: str,
389
+ result: CallToolResult,
390
+ store: ToolOutputStore,
391
+ ) -> list[TextContent | ImageContent]:
392
+ """一次 ``tools/call`` 的结果 → 模型可见的内容块。"""
393
+ if not result.content:
394
+ converted = to_llm_content(result)
395
+ texts = [block.text for block in converted if isinstance(block, TextContent)]
396
+ images = [block for block in converted if isinstance(block, ImageContent)]
397
+ return assemble(f"mcp:{connection.name}/{tool_name}", texts, images, store)
398
+
399
+ texts: list[str] = []
400
+ images: list[ImageContent] = []
401
+ for block in result.content:
402
+ if isinstance(block, AudioBlock):
403
+ data = decode_blob(block.data, f"音频块({block.mime_type})")
404
+ path = store.write_output(
405
+ data, prefix=f"{connection.name}-{tool_name}-audio", suffix=".bin"
406
+ )
407
+ texts.append(f"[audio {block.mime_type} saved to {path}]")
408
+ continue
409
+ if isinstance(block, EmbeddedResourceBlock) and isinstance(
410
+ block.resource, BlobResourceContents
411
+ ):
412
+ resource = block.resource
413
+ if resource.mime_type is not None and resource.mime_type.startswith("image/"):
414
+ images.append(ImageContent(data=resource.blob, mime_type=resource.mime_type))
415
+ continue
416
+ data = decode_blob(resource.blob, f"MCP 资源 {resource.uri}")
417
+ path = store.write_output(
418
+ data, prefix=f"{connection.name}-{tool_name}-blob", suffix=".bin"
419
+ )
420
+ texts.append(
421
+ f"[binary resource {resource.uri} "
422
+ f"({resource.mime_type or 'unknown type'}) saved to {path}]"
423
+ )
424
+ continue
425
+ converted = block_to_llm_content(block)
426
+ if isinstance(converted, TextContent):
427
+ texts.append(converted.text)
428
+ else:
429
+ images.append(converted)
430
+ return assemble(f"mcp:{connection.name}/{tool_name}", texts, images, store)
431
+
432
+
433
+ def resource_content(
434
+ connection: McpServerConnection,
435
+ uri: str,
436
+ result: ReadResourceResult,
437
+ store: ToolOutputStore,
438
+ ) -> list[TextContent | ImageContent]:
439
+ """``resources/read`` 的结果 → 模型可见内容。"""
440
+ texts: list[str] = []
441
+ images: list[ImageContent] = []
442
+ for item in result.contents:
443
+ if isinstance(item, BlobResourceContents):
444
+ if item.mime_type is not None and item.mime_type.startswith("image/"):
445
+ images.append(ImageContent(data=item.blob, mime_type=item.mime_type))
446
+ continue
447
+ data = decode_blob(item.blob, f"MCP 资源 {item.uri}")
448
+ path = store.write_output(
449
+ data, prefix=f"{connection.name}-{safe_label(uri)}", suffix=".bin"
450
+ )
451
+ texts.append(
452
+ f"[binary resource {item.uri} ({item.mime_type or 'unknown type'}) saved to {path}]"
453
+ )
454
+ continue
455
+ assert isinstance(item, TextResourceContents)
456
+ label = f" ({item.mime_type})" if item.mime_type else ""
457
+ texts.append(f"[{item.uri}{label}]\n{item.text}")
458
+ return assemble(f"mcp:{connection.name}/{uri}", texts, images, store)
459
+
460
+
461
+ def prompt_content(
462
+ connection: McpServerConnection,
463
+ name: str,
464
+ result: GetPromptResult,
465
+ store: ToolOutputStore,
466
+ ) -> list[TextContent | ImageContent]:
467
+ """``prompts/get`` 的消息 → 按角色拼成文本。"""
468
+ texts: list[str] = []
469
+ if result.description:
470
+ texts.append(result.description)
471
+ images: list[ImageContent] = []
472
+ for message in result.messages:
473
+ converted = block_to_llm_content(message.content)
474
+ if isinstance(converted, TextContent):
475
+ texts.append(f"[{message.role}]\n{converted.text}")
476
+ else:
477
+ images.append(converted)
478
+ return assemble(f"mcp:{connection.name}/{name}", texts, images, store)
479
+
480
+
481
+ def assemble(
482
+ label: str,
483
+ texts: list[str],
484
+ images: list[ImageContent],
485
+ store: ToolOutputStore,
486
+ ) -> list[TextContent | ImageContent]:
487
+ """把文本段拼成一段(必要时截断落盘),图片跟在后面。"""
488
+ body = "\n".join(part for part in texts if part)
489
+ if not body:
490
+ return list(images)
491
+ wrapped = wrap_untrusted(label, body)
492
+ return [TextContent(text=bounded_text(label, wrapped, store)), *images]
493
+
494
+
495
+ def bounded_text(label: str, text: str, store: ToolOutputStore) -> str:
496
+ """超过展示上限时保留头尾、写全文,并把路径写进结果。"""
497
+ truncation = truncate_middle(text, max_lines=DEFAULT_MAX_LINES, max_bytes=DEFAULT_MAX_BYTES)
498
+ if not truncation.truncated:
499
+ return text
500
+ path = store.write_output(
501
+ text.encode("utf-8"),
502
+ prefix=safe_label(label),
503
+ suffix=".log",
504
+ )
505
+ if truncation.first_line_exceeds_limit:
506
+ return (
507
+ f"[MCP 结果共 {format_size(truncation.total_bytes)},首行就超过单次展示上限"
508
+ f"({format_size(DEFAULT_MAX_BYTES)}),因此没有内联。全文:{path}]"
509
+ )
510
+ return (
511
+ f"{truncation.content}\n\n"
512
+ f"[MCP 结果已截断:共 {truncation.total_lines} 行 / "
513
+ f"{format_size(truncation.total_bytes)},中间部分省略。全文:{path}]"
514
+ )
515
+
516
+
517
+ def decode_blob(blob: str, label: str) -> bytes:
518
+ """base64 → 字节。解不开时带上来源再报。"""
519
+ try:
520
+ return base64.b64decode(blob, validate=True)
521
+ except binascii.Error as error:
522
+ raise ValueError(f"{label} 的 base64 不合法:{error}") from error
523
+
524
+
525
+ def tool_description(server: str, tool: McpTool) -> str:
526
+ """工具描述:服务端原文,截到上限。"""
527
+ text = (tool.description or "").strip()
528
+ if not text:
529
+ return f"MCP tool {tool.name} from server {server}"
530
+ if len(text) > MAX_TOOL_DESCRIPTION_CHARS:
531
+ return text[:MAX_TOOL_DESCRIPTION_CHARS].rstrip() + "…"
532
+ return text
533
+
534
+
535
+ def tool_parameters(schema: dict[str, JsonValue]) -> dict[str, JsonValue]:
536
+ """把服务端的 ``inputSchema`` 补成对象型 schema。"""
537
+ parameters = dict(schema)
538
+ parameters.setdefault("type", "object")
539
+ parameters.setdefault("properties", {})
540
+ return parameters
541
+
542
+
543
+ def content_summary(content: Sequence[TextContent | ImageContent]) -> str:
544
+ parts: list[str] = []
545
+ for block in content:
546
+ parts.append(block.text if isinstance(block, TextContent) else "[image]")
547
+ return "\n".join(parts)
548
+
549
+
550
+ def first_line(text: str | None) -> str:
551
+ if not text or not text.strip():
552
+ return ""
553
+ return text.strip().splitlines()[0][:160]
554
+
555
+
556
+ def safe_label(value: str) -> str:
557
+ label = "".join(
558
+ character if character.isalnum() or character == "_" else "_" for character in value
559
+ )
560
+ return label.strip("_")[:80] or "mcp"
561
+
562
+
563
+ __all__ = [
564
+ "HELPER_TOOL_NAMES",
565
+ "MAX_TOOL_DESCRIPTION_CHARS",
566
+ "assemble",
567
+ "bounded_text",
568
+ "build_agent_tool",
569
+ "content_summary",
570
+ "decode_blob",
571
+ "first_line",
572
+ "helper_tools",
573
+ "prompt_content",
574
+ "resource_content",
575
+ "result_content",
576
+ "safe_label",
577
+ "tool_description",
578
+ "tool_parameters",
579
+ ]