aia 2.0.0.0.pre.alpha → 2.0.0

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 (236) hide show
  1. checksums.yaml +4 -4
  2. data/.version +1 -1
  3. data/CHANGELOG.md +151 -228
  4. data/README.md +42 -19
  5. data/bin/aia +8 -3
  6. data/lib/aia/aia_completion.bash +2 -3
  7. data/lib/aia/aia_completion.fish +6 -5
  8. data/lib/aia/aia_completion.zsh +2 -3
  9. data/lib/aia/chat_loop.rb +24 -66
  10. data/lib/aia/config/cli_parser.rb +164 -123
  11. data/lib/aia/config/defaults.yml +12 -39
  12. data/lib/aia/config/mcp_parser.rb +42 -40
  13. data/lib/aia/config/model_spec.rb +8 -14
  14. data/lib/aia/config/validator.rb +144 -156
  15. data/lib/aia/config/value_caster.rb +76 -0
  16. data/lib/aia/config.rb +72 -54
  17. data/lib/aia/content_extractor.rb +2 -0
  18. data/lib/aia/cost_calculator.rb +1 -0
  19. data/lib/aia/crew.rb +29 -19
  20. data/lib/aia/debate_handler.rb +45 -20
  21. data/lib/aia/delegate_handler.rb +7 -3
  22. data/lib/aia/directive.rb +10 -8
  23. data/lib/aia/directives/configuration_directives.rb +164 -109
  24. data/lib/aia/directives/context_directives.rb +55 -40
  25. data/lib/aia/directives/execution_directives.rb +25 -25
  26. data/lib/aia/directives/model_directives.rb +112 -195
  27. data/lib/aia/directives/trakflow_directives.rb +27 -9
  28. data/lib/aia/directives/utility_directives.rb +86 -87
  29. data/lib/aia/directives/web_and_file_directives.rb +83 -63
  30. data/lib/aia/fact_asserter.rb +3 -3
  31. data/lib/aia/history_transfer.rb +64 -24
  32. data/lib/aia/layered_orchestrator.rb +66 -43
  33. data/lib/aia/logger.rb +27 -62
  34. data/lib/aia/mcp_config_normalizer.rb +27 -14
  35. data/lib/aia/mcp_connection_manager.rb +193 -186
  36. data/lib/aia/mcp_discovery.rb +43 -15
  37. data/lib/aia/mcp_grouper.rb +2 -1
  38. data/lib/aia/mcp_server_config.rb +48 -0
  39. data/lib/aia/mcp_utility.rb +28 -20
  40. data/lib/aia/mention_router.rb +22 -52
  41. data/lib/aia/modality_query.rb +36 -0
  42. data/lib/aia/model_alias_registry.rb +11 -11
  43. data/lib/aia/model_registry.rb +75 -0
  44. data/lib/aia/network_builder.rb +17 -11
  45. data/lib/aia/network_memory_manager.rb +6 -6
  46. data/lib/aia/patches/ruby_llm_streaming_error.rb +21 -4
  47. data/lib/aia/patches/ruby_llm_tool_param_compat.rb +18 -0
  48. data/lib/aia/pipeline_orchestrator.rb +88 -45
  49. data/lib/aia/plugin_monitor.rb +9 -6
  50. data/lib/aia/prompt_decomposer.rb +6 -4
  51. data/lib/aia/prompt_handler.rb +90 -69
  52. data/lib/aia/provider_registry.rb +105 -0
  53. data/lib/aia/robot_builder.rb +1 -1
  54. data/lib/aia/robot_factory.rb +77 -69
  55. data/lib/aia/robot_namer.rb +2 -8
  56. data/lib/aia/robot_sync.rb +79 -0
  57. data/lib/aia/role_catalog.rb +89 -0
  58. data/lib/aia/session.rb +32 -14
  59. data/lib/aia/session_tracker.rb +39 -41
  60. data/lib/aia/similarity_scorer.rb +5 -3
  61. data/lib/aia/skill_utils.rb +60 -19
  62. data/lib/aia/spawn_handler.rb +16 -4
  63. data/lib/aia/spawn_spec_parser.rb +6 -7
  64. data/lib/aia/special_mode_handler.rb +80 -57
  65. data/lib/aia/speech.rb +103 -0
  66. data/lib/aia/startup_coordinator.rb +17 -91
  67. data/lib/aia/streaming_runner.rb +16 -5
  68. data/lib/aia/system_prompt_assembler.rb +20 -15
  69. data/lib/aia/task_board.rb +60 -0
  70. data/lib/aia/task_coordinator.rb +10 -5
  71. data/lib/aia/timing.rb +15 -0
  72. data/lib/aia/tool_approver.rb +205 -0
  73. data/lib/aia/tool_filter.rb +1 -9
  74. data/lib/aia/tool_filter_strategy.rb +39 -25
  75. data/lib/aia/tool_introspection.rb +25 -0
  76. data/lib/aia/tool_loader.rb +71 -31
  77. data/lib/aia/tool_utility.rb +6 -5
  78. data/lib/aia/tools/delegate_to_foreman_tool.rb +6 -4
  79. data/lib/aia/tools/recruit_robot_tool.rb +12 -12
  80. data/lib/aia/tools/reskill_robot_tool.rb +7 -7
  81. data/lib/aia/tools/task_board_tool.rb +17 -16
  82. data/lib/aia/trakflow_bridge.rb +19 -11
  83. data/lib/aia/turn_state.rb +32 -8
  84. data/lib/aia/ui_presenter.rb +83 -59
  85. data/lib/aia/utility.rb +8 -24
  86. data/lib/aia/variable_input_collector.rb +1 -3
  87. data/lib/aia/verification_network.rb +10 -12
  88. data/lib/aia.rb +49 -8
  89. metadata +27 -162
  90. data/.better-commits.json +0 -150
  91. data/.config/tocer/configuration.yml +0 -6
  92. data/.envrc +0 -15
  93. data/.loki +0 -231
  94. data/.quality/flay_baseline.txt +0 -1
  95. data/.quality/flog_baseline.txt +0 -29
  96. data/.quality/reek_baseline.txt +0 -80
  97. data/.rubocop.yml +0 -116
  98. data/COMMITS.md +0 -196
  99. data/IMPLEMENTATION_PLAN.md +0 -506
  100. data/Rakefile +0 -160
  101. data/architecture_review.md +0 -314
  102. data/docs/AGENTS.md +0 -40
  103. data/docs/advanced-prompting.md +0 -814
  104. data/docs/assets/images/aia.png +0 -0
  105. data/docs/cli-reference.md +0 -1241
  106. data/docs/configuration.md +0 -747
  107. data/docs/contributing.md +0 -386
  108. data/docs/directives-reference.md +0 -1145
  109. data/docs/examples/index.md +0 -277
  110. data/docs/examples/mcp/index.md +0 -475
  111. data/docs/examples/prompts/analysis/index.md +0 -78
  112. data/docs/examples/prompts/automation/index.md +0 -109
  113. data/docs/examples/prompts/development/index.md +0 -125
  114. data/docs/examples/prompts/index.md +0 -333
  115. data/docs/examples/prompts/learning/index.md +0 -127
  116. data/docs/examples/prompts/writing/index.md +0 -62
  117. data/docs/examples/tools/index.md +0 -282
  118. data/docs/faq.md +0 -578
  119. data/docs/guides/available-models.md +0 -366
  120. data/docs/guides/basic-usage.md +0 -478
  121. data/docs/guides/chat.md +0 -680
  122. data/docs/guides/crew.md +0 -239
  123. data/docs/guides/executable-prompts.md +0 -331
  124. data/docs/guides/first-prompt.md +0 -454
  125. data/docs/guides/getting-started.md +0 -455
  126. data/docs/guides/image-generation.md +0 -507
  127. data/docs/guides/index.md +0 -48
  128. data/docs/guides/local-models.md +0 -306
  129. data/docs/guides/migrate-prompts.md +0 -335
  130. data/docs/guides/models.md +0 -1017
  131. data/docs/guides/shared-tools.md +0 -254
  132. data/docs/guides/tools.md +0 -831
  133. data/docs/index.md +0 -259
  134. data/docs/installation.md +0 -274
  135. data/docs/mcp-integration.md +0 -603
  136. data/docs/prompt_management.md +0 -665
  137. data/docs/security.md +0 -674
  138. data/docs/special_projects_guide.md +0 -386
  139. data/docs/tools-and-mcp-examples.md +0 -1211
  140. data/docs/workflows-and-pipelines.md +0 -636
  141. data/examples/.gitignore +0 -2
  142. data/examples/00_setup_aia.sh +0 -111
  143. data/examples/01_basic_usage.sh +0 -23
  144. data/examples/02_frontmatter.sh +0 -33
  145. data/examples/03_shell_integration.sh +0 -55
  146. data/examples/04_erb_templating.sh +0 -56
  147. data/examples/05_shell_then_erb.sh +0 -38
  148. data/examples/06_prompt_chaining.sh +0 -59
  149. data/examples/07_pipeline.sh +0 -46
  150. data/examples/08_context_files.sh +0 -43
  151. data/examples/09_roles.sh +0 -67
  152. data/examples/10_stdin_piping.sh +0 -49
  153. data/examples/11_multi_model.sh +0 -65
  154. data/examples/12_token_usage.sh +0 -52
  155. data/examples/13_cost_tracking.sh +0 -68
  156. data/examples/14_output_file.sh +0 -91
  157. data/examples/15_parameters.sh +0 -68
  158. data/examples/16_directives.sh +0 -113
  159. data/examples/17_require_and_conditionals.sh +0 -68
  160. data/examples/18_tools.sh +0 -61
  161. data/examples/19_local_tools.sh +0 -34
  162. data/examples/20_mcp_servers.sh +0 -102
  163. data/examples/21_executable_prompts.sh +0 -78
  164. data/examples/22_chat_mode.sh +0 -217
  165. data/examples/23_verify.sh +0 -139
  166. data/examples/24_decompose.sh +0 -139
  167. data/examples/25_spawn.sh +0 -139
  168. data/examples/26_debate.sh +0 -97
  169. data/examples/27_mention_routing.sh +0 -157
  170. data/examples/28_model_switching.sh +0 -106
  171. data/examples/29_agent_harness.sh +0 -177
  172. data/examples/README.md +0 -321
  173. data/examples/advanced_multi_robot_capabilities_without_examples.md +0 -106
  174. data/examples/aia_config.yml +0 -22
  175. data/examples/aia_config_orchestrator.yml +0 -45
  176. data/examples/aia_config_with_mcp.yml +0 -21
  177. data/examples/common.sh +0 -39
  178. data/examples/context/project_goals.md +0 -6
  179. data/examples/context/tech_stack.md +0 -7
  180. data/examples/directives/timestamp_directive.rb +0 -22
  181. data/examples/mcp/filesystem.json +0 -9
  182. data/examples/prompts_dir/analyze.md +0 -2
  183. data/examples/prompts_dir/brainstorm.md +0 -2
  184. data/examples/prompts_dir/conditional.md +0 -17
  185. data/examples/prompts_dir/creative.md +0 -4
  186. data/examples/prompts_dir/erbinfo.md +0 -5
  187. data/examples/prompts_dir/erbinfo_raw.md +0 -8
  188. data/examples/prompts_dir/evaluate.md +0 -2
  189. data/examples/prompts_dir/explain_joke.md +0 -1
  190. data/examples/prompts_dir/explain_recursion.md +0 -1
  191. data/examples/prompts_dir/fun_fact +0 -3
  192. data/examples/prompts_dir/greeting.md +0 -8
  193. data/examples/prompts_dir/greeting_required.md +0 -7
  194. data/examples/prompts_dir/hello.md +0 -1
  195. data/examples/prompts_dir/includes/ruby_facts.md +0 -4
  196. data/examples/prompts_dir/limerick.md +0 -1
  197. data/examples/prompts_dir/list_with_mcp.md +0 -3
  198. data/examples/prompts_dir/pick_best.md +0 -2
  199. data/examples/prompts_dir/project_summary +0 -12
  200. data/examples/prompts_dir/quiz_with_include.md +0 -6
  201. data/examples/prompts_dir/require_demo.md +0 -5
  202. data/examples/prompts_dir/roles/formal.md +0 -3
  203. data/examples/prompts_dir/roles/orchestrator.md +0 -21
  204. data/examples/prompts_dir/roles/pirate.md +0 -3
  205. data/examples/prompts_dir/shell_then_erb.md +0 -6
  206. data/examples/prompts_dir/sort_compare.md +0 -2
  207. data/examples/prompts_dir/summarize_context.md +0 -2
  208. data/examples/prompts_dir/sysinfo.md +0 -5
  209. data/examples/prompts_dir/sysinfo_raw.md +0 -8
  210. data/examples/prompts_dir/tagline.md +0 -1
  211. data/examples/prompts_dir/tell_joke.md +0 -1
  212. data/examples/prompts_dir/tell_joke_with_next.md +0 -4
  213. data/examples/prompts_dir/use_local_tool.md +0 -8
  214. data/examples/prompts_dir/use_tools.md +0 -8
  215. data/examples/prompts_dir/weather.md +0 -2
  216. data/examples/prompts_dir/whats_new.md +0 -2
  217. data/examples/prompts_dir/with_timestamp.md +0 -5
  218. data/examples/requirements/sinatra_taskflow_app.md +0 -139
  219. data/examples/rules/01_classify_ruby.rb +0 -16
  220. data/examples/rules/02_prefer_claude_for_code.rb +0 -19
  221. data/examples/rules/03_gate_prompt_length.rb +0 -19
  222. data/examples/rules/04_tool_selection.rb +0 -41
  223. data/examples/rules/README.md +0 -30
  224. data/examples/run_all.sh +0 -294
  225. data/examples/tools/word_count_tool.rb +0 -30
  226. data/lib/AGENTS.md +0 -57
  227. data/lib/aia/model_switch_handler.rb +0 -100
  228. data/mcp_servers/README.md +0 -110
  229. data/mcp_servers/apple-mcp.json +0 -8
  230. data/mcp_servers/filesystem.json +0 -9
  231. data/mcp_servers/mcp_server_chart.json +0 -11
  232. data/mcp_servers/playwright_one.json +0 -8
  233. data/mcp_servers/playwright_server_definition.json +0 -9
  234. data/mcp_servers/playwright_two.json +0 -8
  235. data/mcp_servers/tavily_mcp_server.json +0 -8
  236. data/mkdocs.yml +0 -169
