aia 2.0.0.0.pre.beta2 → 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 (225) hide show
  1. checksums.yaml +4 -4
  2. data/.version +1 -1
  3. data/CHANGELOG.md +146 -228
  4. data/README.md +41 -18
  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 +16 -14
  10. data/lib/aia/config/cli_parser.rb +123 -91
  11. data/lib/aia/config/defaults.yml +12 -39
  12. data/lib/aia/config/mcp_parser.rb +30 -36
  13. data/lib/aia/config/model_spec.rb +8 -14
  14. data/lib/aia/config/validator.rb +102 -103
  15. data/lib/aia/config/value_caster.rb +76 -0
  16. data/lib/aia/config.rb +70 -53
  17. data/lib/aia/crew.rb +29 -19
  18. data/lib/aia/debate_handler.rb +27 -10
  19. data/lib/aia/directives/configuration_directives.rb +55 -14
  20. data/lib/aia/directives/context_directives.rb +24 -12
  21. data/lib/aia/directives/execution_directives.rb +18 -23
  22. data/lib/aia/directives/model_directives.rb +41 -104
  23. data/lib/aia/directives/utility_directives.rb +16 -17
  24. data/lib/aia/directives/web_and_file_directives.rb +21 -14
  25. data/lib/aia/fact_asserter.rb +3 -3
  26. data/lib/aia/history_transfer.rb +64 -24
  27. data/lib/aia/logger.rb +10 -45
  28. data/lib/aia/mcp_config_normalizer.rb +27 -14
  29. data/lib/aia/mcp_connection_manager.rb +181 -184
  30. data/lib/aia/mcp_discovery.rb +43 -15
  31. data/lib/aia/mcp_grouper.rb +2 -1
  32. data/lib/aia/mcp_server_config.rb +20 -2
  33. data/lib/aia/mcp_utility.rb +24 -19
  34. data/lib/aia/mention_router.rb +15 -2
  35. data/lib/aia/modality_query.rb +36 -0
  36. data/lib/aia/model_alias_registry.rb +11 -11
  37. data/lib/aia/model_registry.rb +75 -0
  38. data/lib/aia/network_builder.rb +8 -7
  39. data/lib/aia/patches/ruby_llm_streaming_error.rb +21 -4
  40. data/lib/aia/patches/ruby_llm_tool_param_compat.rb +18 -0
  41. data/lib/aia/pipeline_orchestrator.rb +71 -38
  42. data/lib/aia/prompt_decomposer.rb +1 -1
  43. data/lib/aia/prompt_handler.rb +56 -29
  44. data/lib/aia/provider_registry.rb +105 -0
  45. data/lib/aia/robot_builder.rb +1 -1
  46. data/lib/aia/robot_factory.rb +67 -63
  47. data/lib/aia/robot_sync.rb +79 -0
  48. data/lib/aia/role_catalog.rb +89 -0
  49. data/lib/aia/session.rb +25 -11
  50. data/lib/aia/skill_utils.rb +60 -19
  51. data/lib/aia/spawn_handler.rb +16 -4
  52. data/lib/aia/spawn_spec_parser.rb +6 -7
  53. data/lib/aia/special_mode_handler.rb +28 -25
  54. data/lib/aia/speech.rb +70 -34
  55. data/lib/aia/startup_coordinator.rb +17 -92
  56. data/lib/aia/streaming_runner.rb +10 -2
  57. data/lib/aia/system_prompt_assembler.rb +12 -11
  58. data/lib/aia/task_board.rb +60 -0
  59. data/lib/aia/tool_approver.rb +205 -0
  60. data/lib/aia/tool_filter.rb +1 -10
  61. data/lib/aia/tool_filter_strategy.rb +12 -1
  62. data/lib/aia/tool_introspection.rb +9 -1
  63. data/lib/aia/tool_loader.rb +67 -33
  64. data/lib/aia/tool_utility.rb +6 -5
  65. data/lib/aia/tools/delegate_to_foreman_tool.rb +6 -4
  66. data/lib/aia/tools/recruit_robot_tool.rb +12 -12
  67. data/lib/aia/tools/reskill_robot_tool.rb +7 -7
  68. data/lib/aia/tools/task_board_tool.rb +16 -16
  69. data/lib/aia/trakflow_bridge.rb +14 -8
  70. data/lib/aia/turn_state.rb +31 -8
  71. data/lib/aia/ui_presenter.rb +16 -0
  72. data/lib/aia/utility.rb +6 -24
  73. data/lib/aia/variable_input_collector.rb +0 -3
  74. data/lib/aia/verification_network.rb +9 -10
  75. data/lib/aia.rb +33 -8
  76. metadata +19 -160
  77. data/.better-commits.json +0 -150
  78. data/.config/tocer/configuration.yml +0 -6
  79. data/.envrc +0 -19
  80. data/.loki +0 -11
  81. data/.reek.yml +0 -160
  82. data/.rubocop.yml +0 -116
  83. data/.rubocop_strict.yml +0 -15
  84. data/COMMITS.md +0 -196
  85. data/IMPLEMENTATION_PLAN.md +0 -506
  86. data/Rakefile +0 -47
  87. data/_typos.toml +0 -10
  88. data/aia.gemspec +0 -92
  89. data/architecture_review.md +0 -314
  90. data/config/aia.yml +0 -13
  91. data/docs/AGENTS.md +0 -40
  92. data/docs/advanced-prompting.md +0 -814
  93. data/docs/assets/images/aia.png +0 -0
  94. data/docs/cli-reference.md +0 -1241
  95. data/docs/configuration.md +0 -747
  96. data/docs/contributing.md +0 -386
  97. data/docs/directives-reference.md +0 -1145
  98. data/docs/examples/index.md +0 -277
  99. data/docs/examples/mcp/index.md +0 -475
  100. data/docs/examples/prompts/analysis/index.md +0 -78
  101. data/docs/examples/prompts/automation/index.md +0 -109
  102. data/docs/examples/prompts/development/index.md +0 -125
  103. data/docs/examples/prompts/index.md +0 -333
  104. data/docs/examples/prompts/learning/index.md +0 -127
  105. data/docs/examples/prompts/writing/index.md +0 -62
  106. data/docs/examples/tools/index.md +0 -282
  107. data/docs/faq.md +0 -578
  108. data/docs/guides/available-models.md +0 -366
  109. data/docs/guides/basic-usage.md +0 -478
  110. data/docs/guides/chat.md +0 -680
  111. data/docs/guides/crew.md +0 -239
  112. data/docs/guides/executable-prompts.md +0 -331
  113. data/docs/guides/first-prompt.md +0 -454
  114. data/docs/guides/getting-started.md +0 -455
  115. data/docs/guides/image-generation.md +0 -507
  116. data/docs/guides/index.md +0 -48
  117. data/docs/guides/local-models.md +0 -306
  118. data/docs/guides/migrate-prompts.md +0 -335
  119. data/docs/guides/models.md +0 -1017
  120. data/docs/guides/shared-tools.md +0 -254
  121. data/docs/guides/tools.md +0 -831
  122. data/docs/index.md +0 -259
  123. data/docs/installation.md +0 -274
  124. data/docs/mcp-integration.md +0 -603
  125. data/docs/prompt_management.md +0 -665
  126. data/docs/security.md +0 -674
  127. data/docs/special_projects_guide.md +0 -386
  128. data/docs/tools-and-mcp-examples.md +0 -1211
  129. data/docs/workflows-and-pipelines.md +0 -636
  130. data/examples/.gitignore +0 -2
  131. data/examples/00_setup_aia.sh +0 -111
  132. data/examples/01_basic_usage.sh +0 -23
  133. data/examples/02_frontmatter.sh +0 -33
  134. data/examples/03_shell_integration.sh +0 -55
  135. data/examples/04_erb_templating.sh +0 -56
  136. data/examples/05_shell_then_erb.sh +0 -38
  137. data/examples/06_prompt_chaining.sh +0 -59
  138. data/examples/07_pipeline.sh +0 -46
  139. data/examples/08_context_files.sh +0 -43
  140. data/examples/09_roles.sh +0 -67
  141. data/examples/10_stdin_piping.sh +0 -49
  142. data/examples/11_multi_model.sh +0 -65
  143. data/examples/12_token_usage.sh +0 -52
  144. data/examples/13_cost_tracking.sh +0 -68
  145. data/examples/14_output_file.sh +0 -91
  146. data/examples/15_parameters.sh +0 -68
  147. data/examples/16_directives.sh +0 -113
  148. data/examples/17_require_and_conditionals.sh +0 -68
  149. data/examples/18_tools.sh +0 -61
  150. data/examples/19_local_tools.sh +0 -34
  151. data/examples/20_mcp_servers.sh +0 -102
  152. data/examples/21_executable_prompts.sh +0 -78
  153. data/examples/22_chat_mode.sh +0 -217
  154. data/examples/23_verify.sh +0 -139
  155. data/examples/24_decompose.sh +0 -139
  156. data/examples/25_spawn.sh +0 -139
  157. data/examples/26_debate.sh +0 -97
  158. data/examples/27_mention_routing.sh +0 -157
  159. data/examples/28_model_switching.sh +0 -106
  160. data/examples/29_agent_harness.sh +0 -177
  161. data/examples/README.md +0 -321
  162. data/examples/advanced_multi_robot_capabilities_without_examples.md +0 -106
  163. data/examples/aia_config.yml +0 -22
  164. data/examples/aia_config_orchestrator.yml +0 -45
  165. data/examples/aia_config_with_mcp.yml +0 -21
  166. data/examples/common.sh +0 -39
  167. data/examples/context/project_goals.md +0 -6
  168. data/examples/context/tech_stack.md +0 -7
  169. data/examples/directives/timestamp_directive.rb +0 -22
  170. data/examples/mcp/filesystem.json +0 -9
  171. data/examples/prompts_dir/analyze.md +0 -2
  172. data/examples/prompts_dir/brainstorm.md +0 -2
  173. data/examples/prompts_dir/conditional.md +0 -17
  174. data/examples/prompts_dir/creative.md +0 -4
  175. data/examples/prompts_dir/erbinfo.md +0 -5
  176. data/examples/prompts_dir/erbinfo_raw.md +0 -8
  177. data/examples/prompts_dir/evaluate.md +0 -2
  178. data/examples/prompts_dir/explain_joke.md +0 -1
  179. data/examples/prompts_dir/explain_recursion.md +0 -1
  180. data/examples/prompts_dir/fun_fact +0 -3
  181. data/examples/prompts_dir/greeting.md +0 -8
  182. data/examples/prompts_dir/greeting_required.md +0 -7
  183. data/examples/prompts_dir/hello.md +0 -1
  184. data/examples/prompts_dir/includes/ruby_facts.md +0 -4
  185. data/examples/prompts_dir/limerick.md +0 -1
  186. data/examples/prompts_dir/list_with_mcp.md +0 -3
  187. data/examples/prompts_dir/pick_best.md +0 -2
  188. data/examples/prompts_dir/project_summary +0 -12
  189. data/examples/prompts_dir/quiz_with_include.md +0 -6
  190. data/examples/prompts_dir/require_demo.md +0 -5
  191. data/examples/prompts_dir/roles/formal.md +0 -3
  192. data/examples/prompts_dir/roles/orchestrator.md +0 -21
  193. data/examples/prompts_dir/roles/pirate.md +0 -3
  194. data/examples/prompts_dir/shell_then_erb.md +0 -6
  195. data/examples/prompts_dir/sort_compare.md +0 -2
  196. data/examples/prompts_dir/summarize_context.md +0 -2
  197. data/examples/prompts_dir/sysinfo.md +0 -5
  198. data/examples/prompts_dir/sysinfo_raw.md +0 -8
  199. data/examples/prompts_dir/tagline.md +0 -1
  200. data/examples/prompts_dir/tell_joke.md +0 -1
  201. data/examples/prompts_dir/tell_joke_with_next.md +0 -4
  202. data/examples/prompts_dir/use_local_tool.md +0 -8
  203. data/examples/prompts_dir/use_tools.md +0 -8
  204. data/examples/prompts_dir/weather.md +0 -2
  205. data/examples/prompts_dir/whats_new.md +0 -2
  206. data/examples/prompts_dir/with_timestamp.md +0 -5
  207. data/examples/requirements/sinatra_taskflow_app.md +0 -139
  208. data/examples/rules/01_classify_ruby.rb +0 -16
  209. data/examples/rules/02_prefer_claude_for_code.rb +0 -19
  210. data/examples/rules/03_gate_prompt_length.rb +0 -19
  211. data/examples/rules/04_tool_selection.rb +0 -41
  212. data/examples/rules/README.md +0 -30
  213. data/examples/run_all.sh +0 -294
  214. data/examples/tools/word_count_tool.rb +0 -30
  215. data/lib/AGENTS.md +0 -57
  216. data/lib/aia/model_switch_handler.rb +0 -100
  217. data/mcp_servers/README.md +0 -110
  218. data/mcp_servers/apple-mcp.json +0 -8
  219. data/mcp_servers/filesystem.json +0 -9
  220. data/mcp_servers/mcp_server_chart.json +0 -11
  221. data/mcp_servers/playwright_one.json +0 -8
  222. data/mcp_servers/playwright_server_definition.json +0 -9
  223. data/mcp_servers/playwright_two.json +0 -8
  224. data/mcp_servers/tavily_mcp_server.json +0 -8
  225. data/mkdocs.yml +0 -169
