@yahyahammad/venastine 0.2.0 → 0.3.9

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 (152) hide show
  1. package/.env.example +9 -4
  2. package/CONFIG_ARCHITECTURE.md +2030 -0
  3. package/LICENSE +201 -201
  4. package/NOTICE +1 -1
  5. package/README.md +1034 -895
  6. package/agents/builtin/build.md +73 -0
  7. package/agents/builtin/compactor.md +75 -75
  8. package/agents/builtin/explore.md +77 -77
  9. package/agents/builtin/general.md +80 -0
  10. package/agents/builtin/pipeline-reviewer.md +100 -100
  11. package/agents/builtin/plan.md +106 -88
  12. package/agents/builtin/review.md +74 -74
  13. package/agents/builtin/test.md +65 -0
  14. package/agents/builtin/writer.md +67 -0
  15. package/agents/manager.py +68 -2
  16. package/agents/subagent_tool.py +472 -238
  17. package/agents/tui_commands.py +238 -151
  18. package/bin/venastine.mjs +150 -4
  19. package/bin/venastine.py +71 -0
  20. package/cli_commands.py +838 -0
  21. package/config.py +95 -1198
  22. package/config.yaml +1103 -0
  23. package/config_edit.py +1301 -0
  24. package/config_schema.py +971 -0
  25. package/config_update.py +749 -0
  26. package/core/agent_activity.py +256 -118
  27. package/core/ansi.py +452 -0
  28. package/core/approval.py +137 -115
  29. package/core/call_view.py +364 -0
  30. package/core/cancel.py +121 -0
  31. package/core/chatgpt_auth.py +747 -0
  32. package/core/claims_view.py +107 -0
  33. package/core/client.py +2715 -1559
  34. package/core/commands.py +460 -0
  35. package/core/compaction.py +1735 -971
  36. package/core/config_loader.py +1982 -1563
  37. package/core/connect.py +686 -0
  38. package/core/events.py +123 -61
  39. package/core/file_mentions.py +280 -0
  40. package/core/interaction.py +411 -328
  41. package/core/line_pattern.py +128 -0
  42. package/core/loop.py +2566 -1490
  43. package/core/memory.py +482 -370
  44. package/core/pipeline_models.py +190 -176
  45. package/core/provider_errors.py +234 -0
  46. package/core/reasoning/authorization.py +130 -130
  47. package/core/reasoning/base.py +219 -219
  48. package/core/reasoning/confidence_scoring.py +484 -468
  49. package/core/reasoning/events.py +149 -149
  50. package/core/reasoning/json_retry.py +19 -1
  51. package/core/reasoning/orchestrator.py +1561 -1382
  52. package/core/reasoning/output_writer.py +345 -286
  53. package/core/reasoning/payload_validation.py +524 -398
  54. package/core/reasoning/pipeline_storage.py +88 -22
  55. package/core/reasoning/review.py +659 -615
  56. package/core/reasoning/scholar.py +458 -434
  57. package/core/reasoning/source_corpus.py +433 -327
  58. package/core/reasoning/source_scoring.py +855 -855
  59. package/core/replay.py +315 -183
  60. package/core/session.py +36 -12
  61. package/core/session_view.py +259 -0
  62. package/core/session_wake.py +259 -0
  63. package/core/shell_sessions.py +1553 -0
  64. package/core/workspace_trust.py +1 -1
  65. package/credentials.py +148 -20
  66. package/database.py +333 -252
  67. package/{PRIVACY.md → docs/PRIVACY.md} +78 -66
  68. package/docs/SECURITY.md +108 -0
  69. package/docs/THIRD_PARTY_NOTICES.md +148 -0
  70. package/env_secrets.py +50 -9
  71. package/json_store.py +343 -123
  72. package/logging_setup.py +295 -185
  73. package/main.py +3433 -1961
  74. package/mcp_client/client.py +733 -499
  75. package/mcp_client/config.py +126 -21
  76. package/mcp_client/registration.py +343 -182
  77. package/memories/manager.py +147 -132
  78. package/memories/tui_commands.py +319 -244
  79. package/package.json +303 -73
  80. package/project_init/config_files.py +282 -278
  81. package/project_init/generator.py +728 -564
  82. package/project_init/manifest.py +18 -6
  83. package/project_init/tui_commands.py +147 -144
  84. package/prompts/critic_pass.md +24 -24
  85. package/prompts/revalidate.md +25 -25
  86. package/prompts/revise.md +2 -0
  87. package/prompts/source_grounding.md +66 -66
  88. package/prompts/system_prompts.py +316 -262
  89. package/providers.json.example +4 -2
  90. package/pyproject.toml +149 -100
  91. package/requirements.txt +295 -72
  92. package/safety/policy_enforcement.py +1082 -746
  93. package/security/askpass.py +419 -0
  94. package/security/capability.py +207 -177
  95. package/security/confine.py +484 -0
  96. package/security/hosted.py +182 -0
  97. package/security/permissions.py +237 -190
  98. package/security/posture.py +124 -12
  99. package/security/protected_paths.py +501 -309
  100. package/security/sandbox.py +4108 -985
  101. package/security/secrets.py +855 -0
  102. package/skills/builtin/math/formal-specification.md +67 -67
  103. package/skills/builtin/math/numerical-methods.md +66 -66
  104. package/skills/builtin/research/experiment-design.md +62 -62
  105. package/skills/builtin/research/reproducibility.md +55 -55
  106. package/skills/builtin/research/source-evaluation.md +70 -70
  107. package/skills/builtin/research/statistical-inference.md +63 -63
  108. package/skills/builtin/research/technical-writing.md +59 -59
  109. package/skills/builtin/software/code-review.md +61 -61
  110. package/skills/builtin/software/debugging.md +61 -61
  111. package/skills/builtin/software/test-design.md +67 -67
  112. package/skills/tui_commands.py +110 -111
  113. package/storage.py +1338 -1005
  114. package/tools/base.py +161 -1
  115. package/tools/builtin/_math_common.py +667 -377
  116. package/tools/builtin/_net_common.py +225 -19
  117. package/tools/builtin/arxiv.py +497 -39
  118. package/tools/builtin/ask_user.py +231 -213
  119. package/tools/builtin/discrete_math.py +35 -4
  120. package/tools/builtin/fetch_url.py +371 -153
  121. package/tools/builtin/file_ops.py +720 -412
  122. package/tools/builtin/geometry.py +48 -12
  123. package/tools/builtin/get_time.py +2 -2
  124. package/tools/builtin/linear_algebra.py +66 -23
  125. package/tools/builtin/load_skill.py +76 -66
  126. package/tools/builtin/logic.py +171 -12
  127. package/tools/builtin/pin.py +227 -193
  128. package/tools/builtin/probability_stats.py +12 -16
  129. package/tools/builtin/project_docs.py +464 -405
  130. package/tools/builtin/remember.py +175 -158
  131. package/tools/builtin/shell.py +980 -461
  132. package/tools/builtin/shell_sessions.py +613 -0
  133. package/tools/builtin/symbolic_math.py +80 -10
  134. package/tools/builtin/todo.py +149 -147
  135. package/tools/builtin/web_search.py +191 -13
  136. package/tools/context.py +159 -136
  137. package/tools/isolation.py +107 -34
  138. package/tools/registry.py +1242 -925
  139. package/tui/app.py +8318 -4100
  140. package/tui/app.tcss +747 -556
  141. package/tui/commands.py +26 -170
  142. package/tui/diffs.py +34 -13
  143. package/tui/history.py +128 -128
  144. package/tui/hosted_driver.py +102 -0
  145. package/tui/markdown.py +1329 -1279
  146. package/tui/meters.py +364 -268
  147. package/tui/ravens.py +146 -146
  148. package/tui/screens.py +1255 -943
  149. package/tui/themes.py +599 -559
  150. package/tui/widgets.py +3813 -2332
  151. package/SECURITY.md +0 -88
  152. package/THIRD_PARTY_NOTICES.md +0 -100