@@ -2,71 +2,131 @@
2
2
 
3
3
  # lib/aia/mcp_connection_manager.rb
4
4
  #
5
- # Single owner for MCP connection state. Handles connecting to configured
6
- # MCP servers concurrently, tracking successes/failures, and injecting
7
- # results into robots.
5
+ # Single owner for MCP connection state. Builds one RubyLLM::MCP server per
6
+ # configured MCP server (via RobotLab::MCP.build), connects them concurrently
7
+ # at startup, and hands the live server instances to every robot aia builds.
8
+ #
9
+ # Robots share these instances: robot_lab's per-robot MCP::Registry returns
10
+ # an already-registered instance unchanged, so each server process (or HTTP
11
+ # session) is started once per aia process no matter how many robots use it.
12
+ # Servers that fail to connect are left out, so robots never retry them on
13
+ # every turn.
8
14
 
9
15
  require 'timeout'
10
16
  require 'tty-spinner'
11
17
 
12
18
  module AIA
19
+ # :reek:TooManyMethods -- one small helper per connection-lifecycle concern (connect, record outcomes, query, close)
13
20
  class MCPConnectionManager
14
21
  # Maximum seconds to wait for a single MCP server to connect.
15
22
  DEFAULT_TIMEOUT = 30
16
23
 