@@ -3,32 +3,45 @@
3
3
  # lib/aia/mcp_config_normalizer.rb
4
4
  #
5
5
  # Normalizes a single MCP server config from AIA flat format to the nested
6
- # transport format expected by robot_lab. Server selection/filtering is
7
- # the responsibility of MCPDiscovery — this class only transforms shape.
6
+ # transport format expected by robot_lab (RobotLab::MCP.build). Server
7
+ # selection/filtering is the responsibility of MCPDiscovery — this class
8
+ # only transforms shape.
8
9
 
9
10
  module AIA
10
11
  class MCPConfigNormalizer
12
+ # Flat keys that describe how to reach the server; folded into :transport.
13
+ TRANSPORT_KEYS = %i[type command args env url headers bearer_token oauth cwd directory].freeze
14
+
11
15
  class << self
12
16
  # Normalize a single MCP server config to robot_lab's nested transport format.
17
+ # Settings robot_lab understands (timeout, prefix, only, except,
18
+ # requires_approval, description, ...) are carried through unchanged.
19
+ #
20
+ # A RubyLLM::MCP subclass or instance, or the constant name of one,
21
+ # already describes its own transport and is returned unchanged
22
+ # (RobotLab::MCP.build resolves the name).
13
23
  #
14
- # @param server [Hash]
15
- # @return [Hash]
24
+ # @param server [Hash, Class<RubyLLM::MCP>, RubyLLM::MCP, String]
25
+ # @return [Hash, Class<RubyLLM::MCP>, RubyLLM::MCP, String]
16
26
  def normalize(server)
