legion-mcp 0.8.1 → 0.9.2
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.
- checksums.yaml +4 -4
- data/.github/dependabot.yml +0 -4
- data/.github/workflows/ci.yml +6 -2
- data/.gitignore +1 -0
- data/CHANGELOG.md +59 -0
- data/CLAUDE.md +34 -42
- data/Gemfile +4 -0
- data/README.md +181 -49
- data/legion-mcp.gemspec +3 -2
- data/lib/legion/mcp/actors/self_generate_cycle.rb +3 -5
- data/lib/legion/mcp/audit.rb +50 -0
- data/lib/legion/mcp/auth.rb +70 -11
- data/lib/legion/mcp/catalog_dispatcher.rb +29 -50
- data/lib/legion/mcp/client/connection.rb +163 -59
- data/lib/legion/mcp/client/pool.rb +40 -5
- data/lib/legion/mcp/client/server_registry.rb +7 -0
- data/lib/legion/mcp/client.rb +4 -1
- data/lib/legion/mcp/cold_start.rb +7 -9
- data/lib/legion/mcp/context_compiler.rb +6 -1
- data/lib/legion/mcp/context_guard.rb +1 -3
- data/lib/legion/mcp/deferred_registry.rb +20 -16
- data/lib/legion/mcp/discovery.rb +18 -0
- data/lib/legion/mcp/dynamic_injector.rb +4 -1
- data/lib/legion/mcp/embedding_index.rb +5 -3
- data/lib/legion/mcp/function_discovery.rb +46 -6
- data/lib/legion/mcp/gap_detector.rb +8 -3
- data/lib/legion/mcp/observer.rb +11 -9
- data/lib/legion/mcp/override_broadcast.rb +4 -3
- data/lib/legion/mcp/patterns/compiler.rb +59 -0
- data/lib/legion/mcp/patterns/exchange.rb +63 -0
- data/lib/legion/mcp/patterns/gossip.rb +68 -0
- data/lib/legion/mcp/patterns/schema.rb +92 -0
- data/lib/legion/mcp/patterns/store.rb +469 -0
- data/lib/legion/mcp/patterns.rb +25 -0
- data/lib/legion/mcp/resources/extension_info.rb +1 -3
- data/lib/legion/mcp/resources/runner_catalog.rb +24 -3
- data/lib/legion/mcp/self_generate.rb +6 -9
- data/lib/legion/mcp/server.rb +186 -86
- data/lib/legion/mcp/settings.rb +17 -8
- data/lib/legion/mcp/state_tracker.rb +4 -4
- data/lib/legion/mcp/structural_index.rb +6 -4
- data/lib/legion/mcp/tier_router.rb +55 -95
- data/lib/legion/mcp/tool_adapter.rb +101 -1
- data/lib/legion/mcp/tool_governance.rb +76 -5
- data/lib/legion/mcp/tool_quality.rb +3 -0
- data/lib/legion/mcp/tools/create_chain.rb +1 -3
- data/lib/legion/mcp/tools/create_relationship.rb +1 -3
- data/lib/legion/mcp/tools/create_schedule.rb +0 -2
- data/lib/legion/mcp/tools/delete_chain.rb +1 -3
- data/lib/legion/mcp/tools/delete_relationship.rb +1 -3
- data/lib/legion/mcp/tools/delete_schedule.rb +0 -2
- data/lib/legion/mcp/tools/delete_task.rb +0 -2
- data/lib/legion/mcp/tools/describe_runner.rb +0 -2
- data/lib/legion/mcp/tools/discover_tools.rb +2 -2
- data/lib/legion/mcp/tools/do_action.rb +102 -116
- data/lib/legion/mcp/tools/get_task.rb +0 -2
- data/lib/legion/mcp/tools/get_task_logs.rb +0 -2
- data/lib/legion/mcp/tools/list_chains.rb +1 -3
- data/lib/legion/mcp/tools/list_relationships.rb +0 -2
- data/lib/legion/mcp/tools/list_schedules.rb +0 -2
- data/lib/legion/mcp/tools/list_tasks.rb +0 -2
- data/lib/legion/mcp/tools/plan_action.rb +0 -2
- data/lib/legion/mcp/tools/run_task.rb +0 -2
- data/lib/legion/mcp/tools/search_sessions.rb +1 -2
- data/lib/legion/mcp/tools/skills.rb +2 -4
- data/lib/legion/mcp/tools/state_diff.rb +0 -1
- data/lib/legion/mcp/tools/structural_index.rb +0 -1
- data/lib/legion/mcp/tools/tool_audit.rb +0 -1
- data/lib/legion/mcp/tools/update_chain.rb +1 -3
- data/lib/legion/mcp/tools/update_relationship.rb +1 -3
- data/lib/legion/mcp/tools/update_schedule.rb +0 -2
- data/lib/legion/mcp/tools_loader.rb +13 -50
- data/lib/legion/mcp/tracing_context.rb +58 -0
- data/lib/legion/mcp/transport/exchanges/audit.rb +15 -0
- data/lib/legion/mcp/transport/messages/client_call_event.rb +23 -0
- data/lib/legion/mcp/transport/messages/governance_event.rb +23 -0
- data/lib/legion/mcp/transport/messages/tool_call_event.rb +23 -0
- data/lib/legion/mcp/usage_filter.rb +6 -1
- data/lib/legion/mcp/{logging_support.rb → utils.rb} +3 -29
- data/lib/legion/mcp/version.rb +1 -1
- data/lib/legion/mcp.rb +27 -5
- metadata +33 -50
- data/lib/legion/mcp/pattern_compiler.rb +0 -55
- data/lib/legion/mcp/pattern_exchange.rb +0 -61
- data/lib/legion/mcp/pattern_gossip.rb +0 -68
- data/lib/legion/mcp/pattern_schema.rb +0 -80
- data/lib/legion/mcp/pattern_store.rb +0 -492
- data/lib/legion/mcp/tools/absorb.rb +0 -64
- data/lib/legion/mcp/tools/ask_peer.rb +0 -61
- data/lib/legion/mcp/tools/broadcast_peers.rb +0 -60
- data/lib/legion/mcp/tools/dataset_list.rb +0 -55
- data/lib/legion/mcp/tools/dataset_show.rb +0 -61
- data/lib/legion/mcp/tools/disable_extension.rb +0 -57
- data/lib/legion/mcp/tools/enable_extension.rb +0 -57
- data/lib/legion/mcp/tools/eval_list.rb +0 -55
- data/lib/legion/mcp/tools/eval_results.rb +0 -86
- data/lib/legion/mcp/tools/eval_run.rb +0 -64
- data/lib/legion/mcp/tools/experiment_results.rb +0 -86
- data/lib/legion/mcp/tools/get_config.rb +0 -68
- data/lib/legion/mcp/tools/get_extension.rb +0 -63
- data/lib/legion/mcp/tools/get_status.rb +0 -61
- data/lib/legion/mcp/tools/knowledge_context.rb +0 -108
- data/lib/legion/mcp/tools/knowledge_health.rb +0 -62
- data/lib/legion/mcp/tools/list_extensions.rb +0 -53
- data/lib/legion/mcp/tools/list_peers.rb +0 -52
- data/lib/legion/mcp/tools/list_workers.rb +0 -61
- data/lib/legion/mcp/tools/mesh_status.rb +0 -48
- data/lib/legion/mcp/tools/mind_growth_approve.rb +0 -53
- data/lib/legion/mcp/tools/mind_growth_build_queue.rb +0 -48
- data/lib/legion/mcp/tools/mind_growth_cognitive_profile.rb +0 -48
- data/lib/legion/mcp/tools/mind_growth_health.rb +0 -48
- data/lib/legion/mcp/tools/mind_growth_propose.rb +0 -60
- data/lib/legion/mcp/tools/mind_growth_status.rb +0 -48
- data/lib/legion/mcp/tools/notify_peer.rb +0 -59
- data/lib/legion/mcp/tools/prompt_list.rb +0 -55
- data/lib/legion/mcp/tools/prompt_run.rb +0 -66
- data/lib/legion/mcp/tools/prompt_show.rb +0 -62
- data/lib/legion/mcp/tools/query_knowledge.rb +0 -56
- data/lib/legion/mcp/tools/rbac_assignments.rb +0 -50
- data/lib/legion/mcp/tools/rbac_check.rb +0 -51
- data/lib/legion/mcp/tools/rbac_grants.rb +0 -46
- data/lib/legion/mcp/tools/routing_stats.rb +0 -58
- data/lib/legion/mcp/tools/show_worker.rb +0 -55
- data/lib/legion/mcp/tools/team_summary.rb +0 -62
- data/lib/legion/mcp/tools/worker_costs.rb +0 -62
- data/lib/legion/mcp/tools/worker_lifecycle.rb +0 -63
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Legion
|
|
4
|
+
module MCP
|
|
5
|
+
module Audit
|
|
6
|
+
extend Legion::Logging::Helper
|
|
7
|
+
|
|
8
|
+
ROUTING_KEYS = {
|
|
9
|
+
tool_call: 'mcp.audit.tool_call',
|
|
10
|
+
client_call: 'mcp.audit.client_call',
|
|
11
|
+
governance: 'mcp.audit.governance'
|
|
12
|
+
}.freeze
|
|
13
|
+
|
|
14
|
+
module_function
|
|
15
|
+
|
|
16
|
+
def emit_tool_call(**event)
|
|
17
|
+
publish(ROUTING_KEYS[:tool_call], event, :ToolCallEvent)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def emit_client_call(**event)
|
|
21
|
+
publish(ROUTING_KEYS[:client_call], event, :ClientCallEvent)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def emit_governance(**event)
|
|
25
|
+
publish(ROUTING_KEYS[:governance], event, :GovernanceEvent)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def transport_available?
|
|
29
|
+
!!(defined?(Legion::Transport::Message) &&
|
|
30
|
+
defined?(Legion::MCP::Transport::Exchanges::Audit))
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def transport_connected?
|
|
34
|
+
Legion::Settings.dig(:transport, :connected) == true
|
|
35
|
+
rescue StandardError => e
|
|
36
|
+
handle_exception(e, level: :debug, handled: true, operation: 'mcp.audit.transport_connected?')
|
|
37
|
+
false
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def publish(routing_key, event, message_sym)
|
|
41
|
+
return unless transport_available? && transport_connected?
|
|
42
|
+
|
|
43
|
+
message_class = Legion::MCP::Transport::Messages.const_get(message_sym)
|
|
44
|
+
message_class.new(routing_key: routing_key, **event).publish
|
|
45
|
+
rescue StandardError => e
|
|
46
|
+
handle_exception(e, level: :warn, handled: true, operation: 'mcp.audit.publish')
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
data/lib/legion/mcp/auth.rb
CHANGED
|
@@ -8,14 +8,21 @@ module Legion
|
|
|
8
8
|
module_function
|
|
9
9
|
|
|
10
10
|
def authenticate(token)
|
|
11
|
-
|
|
11
|
+
token_type = if token
|
|
12
|
+
jwt_token?(token) ? :jwt : :api_key
|
|
13
|
+
else
|
|
14
|
+
:none
|
|
15
|
+
end
|
|
16
|
+
log.debug("[mcp][auth] action=authenticate token_type=#{token_type}")
|
|
12
17
|
return { authenticated: false, error: 'missing_token' } unless token
|
|
13
18
|
|
|
14
|
-
if jwt_token?(token)
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
+
result = if jwt_token?(token)
|
|
20
|
+
verify_jwt(token)
|
|
21
|
+
else
|
|
22
|
+
verify_api_key(token)
|
|
23
|
+
end
|
|
24
|
+
log.debug("[mcp][auth] action=authenticate.complete authenticated=#{result[:authenticated]}")
|
|
25
|
+
result
|
|
19
26
|
end
|
|
20
27
|
|
|
21
28
|
def auth_enabled?
|
|
@@ -26,30 +33,82 @@ module Legion
|
|
|
26
33
|
Legion::Settings.dig(:mcp, :auth, :require_auth) == true
|
|
27
34
|
end
|
|
28
35
|
|
|
36
|
+
def default_identity
|
|
37
|
+
{ user_id: 'anonymous', risk_tier: :low }
|
|
38
|
+
end
|
|
39
|
+
|
|
29
40
|
def jwt_token?(token)
|
|
30
41
|
token.count('.') == 2
|
|
31
42
|
end
|
|
32
43
|
|
|
33
44
|
def verify_jwt(token)
|
|
45
|
+
log.debug("[mcp][auth] action=verify_jwt crypt_available=#{defined?(Legion::Crypt::JWT) ? true : false}")
|
|
34
46
|
return { authenticated: false, error: 'crypt_unavailable' } unless defined?(Legion::Crypt::JWT)
|
|
35
47
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
48
|
+
verification_key = jwt_verification_key
|
|
49
|
+
|
|
50
|
+
unless verification_key
|
|
51
|
+
log.warn('No JWT verification key available; rejecting token')
|
|
52
|
+
return { authenticated: false, error: 'jwt_verification_key_unavailable' }
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
claims = Legion::Crypt::JWT.verify(
|
|
56
|
+
token,
|
|
57
|
+
verification_key: verification_key,
|
|
58
|
+
algorithm: jwt_algorithm,
|
|
59
|
+
issuer: jwt_issuer,
|
|
60
|
+
verify_expiration: true,
|
|
61
|
+
verify_issuer: true
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
{ authenticated: true, identity: identity_from_claims(claims) }
|
|
39
65
|
rescue StandardError => e
|
|
40
66
|
handle_exception(e, level: :warn, operation: 'legion.mcp.auth.verify_jwt')
|
|
41
|
-
log.warn("Auth#verify_jwt failed: #{e.message}")
|
|
42
67
|
{ authenticated: false, error: e.message }
|
|
43
68
|
end
|
|
44
69
|
|
|
45
70
|
def verify_api_key(token)
|
|
46
71
|
allowed = Legion::Settings.dig(:mcp, :auth, :allowed_api_keys) || []
|
|
47
|
-
|
|
72
|
+
matched = allowed.include?(token)
|
|
73
|
+
log.debug("[mcp][auth] action=verify_api_key allowed_keys=#{allowed.size} matched=#{matched}")
|
|
74
|
+
if matched
|
|
48
75
|
{ authenticated: true, identity: { user_id: 'api_key', risk_tier: :low } }
|
|
49
76
|
else
|
|
50
77
|
{ authenticated: false, error: 'invalid_api_key' }
|
|
51
78
|
end
|
|
52
79
|
end
|
|
80
|
+
|
|
81
|
+
def jwt_verification_key
|
|
82
|
+
configured = Legion::Settings.dig(:mcp, :auth, :jwt_secret)
|
|
83
|
+
return configured if configured
|
|
84
|
+
|
|
85
|
+
return Legion::Crypt::ClusterSecret.cs if defined?(Legion::Crypt::ClusterSecret) && Legion::Crypt::ClusterSecret.respond_to?(:cs)
|
|
86
|
+
|
|
87
|
+
nil
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def jwt_algorithm
|
|
91
|
+
Legion::Settings.dig(:mcp, :auth, :jwt_algorithm) || 'HS256'
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def jwt_issuer
|
|
95
|
+
Legion::Settings.dig(:mcp, :auth, :jwt_issuer) || 'legion'
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def validate_claims!(claims)
|
|
99
|
+
raise 'token missing required sub claim' unless claims[:sub]
|
|
100
|
+
|
|
101
|
+
return unless claims[:exp]
|
|
102
|
+
|
|
103
|
+
raise 'token has expired' if claims[:exp].to_i <= Time.now.to_i
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
def identity_from_claims(claims)
|
|
107
|
+
identity = { user_id: claims[:sub], risk_tier: claims[:risk_tier]&.to_sym,
|
|
108
|
+
tenant_id: claims[:tenant_id], worker_id: claims[:worker_id] }
|
|
109
|
+
log.debug("[mcp][auth] action=identity_from_claims user_id=#{identity[:user_id]} risk_tier=#{identity[:risk_tier]}")
|
|
110
|
+
identity
|
|
111
|
+
end
|
|
53
112
|
end
|
|
54
113
|
end
|
|
55
114
|
end
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require_relative '
|
|
3
|
+
require_relative 'utils'
|
|
4
4
|
require_relative 'tool_adapter'
|
|
5
5
|
|
|
6
6
|
module Legion
|
|
@@ -10,21 +10,18 @@ module Legion
|
|
|
10
10
|
|
|
11
11
|
module_function
|
|
12
12
|
|
|
13
|
-
def
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
13
|
+
def mcp_log(level, event, **fields)
|
|
14
|
+
log.public_send(level, "[mcp] #{event} #{Utils.format_fields(fields)}")
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def dispatch(runner_class:, function:, params:, source: :mcp)
|
|
18
|
+
mcp_log :info, 'catalog.dispatch.start',
|
|
19
|
+
runner_class: runner_class, function: function, source: source,
|
|
20
|
+
params: Utils.summarize_params(params)
|
|
21
21
|
unless defined?(Legion::Ingress)
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
function: function,
|
|
26
|
-
reason: 'ingress unavailable'
|
|
27
|
-
)
|
|
22
|
+
mcp_log :warn, 'catalog.dispatch.skipped',
|
|
23
|
+
runner_class: runner_class, function: function,
|
|
24
|
+
reason: 'ingress unavailable'
|
|
28
25
|
return nil
|
|
29
26
|
end
|
|
30
27
|
|
|
@@ -36,13 +33,9 @@ module Legion
|
|
|
36
33
|
check_subtask: true,
|
|
37
34
|
generate_task: true
|
|
38
35
|
)
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
function: function,
|
|
43
|
-
source: source,
|
|
44
|
-
result: LoggingSupport.summarize_result(result)
|
|
45
|
-
)
|
|
36
|
+
mcp_log :info, 'catalog.dispatch.complete',
|
|
37
|
+
runner_class: runner_class, function: function, source: source,
|
|
38
|
+
result: Utils.summarize_result(result)
|
|
46
39
|
result
|
|
47
40
|
end
|
|
48
41
|
|
|
@@ -69,15 +62,12 @@ module Legion
|
|
|
69
62
|
klass
|
|
70
63
|
end
|
|
71
64
|
|
|
72
|
-
def wire_dispatch(klass, runner_class_str, function_name, tool_name_val)
|
|
73
|
-
klass.define_singleton_method(:call) do |**params|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
function: function_name,
|
|
79
|
-
params: LoggingSupport.summarize_params(params)
|
|
80
|
-
)
|
|
65
|
+
def wire_dispatch(klass, runner_class_str, function_name, tool_name_val)
|
|
66
|
+
klass.define_singleton_method(:call) do |**params|
|
|
67
|
+
log.info("[mcp] catalog.tool_call.start #{Utils.format_fields(
|
|
68
|
+
tool_name: tool_name_val, runner_class: runner_class_str,
|
|
69
|
+
function: function_name, params: Utils.summarize_params(params)
|
|
70
|
+
)}")
|
|
81
71
|
result = CatalogDispatcher.dispatch(
|
|
82
72
|
runner_class: runner_class_str,
|
|
83
73
|
function: function_name,
|
|
@@ -88,37 +78,26 @@ module Legion
|
|
|
88
78
|
text = Legion::JSON.dump({ error: 'Ingress not available' })
|
|
89
79
|
::MCP::Tool::Response.new([{ type: 'text', text: text }], error: true)
|
|
90
80
|
else
|
|
91
|
-
text =
|
|
81
|
+
text = Legion::JSON.dump(result)
|
|
92
82
|
response = ::MCP::Tool::Response.new([{ type: 'text', text: text }])
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
function: function_name,
|
|
98
|
-
result: LoggingSupport.summarize_result(response)
|
|
99
|
-
)
|
|
83
|
+
log.info("[mcp] catalog.tool_call.complete #{Utils.format_fields(
|
|
84
|
+
tool_name: tool_name_val, runner_class: runner_class_str,
|
|
85
|
+
function: function_name, result: Utils.summarize_result(response)
|
|
86
|
+
)}")
|
|
100
87
|
response
|
|
101
88
|
end
|
|
102
89
|
rescue StandardError => e
|
|
103
90
|
handle_exception(e, level: :warn, operation: 'legion.mcp.catalog_dispatcher.call')
|
|
104
|
-
LoggingSupport.warn(
|
|
105
|
-
'catalog.tool_call.failed',
|
|
106
|
-
tool_name: tool_name_val,
|
|
107
|
-
runner_class: runner_class_str,
|
|
108
|
-
function: function_name,
|
|
109
|
-
error: e.message
|
|
110
|
-
)
|
|
111
91
|
text = Legion::JSON.dump({ error: e.message })
|
|
112
92
|
::MCP::Tool::Response.new([{ type: 'text', text: text }], error: true)
|
|
113
93
|
end
|
|
114
94
|
end
|
|
115
95
|
|
|
116
96
|
def generate_tools_from_catalog
|
|
117
|
-
return [] unless
|
|
118
|
-
return [] unless Legion::Tools::Registry.respond_to?(:all_tools)
|
|
97
|
+
return [] unless Legion::Settings::Extensions.respond_to?(:tools)
|
|
119
98
|
|
|
120
|
-
Legion::
|
|
121
|
-
ToolAdapter.
|
|
99
|
+
Legion::Settings::Extensions.tools.filter_map do |tool_entry|
|
|
100
|
+
ToolAdapter.from_registry_entry(tool_entry) if defined?(ToolAdapter) && ToolAdapter.respond_to?(:from_registry_entry)
|
|
122
101
|
rescue StandardError => e
|
|
123
102
|
handle_exception(e, level: :debug, operation: 'legion.mcp.catalog_dispatcher.generate_tools_from_catalog')
|
|
124
103
|
nil
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
require 'securerandom'
|
|
4
|
+
require 'shellwords'
|
|
4
5
|
|
|
5
6
|
module Legion
|
|
6
7
|
module MCP
|
|
@@ -19,6 +20,8 @@ module Legion
|
|
|
19
20
|
@tools_cache = nil
|
|
20
21
|
@tools_cached_at = nil
|
|
21
22
|
@connected = false
|
|
23
|
+
@mcp_client = nil
|
|
24
|
+
@mcp_transport = nil
|
|
22
25
|
@mutex = Mutex.new
|
|
23
26
|
end
|
|
24
27
|
|
|
@@ -30,12 +33,8 @@ module Legion
|
|
|
30
33
|
@mutex.synchronize do
|
|
31
34
|
return if @connected
|
|
32
35
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
connection: @name,
|
|
36
|
-
transport: @transport_type,
|
|
37
|
-
config: @config.slice(:url, :command)
|
|
38
|
-
)
|
|
36
|
+
log.info("[mcp] client.connect.start #{Utils.format_fields(connection: @name, transport: @transport_type,
|
|
37
|
+
config: @config.slice(:url, :command))}")
|
|
39
38
|
case @transport_type
|
|
40
39
|
when :stdio
|
|
41
40
|
connect_stdio
|
|
@@ -44,12 +43,11 @@ module Legion
|
|
|
44
43
|
else
|
|
45
44
|
raise ArgumentError, "Unknown transport: #{@transport_type}"
|
|
46
45
|
end
|
|
46
|
+
|
|
47
|
+
verify_connection!
|
|
48
|
+
|
|
47
49
|
@connected = true
|
|
48
|
-
|
|
49
|
-
'client.connect.complete',
|
|
50
|
-
connection: @name,
|
|
51
|
-
transport: @transport_type
|
|
52
|
-
)
|
|
50
|
+
log.info("[mcp] client.connect.complete #{Utils.format_fields(connection: @name, transport: @transport_type)}")
|
|
53
51
|
end
|
|
54
52
|
rescue StandardError => e
|
|
55
53
|
@connected = false
|
|
@@ -58,9 +56,12 @@ module Legion
|
|
|
58
56
|
end
|
|
59
57
|
|
|
60
58
|
def disconnect
|
|
59
|
+
log.debug("[mcp][client] action=disconnect connection=#{@name}")
|
|
61
60
|
@mutex.synchronize do
|
|
62
|
-
@
|
|
61
|
+
@mcp_transport&.close if @mcp_transport.respond_to?(:close)
|
|
63
62
|
@connected = false
|
|
63
|
+
@mcp_client = nil
|
|
64
|
+
@mcp_transport = nil
|
|
64
65
|
@tools_cache = nil
|
|
65
66
|
end
|
|
66
67
|
end
|
|
@@ -69,83 +70,186 @@ module Legion
|
|
|
69
70
|
@mutex.synchronize do
|
|
70
71
|
if !force_refresh && @tools_cache && @tools_cached_at &&
|
|
71
72
|
(Time.now - @tools_cached_at) < TOOL_CACHE_TTL
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
connection: @name,
|
|
75
|
-
transport: @transport_type,
|
|
76
|
-
count: @tools_cache.size
|
|
77
|
-
)
|
|
73
|
+
log.info("[mcp] client.tools.cache_hit #{Utils.format_fields(connection: @name, transport: @transport_type,
|
|
74
|
+
count: @tools_cache.size)}")
|
|
78
75
|
return @tools_cache
|
|
79
76
|
end
|
|
80
77
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
connection: @name,
|
|
84
|
-
transport: @transport_type,
|
|
85
|
-
force_refresh: force_refresh
|
|
86
|
-
)
|
|
78
|
+
log.info("[mcp] client.tools.fetch.start #{Utils.format_fields(connection: @name, transport: @transport_type,
|
|
79
|
+
force_refresh: force_refresh)}")
|
|
87
80
|
@tools_cache = fetch_tools
|
|
88
81
|
@tools_cached_at = Time.now
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
connection: @name,
|
|
92
|
-
transport: @transport_type,
|
|
93
|
-
count: @tools_cache.size
|
|
94
|
-
)
|
|
82
|
+
log.info("[mcp] client.tools.fetch.complete #{Utils.format_fields(connection: @name, transport: @transport_type,
|
|
83
|
+
count: @tools_cache.size)}")
|
|
95
84
|
@tools_cache
|
|
96
85
|
end
|
|
97
86
|
end
|
|
98
87
|
|
|
99
|
-
def call_tool(name:, arguments: {})
|
|
88
|
+
def call_tool(name:, arguments: {}, context: {})
|
|
100
89
|
connect unless connected?
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
transport:
|
|
105
|
-
|
|
106
|
-
arguments:
|
|
107
|
-
)
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
90
|
+
exchange_id = TracingContext.generate_exchange_id
|
|
91
|
+
|
|
92
|
+
log.info("[mcp] client.tool_call.start #{Utils.format_fields(
|
|
93
|
+
connection: @name, transport: @transport_type, tool_name: name,
|
|
94
|
+
exchange_id: exchange_id, trace_id: context[:trace_id],
|
|
95
|
+
arguments: Utils.summarize_params(arguments)
|
|
96
|
+
)}")
|
|
97
|
+
|
|
98
|
+
start_time = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
|
|
99
|
+
result = execute_tool_call(name: name, arguments: arguments, context: context)
|
|
100
|
+
elapsed = ((::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - start_time) * 1000).round(1)
|
|
101
|
+
|
|
102
|
+
log.info("[mcp] client.tool_call.complete #{Utils.format_fields(
|
|
103
|
+
connection: @name, transport: @transport_type, tool_name: name,
|
|
104
|
+
exchange_id: exchange_id, duration_ms: elapsed,
|
|
105
|
+
result: Utils.summarize_result(result)
|
|
106
|
+
)}")
|
|
107
|
+
|
|
108
|
+
emit_client_audit(tool_name: name, arguments: arguments, result: result,
|
|
109
|
+
context: context, exchange_id: exchange_id, duration_ms: elapsed)
|
|
110
|
+
|
|
116
111
|
result
|
|
117
112
|
rescue StandardError => e
|
|
118
113
|
handle_exception(e, level: :warn, operation: 'legion.mcp.client.connection.call_tool')
|
|
119
|
-
LoggingSupport.warn(
|
|
120
|
-
'client.tool_call.failed',
|
|
121
|
-
connection: @name,
|
|
122
|
-
transport: @transport_type,
|
|
123
|
-
tool_name: name,
|
|
124
|
-
error: e.message
|
|
125
|
-
)
|
|
126
114
|
raise
|
|
127
115
|
end
|
|
128
116
|
|
|
129
117
|
private
|
|
130
118
|
|
|
131
119
|
def connect_stdio
|
|
132
|
-
|
|
120
|
+
command = @config[:command]
|
|
121
|
+
raise ArgumentError, 'stdio transport requires a :command config key' unless command
|
|
122
|
+
|
|
123
|
+
log.debug("[mcp][client] action=connect_stdio connection=#{@name}")
|
|
124
|
+
parts = command.is_a?(Array) ? command : Shellwords.split(command)
|
|
125
|
+
cmd = parts.shift
|
|
126
|
+
@mcp_transport = ::MCP::Client::Stdio.new(command: cmd, args: parts)
|
|
127
|
+
@mcp_client = ::MCP::Client.new(transport: @mcp_transport)
|
|
133
128
|
end
|
|
134
129
|
|
|
135
130
|
def connect_http
|
|
136
|
-
|
|
131
|
+
url = @config[:url]
|
|
132
|
+
raise ArgumentError, 'http transport requires a :url config key' unless url
|
|
133
|
+
|
|
134
|
+
log.debug("[mcp][client] action=connect_http connection=#{@name} url=#{url}")
|
|
135
|
+
@base_headers = (@config[:headers] || {}).dup
|
|
136
|
+
@base_headers['Authorization'] ||= @config[:auth] if @config[:auth]
|
|
137
|
+
|
|
138
|
+
@mcp_transport = ::MCP::Client::HTTP.new(url: url, headers: @base_headers)
|
|
139
|
+
@mcp_client = ::MCP::Client.new(transport: @mcp_transport)
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
def inject_trace_headers(context)
|
|
143
|
+
return unless http_transport? && traceable_context?(context)
|
|
144
|
+
|
|
145
|
+
headers = build_trace_headers(context)
|
|
146
|
+
@mcp_transport.instance_variable_set(:@headers, headers) if @mcp_transport.instance_variable_defined?(:@headers)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def http_transport?
|
|
150
|
+
%i[http streamable_http].include?(@transport_type) &&
|
|
151
|
+
@mcp_transport.respond_to?(:instance_variable_get)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def traceable_context?(context)
|
|
155
|
+
context.is_a?(Hash) && !context.empty? &&
|
|
156
|
+
(context[:trace_id] || context[:conversation_id])
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def build_trace_headers(context)
|
|
160
|
+
headers = @base_headers&.dup || {}
|
|
161
|
+
headers['x-legion-trace-id'] = context[:trace_id] if context[:trace_id]
|
|
162
|
+
headers['x-legion-conversation-id'] = context[:conversation_id] if context[:conversation_id]
|
|
163
|
+
headers['traceparent'] = "00-#{context[:trace_id]}-#{SecureRandom.hex(8)}-01" if context[:trace_id]
|
|
164
|
+
headers
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
# Verify the connection by requesting the tool list. This triggers
|
|
168
|
+
# the MCP initialize handshake on stdio transports and confirms the
|
|
169
|
+
# HTTP endpoint is reachable. The result seeds the tools cache.
|
|
170
|
+
def verify_connection!
|
|
171
|
+
log.debug("[mcp][client] action=verify_connection connection=#{@name}")
|
|
172
|
+
raw_tools = @mcp_client.tools
|
|
173
|
+
@tools_cache = raw_tools.map do |tool|
|
|
174
|
+
{
|
|
175
|
+
name: tool.name,
|
|
176
|
+
description: tool.description,
|
|
177
|
+
input_schema: tool.input_schema
|
|
178
|
+
}
|
|
179
|
+
end
|
|
180
|
+
@tools_cached_at = Time.now
|
|
181
|
+
rescue ::MCP::Client::ServerError, ::MCP::Client::RequestHandlerError => e
|
|
182
|
+
handle_exception(e, level: :error, handled: false,
|
|
183
|
+
operation: 'mcp.client.connection.verify_connection')
|
|
184
|
+
raise ConnectionError, "MCP handshake failed for #{@name}: #{e.message}"
|
|
137
185
|
end
|
|
138
186
|
|
|
139
187
|
def fetch_tools
|
|
140
188
|
connect unless connected?
|
|
141
|
-
|
|
189
|
+
|
|
190
|
+
log.debug("[mcp][client] action=fetch_tools connection=#{@name}")
|
|
191
|
+
raw_tools = @mcp_client.tools
|
|
192
|
+
raw_tools.map do |tool|
|
|
193
|
+
{
|
|
194
|
+
name: tool.name,
|
|
195
|
+
description: tool.description,
|
|
196
|
+
input_schema: tool.input_schema
|
|
197
|
+
}
|
|
198
|
+
end
|
|
199
|
+
rescue ::MCP::Client::ServerError, ::MCP::Client::RequestHandlerError => e
|
|
200
|
+
handle_exception(e, level: :warn, handled: false,
|
|
201
|
+
operation: 'mcp.client.connection.fetch_tools')
|
|
202
|
+
raise ConnectionError, "Failed to fetch tools from #{@name}: #{e.message}"
|
|
142
203
|
end
|
|
143
204
|
|
|
144
|
-
def execute_tool_call(
|
|
205
|
+
def execute_tool_call(name:, arguments:, context: {})
|
|
145
206
|
connect unless connected?
|
|
146
|
-
|
|
207
|
+
inject_trace_headers(context)
|
|
208
|
+
|
|
209
|
+
log.debug("[mcp][client] action=execute_tool_call connection=#{@name} tool=#{name}")
|
|
210
|
+
response = @mcp_client.call_tool(name: name, arguments: arguments)
|
|
211
|
+
result = response.is_a?(Hash) ? response['result'] || response : response
|
|
212
|
+
|
|
213
|
+
content = result.is_a?(Hash) ? result['content'] || result.fetch('content', []) : []
|
|
214
|
+
is_error = result.is_a?(Hash) ? result.fetch('isError', false) : false
|
|
215
|
+
|
|
216
|
+
{ content: content, error: is_error }
|
|
217
|
+
rescue ::MCP::Client::ServerError => e
|
|
218
|
+
handle_exception(e, level: :warn, operation: 'legion.mcp.client.connection.execute_tool_call')
|
|
219
|
+
{ content: [{ type: 'text', text: e.message }], error: true }
|
|
220
|
+
rescue ::MCP::Client::RequestHandlerError => e
|
|
221
|
+
handle_exception(e, level: :warn, handled: false,
|
|
222
|
+
operation: 'mcp.client.connection.execute_tool_call')
|
|
223
|
+
raise ConnectionError, "Tool call failed on #{@name}: #{e.message}"
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
def emit_client_audit(event)
|
|
227
|
+
return unless defined?(Legion::MCP::Audit)
|
|
228
|
+
|
|
229
|
+
context = event[:context] || {}
|
|
230
|
+
result = event[:result]
|
|
231
|
+
status = result.is_a?(Hash) && result[:error] ? :error : :success
|
|
232
|
+
|
|
233
|
+
Legion::MCP::Audit.emit_client_call(
|
|
234
|
+
conversation_id: context[:conversation_id],
|
|
235
|
+
request_id: context[:request_id],
|
|
236
|
+
exchange_id: event[:exchange_id],
|
|
237
|
+
tool_name: event[:tool_name],
|
|
238
|
+
server: @name,
|
|
239
|
+
transport: @transport_type,
|
|
240
|
+
arguments: event[:arguments],
|
|
241
|
+
result: Utils.summarize_result(result),
|
|
242
|
+
status: status,
|
|
243
|
+
duration_ms: event[:duration_ms],
|
|
244
|
+
trace_id: context[:trace_id],
|
|
245
|
+
timestamp: Time.now.utc.iso8601
|
|
246
|
+
)
|
|
247
|
+
rescue StandardError => e
|
|
248
|
+
handle_exception(e, level: :warn, handled: true, operation: 'mcp.client.emit_audit')
|
|
147
249
|
end
|
|
148
250
|
end
|
|
251
|
+
|
|
252
|
+
class ConnectionError < StandardError; end
|
|
149
253
|
end
|
|
150
254
|
end
|
|
151
255
|
end
|
|
@@ -13,33 +13,68 @@ module Legion
|
|
|
13
13
|
|
|
14
14
|
def connection_for(server_name)
|
|
15
15
|
@mutex.synchronize do
|
|
16
|
-
|
|
16
|
+
if @connections.key?(server_name)
|
|
17
|
+
log.debug("[mcp][pool] action=connection_for server=#{server_name} cached=true")
|
|
18
|
+
return @connections[server_name]
|
|
19
|
+
end
|
|
17
20
|
|
|
18
21
|
config = ServerRegistry.servers[server_name]
|
|
19
|
-
|
|
22
|
+
unless config
|
|
23
|
+
log.debug("[mcp][pool] action=connection_for server=#{server_name} found=false")
|
|
24
|
+
return nil
|
|
25
|
+
end
|
|
20
26
|
|
|
27
|
+
log.debug("[mcp][pool] action=connection_for server=#{server_name} creating=true")
|
|
21
28
|
conn = Connection.new(name: server_name, **config.except(:registered_at, :source))
|
|
22
29
|
@connections[server_name] = conn
|
|
23
30
|
end
|
|
24
31
|
end
|
|
25
32
|
|
|
26
33
|
def all_tools
|
|
27
|
-
ServerRegistry.healthy_servers
|
|
34
|
+
healthy = ServerRegistry.healthy_servers
|
|
35
|
+
log.debug("[mcp][pool] action=all_tools healthy_servers=#{healthy.size}")
|
|
36
|
+
healthy.flat_map do |name, _config|
|
|
28
37
|
conn = connection_for(name)
|
|
29
38
|
next [] unless conn
|
|
30
39
|
|
|
31
40
|
conn.tools.map do |tool|
|
|
32
|
-
|
|
41
|
+
tool_entry = {
|
|
42
|
+
name: tool[:name],
|
|
43
|
+
description: tool[:description],
|
|
44
|
+
input_schema: tool[:input_schema],
|
|
45
|
+
tool_class: nil,
|
|
46
|
+
dispatch_type: :mcp_remote,
|
|
47
|
+
extension: "mcp:#{name}",
|
|
48
|
+
source: :mcp_remote,
|
|
49
|
+
mcp_server: name
|
|
50
|
+
}
|
|
51
|
+
# Register into the central registry so LLM pipeline sees these too
|
|
52
|
+
if Legion::Settings::Extensions.respond_to?(:register_tool)
|
|
53
|
+
Legion::Settings::Extensions.register_tool(tool[:name], tool_entry)
|
|
54
|
+
end
|
|
55
|
+
tool_entry
|
|
33
56
|
end
|
|
34
57
|
rescue StandardError => e
|
|
35
58
|
handle_exception(e, level: :warn, operation: 'legion.mcp.client.pool.all_tools')
|
|
36
|
-
log.warn("MCP tool discovery failed for #{name}: #{e.message}")
|
|
37
59
|
ServerRegistry.mark_unhealthy(name)
|
|
38
60
|
[]
|
|
39
61
|
end
|
|
40
62
|
end
|
|
41
63
|
|
|
64
|
+
def refresh_tools!
|
|
65
|
+
log.debug("[mcp][pool] action=refresh_tools connections=#{@connections.size}")
|
|
66
|
+
@mutex.synchronize do
|
|
67
|
+
@connections.each_value do |conn|
|
|
68
|
+
conn.tools(force_refresh: true)
|
|
69
|
+
rescue StandardError => e
|
|
70
|
+
handle_exception(e, level: :debug, operation: 'legion.mcp.client.pool.refresh_tools!')
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
all_tools
|
|
74
|
+
end
|
|
75
|
+
|
|
42
76
|
def reset!
|
|
77
|
+
log.debug("[mcp][pool] action=reset connections=#{@connections.size}")
|
|
43
78
|
@mutex.synchronize do
|
|
44
79
|
@connections.each_value do |connection|
|
|
45
80
|
connection.disconnect
|