17
- attr_reader :connected_clients, :connected_tools, :failed_servers
24
+ attr_reader :failed_servers
25
+
26
+ class << self
27
+ # Select the servers for this session (MCPDiscovery: --mcp-use,
28
+ # --mcp-skip, --no-mcp), connect them, and publish the results to
29
+ # AIA.config and AIA.mcp_manager.
30
+ #
31
+ # @param config [AIA::Config]
32
+ # @return [MCPConnectionManager]
33
+ def start(config)
34
+ manager = new
35
+ unless config.flags&.no_mcp
36
+ discovered = MCPDiscovery.new.discover(config)
37
+ warn_unknown_mcp_use_names(config, discovered)
38
+ manager.connect_all(discovered)
39
+ manager.update_config if manager.connected?
40
+ end
41
+ AIA.mcp_manager = manager
42
+ end
43
+
44
+ # Warn when --mcp-use names don't match any configured server.
45
+ # Helps users catch typos before a silent empty-tools session.
46
+ def warn_unknown_mcp_use_names(config, discovered)
47
+ requested = Array(config.mcp_use)
48
+ return if requested.empty?
49
+
50
+ missing = requested - discovered.map { AIA::Utility.server_name(it) }
51
+ return if missing.empty?
52
+
53
+ available = Array(config.mcp_servers).map { AIA::Utility.server_name(it) }
54
+ $stderr.puts "WARNING: --mcp-use specified server(s) not found in config: #{missing.join(', ')}"
55
+ $stderr.puts " Available servers: #{available.join(', ')}" if available.any?
56
+ end
57
+ end
18
58
 