17
- server = server.is_a?(Hash) ? server.transform_keys(&:to_sym) : server.to_h.transform_keys(&:to_sym)
27
+ return server if mcp_object?(server) || AIA::Utility.mcp_class_name?(server)
28
+
29
+ server = server.to_h.transform_keys(&:to_sym)
18
30
 
19
31
  # Already in robot_lab format — pass through
20
32
  return server if server[:transport]
21
33
 
22
- # Legacy flat format: wrap command/args/env into transport
23
- name = server[:name]
24
- transport = { type: server[:type] || 'stdio' }
25
- transport[:command] = server[:command] if server[:command]
26
- transport[:args] = Array(server[:args]) if server[:args]
27
- transport[:env] = server[:env] if server[:env]
34
+ transport = server.slice(*TRANSPORT_KEYS).compact
35
+ transport[:type] ||= server[:url] ? 'streamable-http' : 'stdio'
36
+ transport[:args] = Array(transport[:args]) if transport.key?(:args)
37
+
38
+ server.except(*TRANSPORT_KEYS).merge(transport: transport)
39
+ end
28
40
 
29
- result = { name: name, transport: transport }
30
- result[:timeout] = server[:timeout] if server[:timeout]
31
- result
41
+ # @param server [Object]
42
+ # @return [Boolean] true for a RubyLLM::MCP instance or subclass
43
+ def mcp_object?(server)
44
+ server.is_a?(RubyLLM::MCP) || (server.is_a?(Class) && server <= RubyLLM::MCP)
32
45
  end