@@ -1,182 +1,343 @@
1
- """
2
- mcp_client/registration.py
3
-
4
- Turns connected MCP servers' tools into ToolSpecs and puts them in the
5
- registry at runtime (D15). ROADMAP_v2 §17.
6
-
7
- Naming is `mcp__<server>__<tool>`, which is what makes the rest of the
8
- system work without special cases:
9
- * security.permissions._default_for_unknown_tool() allows the prefix,
10
- * _default_for_unknown_approval() requires approval for it (§17 D),
11
- * assert_permissions_declared() exempts it (D24),
12
- * tui/ravens.py maps unknown tool names to a generic working state, so
13
- MCP tools animate with no table edit.
14
-
15
- Tool SCHEMAS are authored in Anthropic's native shape everywhere in this
16
- project and translated per-provider at the boundary in core/client.py.
17
- MCP's Tool is already almost that shape, so this is a rename rather than
18
- a translation -- but it is still done HERE, once, rather than teaching
19
- core/client.py about MCP types.
20
- """
21
-
22
- import logging
23
-
24
- from security import permissions
25
- from tools.base import BUDGET_IO, GRANT_ANYWHERE, ToolSpec
26
-
27
- logger = logging.getLogger(__name__)
28
-
29
- NAME_PREFIX = "mcp__"
30
-
31
- # server name -> the exact tool names registered for it.
32
- #
33
- # THE PREFIX IS NOT A PARSER. `mcp__<server>__<tool>` cannot be taken
34
- # apart again: neither `__` in a server name nor `__` in a tool name is
35
- # illegal anywhere, and both occur. Two consequences, both silent:
36
- #
37
- # * teardown by prefix over-matches. Disconnecting server "fs" scans for
38
- # "mcp__fs__", which also matches every tool of a still-connected
39
- # server named "fs__legacy" -- unregistering live tools and dropping
40
- # their approval defaults.
41
- # * names collide. tool_name_for("a", "b__c") and
42
- # tool_name_for("a__b", "c") are the same string, so registry.register
43
- # silently overwrites: a tool the user believes is approval-gated on
44
- # server `a` runs server `a__b`'s handler under a__b's autoApprove.
45
- #
46
- # A trusted project's .venastine/mcp.json can choose the colliding server
47
- # name -- the D29 impersonation threat, one separator away.
48
- #
49
- # Recording what was actually registered fixes both without rejecting any
50
- # mcp.json content, which decision G rules out: validation here is by
51
- # CONNECTING, not by schema.
52
- _registered: dict = {}
53
-
54
-
55
- def tool_name_for(server_name: str, tool_name: str) -> str:
56
- return f"{NAME_PREFIX}{server_name}__{tool_name}"
57
-
58
-
59
- def schema_for(server_name: str, tool) -> dict:
60
- """MCP Tool -> the Anthropic-native schema shape every TOOL_SCHEMA in
61
- tools/builtin/ uses.
62
-
63
- v2 spells these snake_case (.input_schema); v1 used .inputSchema. The
64
- getattr fallback covers both rather than breaking on a pin move --
65
- a stray empty schema here would be advertised to the model as a tool
66
- that takes no arguments, which fails at call time instead of load
67
- time and is the harder failure to trace.
68
- """
69
- input_schema = (
70
- getattr(tool, "input_schema", None)
71
- or getattr(tool, "inputSchema", None)
72
- or {"type": "object", "properties": {}}
73
- )
74
- description = getattr(tool, "description", None) or ""
75
- title = getattr(tool, "title", None)
76
- if title and title not in description:
77
- description = f"{title}. {description}".strip()
78
- return {
79
- "name": tool_name_for(server_name, tool.name),
80
- "description": f"[MCP: {server_name}] {description}".strip(),
81
- "input_schema": input_schema,
82
- }
83
-
84
-
85
- def _make_handler(client, server_name: str, tool_name: str):
86
- """A genuinely plain synchronous function -- no bridging logic leaks
87
- into the tool layer. client.call_tool() does the crossing (D2a) and
88
- returns an already-normalized dict (D23)."""
89
- def handler(params: dict) -> dict:
90
- return client.call_tool(server_name, tool_name, params)
91
- return handler
92
-
93
-
94
- def register_all(client, registry) -> list:
95
- """Register every tool from every connected server. Returns the tool
96
- names registered, so a caller can report what became available."""
97
- registered = []
98
- for server_name in sorted(client.clients):
99
- cfg = client.server_configs.get(server_name)
100
- auto_approve = bool(getattr(cfg, "auto_approve", False))
101
- try:
102
- tools = client.list_tools(server_name)
103
- except Exception as e:
104
- logger.warning("Could not list tools for MCP server %r: %s",
105
- server_name, e)
106
- continue
107
-
108
- for tool in tools:
109
- name = tool_name_for(server_name, tool.name)
110
- if name in registry._tools:
111
- # Never overwrite. The colliding registration would replace
112
- # BOTH the handler and (via set_dynamic_approval_default
113
- # below) the approval policy of a tool already in place --
114
- # so refusing loudly is the only outcome that can't be
115
- # mistaken for the tool the user thinks they are calling.
116
- logger.warning(
117
- "MCP tool name collision: %r from server %r is already "
118
- "registered; skipping it. Rename one of the servers or "
119
- "tools -- '__' in a name makes these ambiguous.",
120
- name, server_name)
121
- continue
122
- # Base approval default BEFORE registering, so there is no
123
- # window in which the tool is callable without its policy set.
124
- permissions.set_dynamic_approval_default(name, not auto_approve)
125
- registry.register(ToolSpec(
126
- name=name,
127
- schema=schema_for(server_name, tool),
128
- handler=_make_handler(client, server_name, tool.name),
129
- # §25 R13. Stated here rather than left to
130
- # registry.grant_policy's mcp__* fallback: this is the
131
- # site that makes the decision, and MCP tools are the
132
- # grant picker's real population -- R1's argument that
133
- # the tool's own description is the whole of informed
134
- # consent was written about exactly these, because MCP
135
- # exposes no read-only/write metadata for anything to
136
- # reason from. The fallback stays as documentation for
137
- # any other dynamic registrant.
138
- grant_policy=GRANT_ANYWHERE,
139
- # H1. Exempt from assert_budget_declared for the reason
140
- # R13 exempts them -- named at connection time, so no
141
- # static declaration can exist -- and declared anyway,
142
- # because these tools DO have a bound and it is worth
143
- # naming which: client.call_tool wraps every call in the
144
- # two-layer clock DEFAULT_CALL_TIMEOUT_S backstops. That
145
- # is BUDGET_IO exactly, and it is the mechanism H2 was
146
- # modelled on.
147
- budget=BUDGET_IO,
148
- ))
149
- _registered.setdefault(server_name, []).append(name)
150
- registered.append(name)
151
-
152
- if auto_approve:
153
- # WARNING, not INFO (F4): TranscriptLogHandler forwards
154
- # WARNING+ into the TUI transcript, and on that path stderr is
155
- # already closed -- at INFO this reached nothing but app.log,
156
- # so the shell where approval prompts are MODALS was exactly
157
- # the one never told some tools would not prompt. Fires every
158
- # launch per auto-approved server, deliberately (#60): worst
159
- # case it trains people past it, which equals today's silence;
160
- # best case it is read once and someone catches a flag they
161
- # did not knowingly set.
162
- logger.warning("MCP server %r is auto-approved; its tools will "
163
- "not prompt before running.", server_name)
164
-
165
- logger.info("Registered %d MCP tool(s).", len(registered))
166
- return registered
167
-
168
-
169
- def unregister_all(registry, server_name: str = None) -> None:
170
- """Remove MCP tools from the registry and drop their approval
171
- defaults. Idempotent -- disconnect handling can run more than once
172
- for the same server, which is why registry.unregister() is too.
173
-
174
- Removes exactly what register_all() put in, by name. A prefix scan
175
- would take a sibling server's tools with it whenever one server's
176
- name is a `__`-prefix of another's (see _registered above).
177
- """
178
- servers = [server_name] if server_name is not None else list(_registered)
179
- for server in servers:
180
- for name in _registered.pop(server, []):
181
- registry.unregister(name)
182
- permissions.clear_dynamic_approval_defaults(name)
1
+ """
2
+ mcp_client/registration.py
3
+
4
+ Turns connected MCP servers' tools into ToolSpecs and puts them in the
5
+ registry at runtime (D15). ROADMAP_v2 §17.
6
+
7
+ Naming is `mcp__<server>__<tool>`, which is what makes the rest of the
8
+ system work without special cases:
9
+ * security.permissions._default_for_unknown_tool() allows the prefix,
10
+ * _default_for_unknown_approval() requires approval for it (§17 D),
11
+ * assert_permissions_declared() exempts it (D24),
12
+ * tui/ravens.py maps unknown tool names to a generic working state, so
13
+ MCP tools animate with no table edit.
14
+
15
+ Tool SCHEMAS are authored in Anthropic's native shape everywhere in this
16
+ project and translated per-provider at the boundary in core/client.py.
17
+ MCP's Tool is already almost that shape, so this is a rename rather than
18
+ a translation -- but it is still done HERE, once, rather than teaching
19
+ core/client.py about MCP types.
20
+ """
21
+
22
+ import json
23
+ import logging
24
+ import re
25
+
26
+ from security import permissions
27
+ from tools.base import BUDGET_IO, GRANT_ANYWHERE, ToolSpec
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ NAME_PREFIX = "mcp__"
32
+
33
+ # WHAT A PROVIDER WILL ACCEPT AS A TOOL NAME. Anthropic, OpenAI and Google
34
+ # all publish the same rule -- `^[a-zA-Z0-9_-]{1,64}$` -- and BOTH halves
35
+ # of the composed name are outside this repository's control: the server
36
+ # half is a free-form key in mcp.json, the tool half comes from the server.
37
+ # Verified against the installed mcp==2.0.0, and again on 2.2.0 and 2.3.0:
38
+ # Tool.model_fields["name"] is a bare required `str` with empty metadata --
39
+ # no pattern, no max length.
40
+ #
41
+ # The prefix spends 7 of the 64 before either name starts.
42
+ #
43
+ # Checked HERE because this is the last place the fact is knowable:
44
+ # registration is the one function that sees the server name and the tool
45
+ # name together, and neither core/client.py (which translates schemas) nor
46
+ # tools/registry.py (which dispatches) has a reason to know what a
47
+ # provider will accept. All 31 of this harness's own tool names satisfy the
48
+ # rule, which is what makes it a bound on third-party names rather than a
49
+ # constraint the project would have to live down to.
50
+ MAX_TOOL_NAME_CHARS = 64
51
+ _NAME_CHAR = re.compile(r"[A-Za-z0-9_-]")
52
+
53
+ # THE TWO BOUNDS ON THIRD-PARTY TEXT IN AN ADVERTISED SCHEMA. Both are
54
+ # paid on EVERY model call for the rest of the session, because
55
+ # registry.schemas() is recomputed at the top of each one (K7) -- which is
56
+ # the difference between these and the bound on a tool RESULT (A79),
57
+ # paid once per call.
58
+ #
59
+ # Deliberately NOT config.MAX_CATALOG_TEXT_CHARS. 300 is right for a
60
+ # one-line catalog bullet and would mutilate a legitimate tool
61
+ # description; sharing the constant would couple two bounds that answer
62
+ # different questions. 2000 is 2.5x the longest description this harness
63
+ # ships (786, `shell_interactive`) and 25x smaller than the 50 KB a probe
64
+ # drove through here.
65
+ MAX_TOOL_DESCRIPTION_CHARS = 2000
66
+
67
+ # And the whole advertised schema, because `description` is not the only
68
+ # third-party string in it: input_schema arrives from the server untouched
69
+ # and a property description is model-facing text in the same request.
70
+ # Capping the strings INSIDE it was declined -- a truncated enum or
71
+ # pattern is a tool that fails at call time instead of load time -- so an
72
+ # oversized schema loses the tool instead, by name, which is the outcome
73
+ # shape the collision branch below already has. 16384 is ~3.6x the largest
74
+ # schema this harness ships (4544, `shell`).
75
+ MAX_TOOL_SCHEMA_CHARS = 16384
76
+
77
+ # server name -> the exact tool names registered for it.
78
+ #
79
+ # THE PREFIX IS NOT A PARSER. `mcp__<server>__<tool>` cannot be taken
80
+ # apart again: neither `__` in a server name nor `__` in a tool name is
81
+ # illegal anywhere, and both occur. Two consequences, both silent:
82
+ #
83
+ # * teardown by prefix over-matches. Disconnecting server "fs" scans for
84
+ # "mcp__fs__", which also matches every tool of a still-connected
85
+ # server named "fs__legacy" -- unregistering live tools and dropping
86
+ # their approval defaults.
87
+ # * names collide. tool_name_for("a", "b__c") and
88
+ # tool_name_for("a__b", "c") are the same string, so registry.register
89
+ # silently overwrites: a tool the user believes is approval-gated on
90
+ # server `a` runs server `a__b`'s handler under a__b's autoApprove.
91
+ #
92
+ # A trusted project's .venastine/mcp.json can choose the colliding server
93
+ # name -- the D29 impersonation threat, one separator away.
94
+ #
95
+ # Recording what was actually registered fixes both without rejecting any
96
+ # mcp.json content, which decision G rules out: validation here is by
97
+ # CONNECTING, not by schema.
98
+ #
99
+ # THAT SENTENCE IS ABOUT THESE TWO HAZARDS AND NOT ABOUT NAMES IN GENERAL,
100
+ # and batch 150 is where the difference started to matter. A name that
101
+ # COLLIDES is recorded rather than rejected, as above. A name no provider
102
+ # will accept is refused at registration (A30), which is not up-front
103
+ # schema validation of mcp.json -- nothing below reads the file -- and is
104
+ # decision G's own remedy: that one server's named failure rather than a
105
+ # startup error for everything else.
106
+ _registered: dict = {}
107
+
108
+
109
+ def tool_name_for(server_name: str, tool_name: str) -> str:
110
+ return f"{NAME_PREFIX}{server_name}__{tool_name}"
111
+
112
+
113
+ def _illegal_chars(text: str) -> list:
114
+ return sorted({c for c in text if not _NAME_CHAR.match(c)})
115
+
116
+
117
+ def _unadvertisable(name: str) -> str:
118
+ """Why no provider will accept this as a tool name, or "".
119
+
120
+ A REASON rather than a boolean, because it is going into a log line
121
+ somebody has to act on: the server is theirs to rename and the tool is
122
+ not, and which one they can fix depends on which half is wrong.
123
+ """
124
+ if not name:
125
+ return "it is empty"
126
+ if len(name) > MAX_TOOL_NAME_CHARS:
127
+ return (f"it is {len(name)} characters and the limit is "
128
+ f"{MAX_TOOL_NAME_CHARS}")
129
+ bad = _illegal_chars(name)
130
+ if bad:
131
+ return ("it contains " + ", ".join(repr(c) for c in bad)
132
+ + "; only letters, digits, '_' and '-' are accepted")
133
+ return ""
134
+
135
+
136
+ def _bounded(text: str) -> str:
137
+ """One line, capped -- A5's two rules on a string that enters every
138
+ model call, applied at the producer.
139
+
140
+ The same shape as core/config_loader._catalog_text, including the
141
+ VISIBLE ellipsis (a model reading a cut-off description should be able
142
+ to tell), with its own constant for the reason stated above. A5's
143
+ security half applies here too, one step removed: a tool schema is a
144
+ JSON array rather than a rendered list, so a newline cannot leave its
145
+ bullet the way #131's did -- but the newlines still arrive, and what
146
+ they can do then depends on a consumer. That dependence is what A5
147
+ exists to remove, and this project has already paid for it once at the
148
+ consumer end: core/reasoning/authorization.py takes
149
+ `description.strip().splitlines()[0]` for the grant picker, which is a
150
+ consumer defending itself against this producer.
151
+ """
152
+ collapsed = " ".join(str(text).split())
153
+ if len(collapsed) <= MAX_TOOL_DESCRIPTION_CHARS:
154
+ return collapsed
155
+ return collapsed[:MAX_TOOL_DESCRIPTION_CHARS - 1].rstrip() + "\u2026"
156
+
157
+
158
+ def _too_big(schema: dict) -> str:
159
+ """Why this schema cannot be advertised, or "".
160
+
161
+ Measured on the SERIALISED form, because that is what is paid: the
162
+ dict goes to the provider as JSON on every call. A schema that will
163
+ not serialise at all is refused by the same gate -- it could not be
164
+ sent either way, and finding that out here names the server instead
165
+ of raising inside the provider branch in core/client.py.
166
+ """
167
+ try:
168
+ size = len(json.dumps(schema))
169
+ except (TypeError, ValueError) as e:
170
+ return f"its schema is not JSON-serialisable ({e})"
171
+ if size > MAX_TOOL_SCHEMA_CHARS:
172
+ return (f"its schema is {size} characters and the limit is "
173
+ f"{MAX_TOOL_SCHEMA_CHARS}")
174
+ return ""
175
+
176
+
177
+ def schema_for(server_name: str, tool) -> dict:
178
+ """MCP Tool -> the Anthropic-native schema shape every TOOL_SCHEMA in
179
+ tools/builtin/ uses.
180
+
181
+ v2 spells these snake_case (.input_schema); v1 used .inputSchema. The
182
+ getattr fallback covers both rather than breaking on a pin move --
183
+ a stray empty schema here would be advertised to the model as a tool
184
+ that takes no arguments, which fails at call time instead of load
185
+ time and is the harder failure to trace.
186
+ """
187
+ input_schema = (
188
+ getattr(tool, "input_schema", None)
189
+ or getattr(tool, "inputSchema", None)
190
+ or {"type": "object", "properties": {}}
191
+ )
192
+ description = getattr(tool, "description", None) or ""
193
+ title = getattr(tool, "title", None)
194
+ if title and title not in description:
195
+ description = f"{title}. {description}".strip()
196
+ return {
197
+ "name": tool_name_for(server_name, tool.name),
198
+ # BOUNDED AFTER the prefix and the title are composed in, so one
199
+ # call covers all three strings: `title` is server-supplied too
200
+ # and reaches the model through this field, which a cap applied
201
+ # before the concatenation would have missed.
202
+ "description": _bounded(f"[MCP: {server_name}] {description}"),
203
+ "input_schema": input_schema,
204
+ }
205
+
206
+
207
+ def _make_handler(client, server_name: str, tool_name: str):
208
+ """A genuinely plain synchronous function -- no bridging logic leaks
209
+ into the tool layer. client.call_tool() does the crossing (D2a) and
210
+ returns an already-normalized dict (D23)."""
211
+ def handler(params: dict) -> dict:
212
+ return client.call_tool(server_name, tool_name, params)
213
+ return handler
214
+
215
+
216
+ def register_all(client, registry) -> list:
217
+ """Register every tool from every connected server. Returns the tool
218
+ names registered, so a caller can report what became available."""
219
+ registered = []
220
+ for server_name in sorted(client.clients):
221
+ cfg = client.server_configs.get(server_name)
222
+ auto_approve = bool(getattr(cfg, "auto_approve", False))
223
+ # ONE WARNING FOR THE SERVER, not one per tool: a character the
224
+ # rule rejects in the SERVER half poisons every name it composes,
225
+ # and `"my.server"` or `"api.example.com"` is an ordinary
226
+ # mcp.json key. The tool half is checked per tool below, where
227
+ # only that tool is lost.
228
+ bad_chars = _illegal_chars(server_name)
229
+ if bad_chars:
230
+ logger.warning(
231
+ "MCP server %r can compose no advertisable tool name: its "
232
+ "name contains %s, and a provider accepts only letters, "
233
+ "digits, '_' and '-' in a tool name. Rename the server in "
234
+ "mcp.json; none of its tools are registered.",
235
+ server_name, ", ".join(repr(c) for c in bad_chars))
236
+ continue
237
+ try:
238
+ tools = client.list_tools(server_name)
239
+ except Exception as e:
240
+ logger.warning("Could not list tools for MCP server %r: %s",
241
+ server_name, e)
242
+ continue
243
+
244
+ for tool in tools:
245
+ name = tool_name_for(server_name, tool.name)
246
+ # REFUSE, DO NOT MANGLE (A30). A silently renamed tool is one
247
+ # the model cannot name back, and the prefix is not a parser,
248
+ # so a generated name maps to no server. Refusing is also the
249
+ # only outcome that keeps this module's own invariant the
250
+ # right way up: "one unreachable server must never take down
251
+ # the others" has an inversion, and advertising a name no
252
+ # provider accepts is it -- one list comprehension builds the
253
+ # whole `tools` array, so one bad name makes EVERY request
254
+ # malformed, in plain chat and all ten research passes, and a
255
+ # 400 is not transient so nothing retries it.
256
+ #
257
+ # Within decision G rather than against it: G says an entry we
258
+ # cannot make sense of becomes that one server's NAMED
259
+ # failure instead of a startup error for everything else,
260
+ # which is exactly what this is. What G rules out is
261
+ # up-front SCHEMA validation of mcp.json, and nothing here
262
+ # reads the file.
263
+ schema = schema_for(server_name, tool)
264
+ refusal = _unadvertisable(name) or _too_big(schema)
265
+ if refusal:
266
+ logger.warning(
267
+ "MCP tool %r from server %r cannot be advertised: %s. "
268
+ "Skipping it; the server's other tools are unaffected.",
269
+ name, server_name, refusal)
270
+ continue
271
+ if name in registry._tools:
272
+ # Never overwrite. The colliding registration would replace
273
+ # BOTH the handler and (via set_dynamic_approval_default
274
+ # below) the approval policy of a tool already in place --
275
+ # so refusing loudly is the only outcome that can't be
276
+ # mistaken for the tool the user thinks they are calling.
277
+ logger.warning(
278
+ "MCP tool name collision: %r from server %r is already "
279
+ "registered; skipping it. Rename one of the servers or "
280
+ "tools -- '__' in a name makes these ambiguous.",
281
+ name, server_name)
282
+ continue
283
+ # Base approval default BEFORE registering, so there is no
284
+ # window in which the tool is callable without its policy set.
285
+ permissions.set_dynamic_approval_default(name, not auto_approve)
286
+ registry.register(ToolSpec(
287
+ name=name,
288
+ schema=schema,
289
+ handler=_make_handler(client, server_name, tool.name),
290
+ # §25 R13. Stated here rather than left to
291
+ # registry.grant_policy's mcp__* fallback: this is the
292
+ # site that makes the decision, and MCP tools are the
293
+ # grant picker's real population -- R1's argument that
294
+ # the tool's own description is the whole of informed
295
+ # consent was written about exactly these, because MCP
296
+ # exposes no read-only/write metadata for anything to
297
+ # reason from. The fallback stays as documentation for
298
+ # any other dynamic registrant.
299
+ grant_policy=GRANT_ANYWHERE,
300
+ # H1. Exempt from assert_budget_declared for the reason
301
+ # R13 exempts them -- named at connection time, so no
302
+ # static declaration can exist -- and declared anyway,
303
+ # because these tools DO have a bound and it is worth
304
+ # naming which: client.call_tool wraps every call in the
305
+ # two-layer clock DEFAULT_CALL_TIMEOUT_S backstops. That
306
+ # is BUDGET_IO exactly, and it is the mechanism H2 was
307
+ # modelled on.
308
+ budget=BUDGET_IO,
309
+ ))
310
+ _registered.setdefault(server_name, []).append(name)
311
+ registered.append(name)
312
+
313
+ if auto_approve:
314
+ # WARNING, not INFO (F4): TranscriptLogHandler forwards
315
+ # WARNING+ into the TUI transcript, and on that path stderr is
316
+ # already closed -- at INFO this reached nothing but app.log,
317
+ # so the shell where approval prompts are MODALS was exactly
318
+ # the one never told some tools would not prompt. Fires every
319
+ # launch per auto-approved server, deliberately (#60): worst
320
+ # case it trains people past it, which equals today's silence;
321
+ # best case it is read once and someone catches a flag they
322
+ # did not knowingly set.
323
+ logger.warning("MCP server %r is auto-approved; its tools will "
324
+ "not prompt before running.", server_name)
325
+
326
+ logger.info("Registered %d MCP tool(s).", len(registered))
327
+ return registered
328
+
329
+
330
+ def unregister_all(registry, server_name: str = None) -> None:
331
+ """Remove MCP tools from the registry and drop their approval
332
+ defaults. Idempotent -- disconnect handling can run more than once
333
+ for the same server, which is why registry.unregister() is too.
334
+
335
+ Removes exactly what register_all() put in, by name. A prefix scan
336
+ would take a sibling server's tools with it whenever one server's
337
+ name is a `__`-prefix of another's (see _registered above).
338
+ """
339
+ servers = [server_name] if server_name is not None else list(_registered)
340
+ for server in servers:
341
+ for name in _registered.pop(server, []):
342
+ registry.unregister(name)
343
+ permissions.clear_dynamic_approval_defaults(name)