19
59
  def initialize
20
- @connected_clients = {}
21
- @connected_tools = []
22
- @failed_servers = []
23
- @server_tool_counts = {}
24
- @connected = false
25
- @mutex = Mutex.new
60
+ @servers = {} # name => RubyLLM::MCP (connected)
61
+ @server_tools = {} # name => Array<RubyLLM::MCP::Tool>
62
+ @failed_servers = []
63
+ @connected = false
64
+ @mutex = Mutex.new
26
65
  end
27
66
 
28
67
  # Connect all configured MCP servers concurrently.
29
68
  # Each server gets its own spinner line and thread.
30
69
  #
31
- # @param servers [Array<Hash>] MCP server configurations
70
+ # @param configs [Array<Hash>] MCP server configurations
32
71
  # @return [self]
33
- def connect_all(servers)
34
- return self unless servers.is_a?(Array) && servers.any?
72
+ # :reek:TooManyStatements -- connection ceremony: spinner setup, thread launch, global timeout guard, summary logging
73
+ def connect_all(configs)
74
+ return self unless configs.is_a?(Array) && configs.any?
35
75
 
36
76
  reset_connection_state
37
- logger = AIA::LoggerManager.mcp_logger
38
- server_names = servers.map { |s| s.is_a?(Hash) ? s[:name] : s.to_s }.compact
39
- logger.info("MCP initialization: connecting #{servers.size} server(s): #{server_names.join(', ')}")
77
+ logger.info("MCP initialization: connecting #{configs.size} server(s): #{configs.map { config_name(it) }.join(', ')}")
40
78
 
41
- multi = TTY::Spinner::Multi.new("[:spinner] Connecting MCP servers", format: :dots, output: $stderr)
42
- threads = launch_server_threads(servers, multi, logger)
79
+ multi = TTY::Spinner::Multi.new("[:spinner] Connecting MCP servers", format: :dots, output: $stderr)
80
+ threads = launch_server_threads(configs, multi)
43
81
 
44
82
  # The global cap must never be smaller than the slowest single server's
45
83
  # timeout, or concurrent connections get killed before they can finish.
46
- global_limit = [global_connection_timeout, *servers.map { |s| server_timeout(s) }].max
84
+ global_limit = [global_connection_timeout, *configs.map { server_timeout(it) }].max
47
85
  Timeout.timeout(global_limit) { threads.each(&:join) }
48
86
 
49
87
  @connected = true
50
- logger.info("MCP initialization complete: #{@connected_clients.size} connected, #{@failed_servers.size} failed")
88
+ logger.info("MCP initialization complete: #{@servers.size} connected, #{@failed_servers.size} failed")
51
89
  self
52
90
  rescue Timeout::Error
53
- handle_global_timeout(servers, global_limit)
91
+ handle_global_timeout(configs, global_limit)
54
92
  end
55
93
 
56
- # Inject connected MCP clients and tools into robot(s).
94
+ # The connected servers, in connection order.
57
95
  #
58
- # @param robot [RobotLab::Robot, RobotLab::Network] the robot or network
59
- # @return [self]
60
- def inject_into(robot)
61
- clients, tools = @mutex.synchronize { [@connected_clients.dup, @connected_tools.dup] }
96
+ # @return [Array<RubyLLM::MCP>]
97
+ def servers
98
+ @mutex.synchronize { @servers.values }
99
+ end
62
100
 
63
- targets = robot.crew
101
+ # The connected servers named by +configs+ (Hashes, names, or servers),
102
+ # skipping any that are not connected.
103
+ #
104
+ # @param configs [Array<Hash, String, RubyLLM::MCP>]
105
+ # @return [Array<RubyLLM::MCP>]
106
+ def servers_for(configs)
107
+ @mutex.synchronize { Array(configs).filter_map { @servers[config_name(it)] } }
108
+ end
64
109
 
65
- targets.each do |target|
66
- target.inject_mcp!(clients: clients, tools: tools)
67
- end
110
+ # Find a connected server by name.
111
+ #
112
+ # @param name [String]
113
+ # @return [RubyLLM::MCP, nil]
114
+ def server(name)
115
+ @mutex.synchronize { @servers[name.to_s] }
116
+ end
68
117
 