33
46
  end
34
47
  end
@@ -2,73 +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
13
- # :reek:TooManyMethods -- one small helper per connection-lifecycle concern (connect, wrap tools, record outcomes)
19
+ # :reek:TooManyMethods -- one small helper per connection-lifecycle concern (connect, record outcomes, query, close)
14
20
  class MCPConnectionManager
15
21
  # Maximum seconds to wait for a single MCP server to connect.
16
22
  DEFAULT_TIMEOUT = 30
17
23
 
18
- 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
19
58
 
20
59
  def initialize
21
- @connected_clients = {}
22
- @connected_tools = []
23
- @failed_servers = []
24
- @server_tool_counts = {}
25
- @connected = false
26
- @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
27
65
  end
28
66
 
29
67
  # Connect all configured MCP servers concurrently.
30
68
  # Each server gets its own spinner line and thread.
31
69
  #
32
- # @param servers [Array<Hash>] MCP server configurations
70
+ # @param configs [Array<Hash>] MCP server configurations
33
71
  # @return [self]
34
72
  # :reek:TooManyStatements -- connection ceremony: spinner setup, thread launch, global timeout guard, summary logging
35
- def connect_all(servers)
36
- return self unless servers.is_a?(Array) && servers.any?
73
+ def connect_all(configs)
74
+ return self unless configs.is_a?(Array) && configs.any?
37
75
 