69
- self
118
+ # Every connected server's tools.
119
+ #
120
+ # @return [Array<RubyLLM::MCP::Tool>]
121
+ def connected_tools
122
+ @mutex.synchronize { @server_tools.values.flatten }
123
+ end
124
+
125
+ # Tools grouped by the name of the server that offers them.
126
+ #
127
+ # @return [Hash{String => Array<RubyLLM::MCP::Tool>}]
128
+ def tools_by_server
129
+ @mutex.synchronize { @server_tools.transform_values(&:dup) }
70
130
  end
71
131
 
72
132
  # Update AIA config with connection results.
@@ -74,223 +134,170 @@ module AIA
74
134
  # @return [self]
75
135
  def update_config
76
136
  connected_keys, tool_counts, failed = @mutex.synchronize do
77
- [@connected_clients.keys.dup, @server_tool_counts.dup, @failed_servers.dup]
137
+ [@servers.keys, @server_tools.transform_values(&:size), @failed_servers.dup]
78
138
  end
79
- AIA.config.connected_mcp_servers = connected_keys
80
- AIA.config.mcp_server_tool_counts = tool_counts
81
- AIA.config.failed_mcp_servers = failed
139
+ cfg = AIA.config
140
+ cfg.connected_mcp_servers = connected_keys
141
+ cfg.mcp_server_tool_counts = tool_counts
142
+ cfg.failed_mcp_servers = failed
82
143
  self
83
144
  end
84
145
 
85
- # Whether connect_all has been called.
146
+ # Whether connect_all has run to completion (or hit the global timeout).
86
147
  def connected?
87
148
  @connected
88
149
  end
89
150
 
90
- # Whether any tools were collected (from config servers or Ruby require).
151
+ # Whether any MCP tools were collected.
91
152
  def any_tools?
92
- @mutex.synchronize { @connected_tools.any? }
93
- end
94
-
95
- # Absorb MCP clients registered in RubyLLM::MCP (e.g., via --require loading
96
- # shared_tools/mcp/* files) that are not already tracked by this manager.
97
- # Starts any unstarted clients, extracts their tools, and merges them into
98
- # the connected state so inject_into will include them in the robot.
99
- #
100
- # @return [self]
101
- def absorb_ruby_llm_mcp_clients
102
- return self unless defined?(RubyLLM::MCP)
103
-
104
- logger = AIA::LoggerManager.mcp_logger
105
-
106
- RubyLLM::MCP.clients.each do |name, client|
107
- next if @connected_clients.key?(name)
108
-
109
- begin
110
- client.start unless client.alive?
111
-
112
- if client.alive?
113
- tools = client.tools rescue []
114
- @mutex.synchronize do
115
- @connected_clients[name] = client
116
- @server_tool_counts[name] = tools.size
117
- @connected_tools.concat(tools)
118
- end
119
- logger.info("MCP: absorbed RubyLLM::MCP client '#{name}' (#{tools.size} tools)")
120
- else
121
- logger.warn("MCP: RubyLLM::MCP client '#{name}' not alive, skipping")
122
- end
123
- rescue StandardError => e
124
- logger.warn("MCP: error absorbing RubyLLM::MCP client '#{name}': #{e.message}")
125
- end
126
- end
127
-
128
- @connected = true unless RubyLLM::MCP.clients.empty?
129
- self
130
- end
131
-
132
- # Find an MCP client by server name.
133
- #
134
- # @param name [String] server name
135
- # @return [RobotLab::MCP::Client, nil]
136
- def client(name)
137
- @connected_clients[name]
153
+ @mutex.synchronize { @server_tools.values.any?(&:any?) }
138
154
  end
139
155
 
140
156
  # Connected server names.
141
157
  #
142
158
  # @return [Array<String>]
143
159
  def connected_server_names
144
- @mutex.synchronize { @connected_clients.keys.dup }
160
+ @mutex.synchronize { @servers.keys }
145
161
  end
146
162
 
147
163
  # Failed server names.
148
164
  #
149
165
  # @return [Array<String>]
150
166
  def failed_server_names
151
- @mutex.synchronize { @failed_servers.map { |f| f[:name] } }
167
+ @mutex.synchronize { @failed_servers.map { it[:name] } }
152
168
  end
153
169
 
154
- # Close all connected MCP clients and reset connection state.
155
- # Errors from individual client closes are silently rescued —
156
- # best-effort cleanup on process exit.
170
+ # Close all connected servers (stopping stdio processes) and reset state.
157
171
  def close_all
158
- clients = @mutex.synchronize { @connected_clients.dup }
159
- clients.each_value do |client|
160
- client.close
161
- rescue StandardError
162
- # best-effort — client may already be closed
163
- end
172
+ servers.each { close_quietly(it) }
164
173
  @mutex.synchronize do
165
- @connected_clients = {}
166
- @connected_tools = []
167
- @server_tool_counts = {}
168
- @connected = false
174
+ @servers = {}
175
+ @server_tools = {}
176
+ @connected = false
169
177
  end
170
178
  end
171
179
 
172
180
  private
173
181
 
174
182
  def reset_connection_state
175
- @connected_clients = {}
176
- @connected_tools = []
177
- @failed_servers = []
183
+ @servers = {}
184
+ @server_tools = {}
185
+ @failed_servers = []
186
+ end
187
+
188
+ def config_name(spec)
189
+ AIA::Utility.server_name(spec).to_s
178
190
  end
179
191
 
180
- def launch_server_threads(servers, multi, logger)
181
- servers.map do |server_config|
182
- name = server_config.is_a?(Hash) ? (server_config[:name] || server_config['name']) : server_config.to_s
192
+ # The shared MCP log (memoized by LoggerManager, safe across the connect threads).
193
+ def logger
194
+ AIA::LoggerManager.mcp_logger
195
+ end
196
+
197
+ def launch_server_threads(configs, multi)
198
+ configs.map do |server_config|
199
+ name = config_name(server_config)
183
200
  spinner = multi.register("[:spinner] #{name}")
184
- Thread.new(server_config, name, spinner) { |cfg, srv_name, sp| connect_one(cfg, srv_name, sp, logger) }
201
+ Thread.new(server_config, name, spinner) { |cfg, srv_name, sp| connect_one(cfg, srv_name, sp) }
185
202
  end
186
203
  end
187
204
 
188
- def handle_global_timeout(servers, global_limit)
189
- logger = AIA::LoggerManager.mcp_logger
205
+ def handle_global_timeout(configs, global_limit)
190
206
  logger.warn("MCP: Global connection timeout (#{global_limit}s) reached")
191
207
 
192
- connected_names = @mutex.synchronize { @connected_clients.keys.to_set }
193
- failed_names = @mutex.synchronize { @failed_servers.to_set { |f| f[:name] } }
194
-
195
- servers.each do |server_config|
196
- srv_name = server_config.is_a?(Hash) ? (server_config[:name] || server_config['name']) : server_config.to_s
197
- next if connected_names.include?(srv_name) || failed_names.include?(srv_name)
198
- @mutex.synchronize { @failed_servers << { name: srv_name, error: "global connection timeout (#{global_limit}s)" } }
208
+ @mutex.synchronize do
209
+ settled = @servers.keys + @failed_servers.map { it[:name] }
210
+ stragglers = configs.map { config_name(it) } - settled
211
+ @failed_servers.concat(stragglers.map { { name: it, error: "global connection timeout (#{global_limit}s)" } })
212
+ @connected = true
199
213
  end
214
+ self
200
215
  end
201
216
 
202
217
  # Read global MCP connection timeout from config.
203
218
  # Falls back to 120s if config is unavailable.
204
219
  def global_connection_timeout
205
- AIA.config&.concurrency&.mcp_timeout.to_i.then { |v| v.positive? ? v : 120 }
220
+ AIA.config&.concurrency&.mcp_timeout.to_i.then { it.positive? ? it : 120 }
206
221
  rescue StandardError
207
222
  120
208
223
  end
209
224
 
210
- # Connect a single MCP server, updating the spinner on completion.
211
- # rubocop:disable Metrics/MethodLength
212
- def connect_one(server_config, name, spinner, logger)
225
+ # Build and connect a single MCP server, updating the spinner on completion.
226
+ # Listing the server's tools is what makes RubyLLM::MCP connect.
227
+ # :reek:TooManyStatements -- one connect attempt with per-outcome reporting (success, timeout, error)
228
+ def connect_one(server_config, name, spinner)
213
229
  timeout = server_timeout(server_config)
214
230
  spinner.auto_spin
215
-
216
231
  logger.info("MCP: connecting to '#{name}'...")
217
- # rubocop:disable Metrics/BlockLength
218
- Timeout.timeout(timeout) do
219
- client = RobotLab::MCP::Client.new(server_config)
220
- client.connect
221
-
222
- if client.connected?
223
- tools = client.list_tools
224
- built_tools = tools.map do |tool_def|
225
- tool_name = tool_def[:name]
226
- mcp_client = client
227
- RobotLab::Tool.create(
228
- name: tool_name,
229
- description: tool_def[:description],
230
- parameters: tool_def[:inputSchema],
231
- mcp: name
232
- ) { |args| mcp_client.call_tool(tool_name, args) }
233
- end
234
-
235
- @mutex.synchronize do
236
- @connected_clients[name] = client
237
- @server_tool_counts[name] = tools.size
238
- add_tools_deduped(built_tools, name, logger)
239
- end
240
-
241
- logger.info("MCP: '#{name}' connected (#{tools.size} tools)")
242
- spinner.success("(#{tools.size} tools)")
243
- else
244
- @mutex.synchronize do
245
- @failed_servers << { name: name, error: "connection failed" }
246
- end
247
- logger.warn("MCP: '#{name}' failed to connect")
248
- spinner.error("(connection failed)")
249
- end
250
- end
251
- # rubocop:enable Metrics/BlockLength
232
+
233
+ server = RobotLab::MCP.build(MCPConfigNormalizer.normalize(server_config))
234
+ tools = Timeout.timeout(timeout) { server.tools }
235
+ record_connected(name, server, tools, spinner)
252
236
  rescue Timeout::Error
253
- @mutex.synchronize do
254
- @failed_servers << { name: name, error: "timed out after #{timeout}s" }
255
- end
256
- logger.warn("MCP: '#{name}' timed out after #{timeout}s")
257
- spinner.error("(timed out)")
237
+ close_quietly(server)
238
+ report_failure(name, "timed out after #{timeout}s", "(timed out)", spinner)
258
239
  rescue StandardError => e