38
76
  reset_connection_state
39
- logger = AIA::LoggerManager.mcp_logger
40
- server_names = servers.map { |s| s.is_a?(Hash) ? s[:name] : s.to_s }.compact
41
- 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(', ')}")
42
78
 
43
- multi = TTY::Spinner::Multi.new("[:spinner] Connecting MCP servers", format: :dots, output: $stderr)
44
- 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)
45
81
 
46
82
  # The global cap must never be smaller than the slowest single server's
47
83
  # timeout, or concurrent connections get killed before they can finish.
48
- global_limit = [global_connection_timeout, *servers.map { |s| server_timeout(s) }].max
84
+ global_limit = [global_connection_timeout, *configs.map { server_timeout(it) }].max
49
85
  Timeout.timeout(global_limit) { threads.each(&:join) }
50
86
 
51
87
  @connected = true
52
- 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")
53
89
  self
54
90
  rescue Timeout::Error
55
- handle_global_timeout(servers, global_limit)
91
+ handle_global_timeout(configs, global_limit)
56
92
  end
57
93
 
58
- # Inject connected MCP clients and tools into robot(s).
94
+ # The connected servers, in connection order.
59
95
  #
60
- # @param robot [RobotLab::Robot, RobotLab::Network] the robot or network
61
- # @return [self]
62
- def inject_into(robot)
63
- 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
64
100
 
65
- 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
66
109
 