259
- @mutex.synchronize do
260
- @failed_servers << { name: name, error: e.message }
261
- end
262
- logger.warn("MCP: '#{name}' error: #{e.message}")
263
- spinner.error("(#{e.message})")
240
+ close_quietly(server)
241
+ report_failure(name, e.message, "(#{e.message})", spinner)
264
242
  end
265
- # rubocop:enable Metrics/MethodLength
266
243
 
267
- # Add tools to @connected_tools, skipping any whose name is already present.
268
- # Logs a warning for each duplicate so the user knows which server wins.
269
- # MUST be called inside @mutex.synchronize.
270
- #
271
- # @param new_tools [Array] tools to add
272
- # @param server_name [String] name of the server providing these tools (for warning)
273
- # @param logger [Logger] MCP logger
274
- def add_tools_deduped(new_tools, server_name, logger)
275
- new_tools.each do |tool|
276
- tool_name = tool.respond_to?(:name) ? tool.name : tool.to_s
277
- existing = @connected_tools.find do |t|
278
- (t.respond_to?(:name) ? t.name : t.to_s) == tool_name
244
+ # Record a connected server. robot_lab refuses to offer two tools with one
245
+ # name, so a server whose tool names clash with an already-connected
246
+ # server's is recorded as failed with the fix (prefix:) spelled out.
247
+ def record_connected(name, server, tools, spinner)
248
+ clash = @mutex.synchronize do
249
+ found = tool_name_clash(tools)
250
+ unless found
251
+ @servers[name] = server
252
+ @server_tools[name] = tools
279
253
  end
254
+ found
255
+ end
256
+ return report_clash(name, server, clash, spinner) if clash
280
257
 
281
- if existing
282
- logger.warn("MCP: Tool '#{tool_name}' already registered from another server. " \
283
- "Skipping duplicate from '#{server_name}'.")
284
- else
285
- @connected_tools << tool
286
- end
258
+ logger.info("MCP: '#{name}' connected (#{tools.size} tools)")
259
+ spinner.success("(#{tools.size} tools)")
260
+ end
261
+
262
+ # MUST be called inside @mutex.synchronize.
263
+ # @return [Array(String, String), nil] [tool name, owning server] of the first clash
264
+ def tool_name_clash(tools)
265
+ names = tools.map { it.name.to_s }
266
+ @server_tools.each do |owner, owned|
267
+ dup = owned.map { it.name.to_s }.find { names.include?(it) }
268
+ return [dup, owner] if dup
287
269
  end
270
+ nil
288
271
  end
289
272
 
290
- # Extract timeout in seconds from server config.
291
- # Config values >= 1000 are treated as milliseconds.
273
+ def report_clash(name, server, clash, spinner)
274
+ close_quietly(server)
275
+ tool, owner = clash
276
+ report_failure(name, "tool '#{tool}' is also offered by '#{owner}'; give one server a prefix:",
277
+ "(duplicate tool '#{tool}')", spinner)
278
+ end
279
+
280
+ def report_failure(name, error, spinner_note, spinner)
281
+ @mutex.synchronize { @failed_servers << { name: name, error: error } }
282
+ logger.warn("MCP: '#{name}' error: #{error}")
283
+ spinner.error(spinner_note)
284
+ end
285
+
286
+ # Best-effort close; a server that never connected may raise.
287
+ def close_quietly(server)
288
+ server&.close
289
+ rescue StandardError
290
+ nil # nothing to clean up on a server that never started
291
+ end
292
+
293
+ # Extract timeout in seconds from server config, or from a RubyLLM::MCP
294
+ # subclass's own +timeout+ setting. Config values >= 1000 are treated as
295
+ # milliseconds.
292
296
  def server_timeout(server_config)
293
- raw = server_config.is_a?(Hash) ? server_config[:timeout] : nil
297
+ raw = case server_config
298
+ when Hash then server_config[:timeout] || server_config['timeout']
299
+ when Class then server_config.timeout if server_config.respond_to?(:timeout)
300
+ end
294
301
  return DEFAULT_TIMEOUT if raw.nil?
295
302
 
296
303
  seconds = raw.to_f
@@ -9,36 +9,64 @@ module AIA
9
9
  class MCPDiscovery
10
10
  def initialize; end
11
11
 
12
+ # The servers --mcp-use keeps (all of them when it is empty), minus
13
+ # those --mcp-skip names. Shared by sessions, --mcp-list and the banner.
14
+ #
15
+ # @param servers [Array<Hash>] configured servers
16
+ # @param use [Array<String>] --mcp-use names
17
+ # @param skip [Array<String>] --mcp-skip names
18
+ # @return [Array<Hash>]
19
+ def self.select(servers, use: [], skip: [])
20
+ use = Array(use)
21
+ skip = Array(skip)
22
+ kept = use.empty? ? Array(servers) : Array(servers).select { use.include?(AIA::Utility.server_name(it)) }
23
+ kept.reject { skip.include?(AIA::Utility.server_name(it)) }
24
+ end
25
+
12
26
  # Discover relevant MCP servers for the current prompt.
13
27
  # Priority: explicit --mcp-use list > all configured servers.
14
- # --mcp-skip is always applied last.
28
+ # --mcp-skip is always applied last. Entries that name a RubyLLM::MCP
29
+ # subclass are resolved to the class (see #resolve_entries).
15
30
  #
16
31
  # @param config the AIA configuration
17
- # @return [Array<Hash>] relevant MCP server configs
32
+ # @return [Array<Hash, Class<RubyLLM::MCP>>] relevant MCP server configs
18
33
  def discover(config)
19
34
  return [] if config.flags&.no_mcp
20
35
 
21
- servers = select_servers(config)
22
- apply_skip_filter(servers, config)
36
+ selected = self.class.select(config.mcp_servers || [], use: config.mcp_use, skip: config.mcp_skip)
37
+ resolve_entries(selected)
23
38
  end
24
39
 
25
- private
26
-
27
- def select_servers(config)
28
- return select_by_names(config.mcp_servers || [], Array(config.mcp_use)) if Array(config.mcp_use).any?
40
+ # Turn constant-name entries ("SharedTools::MCP::Memory") into their
41
+ # RubyLLM::MCP subclass, loaded by --require before MCP servers connect.
42
+ # An entry that names no such class, or whose class reports itself
43
+ # unavailable via +available?+ (e.g. a missing API key), is skipped
44
+ # with a one-line note. Hash entries pass through unchanged.
45
+ #
46
+ # @param entries [Array<Hash, String, Class>]
47
+ # @return [Array<Hash, Class<RubyLLM::MCP>>]
48
+ def resolve_entries(entries)
49
+ entries.filter_map do |entry|
50
+ klass = AIA::Utility.mcp_class_name?(entry) ? RobotLab::MCP.resolve(entry) : entry
51
+ next klass unless klass.is_a?(Class) && klass.respond_to?(:available?) && !klass.available?
29
52
 
30
- config.mcp_servers || []
53
+ note_skipped(AIA::Utility.server_name(klass), unavailable_reason(klass))
54
+ rescue RobotLab::MCPError => e
55
+ note_skipped(entry, e.message)
56
+ end
31
57
  end
32
58
 
33
- def apply_skip_filter(servers, config)
34
- skip_list = Array(config.mcp_skip)
35
- return servers if skip_list.empty?
59
+ private
36
60
 
37
- servers.reject { |s| skip_list.include?(AIA::Utility.server_name(s)) }
61
+ def unavailable_reason(klass)
62
+ missing = klass.respond_to?(:missing_envars) ? Array(klass.missing_envars) : []
63
+ missing.empty? ? "not available" : "missing #{missing.join(', ')}"
38
64
  end
39
65
 
40
- def select_by_names(all_servers, names)
41
- all_servers.select { |s| names.include?(AIA::Utility.server_name(s)) }
66
+ # Report a skipped server; returns nil so filter_map drops the entry.
67
+ def note_skipped(name, reason)
68
+ $stderr.puts "Info: MCP server '#{name}' skipped (#{reason})"
69
+ nil
42
70
  end
43
71
  end
44
72
  end
@@ -19,7 +19,8 @@ module AIA
19
19
  groups = Hash.new { |h, k| h[k] = [] }
20
20
 
21
21
  servers.each do |server|
22
- group_name = server[:group] || server["group"]
22
+ # Only a Hash config can carry a group; a RubyLLM::MCP class is independent.
23
+ group_name = server.is_a?(Hash) ? (server[:group] || server["group"]) : nil
23
24
  if group_name
24
25
  groups[group_name] << server
25
26
  else
@@ -0,0 +1,48 @@
1
+ # lib/aia/mcp_server_config.rb
2
+
3
+ module AIA
4
+ # Normalized view of one MCP server hash. Server configs arrive with
5
+ # symbol or string keys, and with connection fields either nested under
6
+ # :transport or at the top level; this object owns all of that fallback
7
+ # logic so callers never touch the raw hash shape.
8
+ McpServerConfig = Data.define(:name, :command, :args, :env, :timeout_raw, :url) do
9
+ def self.from_hash(server)
10
+ return from_class(server) unless server.is_a?(Hash)
11
+
12
+ transport = fetch_key(server, :transport) || {}
13
+ new(
14
+ name: AIA::Utility.server_name(server),
15
+ command: fetch_key(transport, :command) || fetch_key(server, :command),
16
+ args: Array(fetch_key(transport, :args) || fetch_key(server, :args)),
17
+ env: fetch_key(transport, :env) || fetch_key(server, :env) || {},
18
+ timeout_raw: fetch_key(server, :timeout),
19
+ url: fetch_key(transport, :url) || fetch_key(server, :url)
20
+ )
21
+ end
22
+
23
+ # A RubyLLM::MCP subclass describes itself through its class DSL. A
24
+ # constant name whose class is not loaded yet yields just its name.
25
+ def self.from_class(server)
26
+ klass = server.is_a?(Class) ? server : nil
27
+ argv = klass.respond_to?(:command) ? Array(klass.command) : []
28
+ new(
29
+ name: AIA::Utility.server_name(server),
30
+ command: argv.first,
31
+ args: argv.drop(1),
32
+ env: {},
33
+ timeout_raw: (klass.timeout if klass.respond_to?(:timeout)),
34
+ url: (klass.url if klass.respond_to?(:url))
35
+ )
36
+ end
37
+
38
+ # Read a hash entry by symbol or string key.
39
+ def self.fetch_key(hash, key) = hash[key] || hash[key.to_s]
40
+
41
+ # Timeout in milliseconds; raw values below 1000 are treated as seconds.
42
+ def timeout_ms(default: 8_000, cap: 30_000)
43
+ raw = (timeout_raw || default).to_i
44
+ ms = raw < 1000 ? raw * 1000 : raw
45
+ [ms, cap].min
46
+ end
47
+ end
48
+ end