67
- targets.each do |target|
68
- target.inject_mcp!(clients: clients, tools: tools)
69
- 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
70
117
 
71
- 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) }
72
130
  end
73
131
 
74
132
  # Update AIA config with connection results.
@@ -76,7 +134,7 @@ module AIA
76
134
  # @return [self]
77
135
  def update_config
78
136
  connected_keys, tool_counts, failed = @mutex.synchronize do
79
- [@connected_clients.keys.dup, @server_tool_counts.dup, @failed_servers.dup]
137
+ [@servers.keys, @server_tools.transform_values(&:size), @failed_servers.dup]
80
138
  end
81
139
  cfg = AIA.config
82
140
  cfg.connected_mcp_servers = connected_keys
@@ -85,222 +143,161 @@ module AIA
85
143
  self
86
144
  end
87
145
 
88
- # Whether connect_all has been called.
146
+ # Whether connect_all has run to completion (or hit the global timeout).
89
147
  def connected?
90
148
  @connected
91
149
  end
92
150
 
93
- # Whether any tools were collected (from config servers or Ruby require).
151
+ # Whether any MCP tools were collected.
94
152
  def any_tools?
95
- @mutex.synchronize { @connected_tools.any? }
96
- end
97
-
98
- # Absorb MCP clients registered in RubyLLM::MCP (e.g., via --require loading
99
- # shared_tools/mcp/* files) that are not already tracked by this manager.
100
- # Starts any unstarted clients, extracts their tools, and merges them into
101
- # the connected state so inject_into will include them in the robot.
102
- #
103
- # @return [self]
104
- # :reek:TooManyStatements -- per-client absorb loop: start if needed, extract tools, merge into connected state with error capture
105
- def absorb_ruby_llm_mcp_clients
106
- return self unless defined?(RubyLLM::MCP)
107
-
108
- logger = AIA::LoggerManager.mcp_logger
109
-
110
- RubyLLM::MCP.clients.each do |name, client|
111
- next if @connected_clients.key?(name)
112
-
113
- begin
114
- client.start unless client.alive?
115
-
116
- if client.alive?
117
- tools = client.tools rescue []
118
- @mutex.synchronize do
119
- @connected_clients[name] = client
120
- @server_tool_counts[name] = tools.size
121
- @connected_tools.concat(tools)
122
- end
123
- logger.info("MCP: absorbed RubyLLM::MCP client '#{name}' (#{tools.size} tools)")
124
- else
125
- logger.warn("MCP: RubyLLM::MCP client '#{name}' not alive, skipping")
126
- end
127
- rescue StandardError => e
128
- logger.warn("MCP: error absorbing RubyLLM::MCP client '#{name}': #{e.message}")
129
- end
130
- end
131
-
132
- @connected = true unless RubyLLM::MCP.clients.empty?
133
- self
134
- end
135
-
136
- # Find an MCP client by server name.
137
- #
138
- # @param name [String] server name
139
- # @return [RobotLab::MCP::Client, nil]
140
- def client(name)
141
- @connected_clients[name]
153
+ @mutex.synchronize { @server_tools.values.any?(&:any?) }
142
154
  end
143
155
 
144
156
  # Connected server names.
145
157
  #
146
158
  # @return [Array<String>]
147
159
  def connected_server_names
148
- @mutex.synchronize { @connected_clients.keys.dup }
160
+ @mutex.synchronize { @servers.keys }
149
161
  end
150
162
 
151
163
  # Failed server names.
152
164
  #
153
165
  # @return [Array<String>]
154
166
  def failed_server_names
155
- @mutex.synchronize { @failed_servers.map { |f| f[:name] } }
167
+ @mutex.synchronize { @failed_servers.map { it[:name] } }
156
168
  end
157
169
 
158
- # Close all connected MCP clients and reset connection state.
159
- # Errors from individual client closes are silently rescued —
160
- # best-effort cleanup on process exit.
170
+ # Close all connected servers (stopping stdio processes) and reset state.
161
171
  def close_all
162
- clients = @mutex.synchronize { @connected_clients.dup }
163
- clients.each_value do |client|
164
- client.close
165
- rescue StandardError
166
- # best-effort — client may already be closed
167
- end
172
+ servers.each { close_quietly(it) }
168
173
  @mutex.synchronize do
169
- @connected_clients = {}
170
- @connected_tools = []
171
- @server_tool_counts = {}
172
- @connected = false
174
+ @servers = {}
175
+ @server_tools = {}
176
+ @connected = false
173
177
  end
174
178
  end
175
179
 
176
180
  private
177
181
 
178
182
  def reset_connection_state
179
- @connected_clients = {}
180
- @connected_tools = []
181
- @failed_servers = []
183
+ @servers = {}
184
+ @server_tools = {}
185
+ @failed_servers = []
182
186
  end
183
187
 
184
- def launch_server_threads(servers, multi, logger)
185
- servers.map do |server_config|
186
- name = server_config.is_a?(Hash) ? (server_config[:name] || server_config['name']) : server_config.to_s
187
- spinner = multi.register("[:spinner] #{name}")
188
- Thread.new(server_config, name, spinner) { |cfg, srv_name, sp| connect_one(cfg, srv_name, sp, logger) }
189
- end
188
+ def config_name(spec)
189
+ AIA::Utility.server_name(spec).to_s
190
190
  end
191
191
 
192
- def handle_global_timeout(servers, global_limit)
193
- logger = AIA::LoggerManager.mcp_logger
194
- logger.warn("MCP: Global connection timeout (#{global_limit}s) reached")
192
+ # The shared MCP log (memoized by LoggerManager, safe across the connect threads).
193
+ def logger
194
+ AIA::LoggerManager.mcp_logger
195
+ end
195
196
 
196
- connected_names, failed_names = @mutex.synchronize do
197
- [@connected_clients.keys.to_set, @failed_servers.to_set { |f| f[:name] }]
197
+ def launch_server_threads(configs, multi)
198
+ configs.map do |server_config|
199
+ name = config_name(server_config)
200
+ spinner = multi.register("[:spinner] #{name}")
201
+ Thread.new(server_config, name, spinner) { |cfg, srv_name, sp| connect_one(cfg, srv_name, sp) }
198
202
  end
203
+ end
199
204
 
200
- stragglers = servers.filter_map do |server_config|
201
- srv_name = server_config.is_a?(Hash) ? (server_config[:name] || server_config['name']) : server_config.to_s
202
- next if connected_names.include?(srv_name) || failed_names.include?(srv_name)
205
+ def handle_global_timeout(configs, global_limit)
206
+ logger.warn("MCP: Global connection timeout (#{global_limit}s) reached")
203
207
 
204
- { 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
205
213
  end
206
- @mutex.synchronize { @failed_servers.concat(stragglers) }
214
+ self
207
215
  end
208
216
 
209
217
  # Read global MCP connection timeout from config.
210
218
  # Falls back to 120s if config is unavailable.
211
219
  def global_connection_timeout
212
- 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 }
213
221
  rescue StandardError
214
222
  120
215
223
  end
216
224
 
217
- # Connect a single MCP server, updating the spinner on completion.
218
- # :reek:TooManyStatements -- one connect attempt with per-outcome reporting (success, refused, timeout, error)
219
- 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)
220
229
  timeout = server_timeout(server_config)
221
230
  spinner.auto_spin
222
-
223
231
  logger.info("MCP: connecting to '#{name}'...")
224
- Timeout.timeout(timeout) do
225
- client = RobotLab::MCP::Client.new(server_config)
226
- client.connect
227
-
228
- if client.connected?
229
- record_connected(name, client, build_mcp_tools(client, name), spinner, logger)
230
- else
231
- record_failed_server(name, "connection failed")
232
- logger.warn("MCP: '#{name}' failed to connect")
233
- spinner.error("(connection failed)")
234
- end
235
- end
232
+
233
+ server = RobotLab::MCP.build(MCPConfigNormalizer.normalize(server_config))
234
+ tools = Timeout.timeout(timeout) { server.tools }
235
+ record_connected(name, server, tools, spinner)
236
236
  rescue Timeout::Error
237
- record_failed_server(name, "timed out after #{timeout}s")
238
- logger.warn("MCP: '#{name}' timed out after #{timeout}s")
239
- spinner.error("(timed out)")
237
+ close_quietly(server)
238
+ report_failure(name, "timed out after #{timeout}s", "(timed out)", spinner)
240
239
  rescue StandardError => e
241
- msg = e.message
242
- record_failed_server(name, msg)
243
- logger.warn("MCP: '#{name}' error: #{msg}")
244
- spinner.error("(#{msg})")
240
+ close_quietly(server)
241
+ report_failure(name, e.message, "(#{e.message})", spinner)
245
242
  end
246
243
 
247
- # Wrap each remote tool definition in a RobotLab::Tool proxying to the client.
248
- def build_mcp_tools(client, server_name)
249
- client.list_tools.map do |tool_def|
250
- tool_name = tool_def[:name]
251
- RobotLab::Tool.create(
252
- name: tool_name,
253
- description: tool_def[:description],
254
- parameters: tool_def[:inputSchema],
255
- mcp: server_name
256
- ) { |args| client.call_tool(tool_name, args) }
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
253
+ end
254
+ found
257
255
  end
258
- end
256
+ return report_clash(name, server, clash, spinner) if clash
259
257
 
260
- def record_connected(name, client, tools, spinner, logger)
261
- tool_count = tools.size
258
+ logger.info("MCP: '#{name}' connected (#{tools.size} tools)")
259
+ spinner.success("(#{tools.size} tools)")
260
+ end
262
261
 
263
- @mutex.synchronize do
264
- @connected_clients[name] = client
265
- @server_tool_counts[name] = tool_count
266
- add_tools_deduped(tools, name, logger)
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
267
269
  end
270
+ nil
271
+ end
268
272
 
269
- logger.info("MCP: '#{name}' connected (#{tool_count} tools)")
270
- spinner.success("(#{tool_count} tools)")
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)
271
278
  end
272
279
 
273
- def record_failed_server(name, error)
280
+ def report_failure(name, error, spinner_note, spinner)
274
281
  @mutex.synchronize { @failed_servers << { name: name, error: error } }
282
+ logger.warn("MCP: '#{name}' error: #{error}")
283
+ spinner.error(spinner_note)
275
284
  end
276
285
 
277
- # Add tools to @connected_tools, skipping any whose name is already present.
278
- # Logs a warning for each duplicate so the user knows which server wins.
279
- # MUST be called inside @mutex.synchronize.
280
- #
281
- # @param new_tools [Array] tools to add
282
- # @param server_name [String] name of the server providing these tools (for warning)
283
- # @param logger [Logger] MCP logger
284
- def add_tools_deduped(new_tools, server_name, logger)
285
- new_tools.each do |tool|
286
- tool_name = tool.respond_to?(:name) ? tool.name : tool.to_s
287
- existing = @connected_tools.find do |t|
288
- (t.respond_to?(:name) ? t.name : t.to_s) == tool_name
289
- end
290
-
291
- if existing
292
- logger.warn("MCP: Tool '#{tool_name}' already registered from another server. " \
293
- "Skipping duplicate from '#{server_name}'.")
294
- else
295
- @connected_tools << tool
296
- end
297
- end
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
298
291
  end
299
292
 
300
- # Extract timeout in seconds from server config.
301
- # Config values >= 1000 are treated as milliseconds.
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.
302
296
  def server_timeout(server_config)
303
- 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
304
301
  return DEFAULT_TIMEOUT if raw.nil?
305
302
 
306
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