legion-mcp 0.9.2 → 0.9.3

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.
data/README.md CHANGED
@@ -1,215 +1,145 @@
1
1
  # legion-mcp
2
2
 
3
- Model Context Protocol (MCP) server for the LegionIO framework. Provides semantic tool matching, observation pipeline, context compilation, tiered behavioral intelligence (Tier 0/1/2 routing), tool governance, deferred tool loading, and MCP client pooling for remote server federation.
3
+ `legion-mcp` is the LegionIO Model Context Protocol (MCP) server and client library. It adapts the Legion tool registry to the MCP SDK, exposes Legion-owned discovery and inspection tools, applies role/risk policy, records tool observations, and includes remote-server registration and federation client APIs.
4
4
 
5
- **Version**: 0.9.2
6
- **License**: Apache-2.0
7
- **Ruby**: >= 3.4
5
+ This gem is a **core Legion library**, not a LEX extension. It does not provide a general-purpose LLM host, an HTTP deployment platform, or a complete authentication/authorization deployment by itself.
8
6
 
9
- Extracted from [LegionIO](https://github.com/LegionIO/LegionIO) for independent versioning and reuse.
7
+ - **Source version:** 0.9.3
8
+ - **Ruby:** >= 3.4
9
+ - **License:** Apache-2.0
10
+ - **Source:** [LegionIO/legion-mcp](https://github.com/LegionIO/legion-mcp)
10
11
 
11
12
  ## Installation
12
13
 
13
- ```ruby
14
- gem 'legion-mcp'
15
- ```
16
-
17
- Or in a Gemfile:
14
+ Add the gem to the application bundle:
18
15
 
19
16
  ```ruby
20
- gem 'legion-mcp', '~> 0.9', '>= 0.9.2'
17
+ gem 'legion-mcp', '~> 0.9', '>= 0.9.3'
21
18
  ```
22
19
 
23
- The MCP SDK dependency requires `>= 1.2.0, < 2.0`. Earlier SDK versions are
24
- excluded because of [GHSA-4m5j-jjfc-97gx](https://github.com/modelcontextprotocol/ruby-sdk/security/advisories/GHSA-4m5j-jjfc-97gx),
25
- an OAuth discovery SSRF vulnerability. Upgrade the bundle rather than ignoring
26
- the advisory.
27
-
28
- ## Architecture
20
+ Then install:
29
21
 
30
- ```
31
- Legion::MCP
32
- ├── Server # MCP::Server builder, governance-aware build; tool list sourced via DeferredRegistry
33
- ├── Auth # JWT + API key authentication
34
- ├── Utils # Pure-function summarization and formatting helpers
35
- ├── ToolGovernance # Risk-tier tool filtering + invocation audit
36
- ├── ToolAdapter # Adapts Legion::Tools::Base to MCP SDK format; handles :mcp_remote dispatch
37
- ├── DeferredRegistry # Reads deferred/always-loaded tools from Settings::Extensions at request time
38
- ├── ContextCompiler # Keyword + semantic tool matching (60/40 blend), 17 categories
39
- ├── EmbeddingIndex # In-memory vector cache for semantic matching
40
- ├── Observer # Instrumentation: counters, ring buffer, intent tracking, pattern promotion
41
- ├── UsageFilter # Frequency/recency/keyword scoring for dynamic tool filtering
42
- ├── DynamicInjector # Context-aware tool injection/removal with tools/list_changed notification
43
- ├── CatalogDispatcher # Dispatch layer routing MCP calls through Legion::Ingress
44
- ├── Patterns::Store # 3-layer degrading storage (L0 memory -> L1 cache -> L2 SQLite)
45
- ├── Patterns::Schema # Portable pattern format with trust-level confidence capping
46
- ├── Patterns::Exchange # Bulk import/export of patterns via JSON files
47
- ├── Patterns::Gossip # AMQP-based pattern sharing between instances
48
- ├── Patterns::Compiler # Compressed tool definitions and compiled workflows
49
- ├── TierRouter # Confidence-gated tier selection (0/1/2)
50
- ├── ContextGuard # Staleness, rapid-fire, anomaly detection guards
51
- ├── StateTracker # In-memory state snapshots with delta diff computation
52
- ├── StructuralIndex # Precomputed index of extensions, runners, actors, and tools
53
- ├── ToolQuality # Docstring quality audit, category resolution, capability matrix
54
- ├── GapDetector # Unmatched intents, high-failure tools, stale candidate detection
55
- ├── SelfGenerate # Gap detection + publication cycles with cooldown
56
- ├── OverrideBroadcast # Mesh-wide override confirmation via RabbitMQ
57
- ├── TracingContext # Thread-local conversation/request/exchange/trace ID propagation
58
- ├── Client::Pool # Remote MCP server connections; registers tools into Settings::Extensions
59
- ├── Client::Connection # stdio and HTTP transport connections with TTL-cached tool lists
60
- ├── Client::ServerRegistry # Static and dynamic server registration with health tracking
61
- ├── Tools/ # 10 MCP-specific + 18 legion-data CRUD tools; extension tools via Settings::Extensions
62
- └── Resources/ # RunnerCatalog, ExtensionInfo
22
+ ```bash
23
+ bundle install
63
24
  ```
64
25
 
65
- ### Tool Registry
26
+ The gemspec requires the MCP Ruby SDK `>= 1.9, < 2`, Ruby 3.4 or newer, and the Legion dependencies listed in [Dependencies](#dependencies). The SDK range includes the OAuth-discovery SSRF fix described in [GHSA-4m5j-jjfc-97gx](https://github.com/modelcontextprotocol/ruby-sdk/security/advisories/GHSA-4m5j-jjfc-97gx).
66
27
 
67
- - **MCP_SPECIFIC_TOOLS** (10 tools): `do_action`, `discover_tools`, `plan_action`, `structural_index`, `tool_audit`, `state_diff`, `search_sessions`, `skill_list`, `skill_describe`, `skill_invoke`, `skill_cancel`
68
- - **legion-data CRUD** (18 tools): `run_task`, `describe_runner`, list/get/delete tasks, `get_task_logs`, CRUD chains/relationships/schedules
69
- - **Extension tools**: Auto-discovered via `Legion::Settings::Extensions` at runtime; not shipped as static files
70
- - **Remote MCP tools**: Fetched from remote servers via `Client::Pool.all_tools`, registered into `Settings::Extensions` with `dispatch_type: :mcp_remote`
28
+ ## Starting a server
71
29
 
72
- ## Tiered Behavioral Intelligence
30
+ ### Standalone stdio
73
31
 
74
- Requests flow through three tiers, each with increasing latency and capability:
32
+ Save the following as `mcp_stdio.rb`. Configure file logging **before** loading MCP so log output cannot corrupt the JSON-RPC stream:
75
33
 
76
- | Tier | Confidence | What happens | Latency |
77
- |------|-----------|--------------|---------|
78
- | 0 | >= 0.8 | Cached pattern match, no LLM | < 5ms |
79
- | 1 | 0.6 - 0.8 | Local/fleet model hint | ~100ms |
80
- | 2 | < 0.6 | Full cloud LLM | ~1-3s |
34
+ ```ruby
35
+ # mcp_stdio.rb
36
+ require 'legion/logging'
37
+
38
+ Legion::Logging.setup(
39
+ log_file: File.expand_path('~/.legionio/logs/mcp.log'),
40
+ log_stdout: false
41
+ )
81
42
 
82
- ### Pattern Lifecycle
43
+ require 'legion/mcp'
44
+ require 'mcp/server/transports/stdio_transport'
83
45
 
84
- 1. **Observer** records intent+tool pairs from MCP tool invocations
85
- 2. After 3 successful observations, promotes candidate to **PatternStore** (seeded confidence 0.5)
86
- 3. Successful executions increase confidence (+0.02), failures decrease it (-0.05)
87
- 4. Once confidence reaches 0.8, **TierRouter** serves the pattern at Tier 0
46
+ transport = ::MCP::Server::Transports::StdioTransport.new(Legion::MCP.server)
47
+ transport.open
48
+ ```
88
49
 
89
- ### Context Guards
50
+ Launch it with `bundle exec ruby mcp_stdio.rb`. The explicit file destination matters: `log_stdout: false` without a file destination can still leave logging on stdout. Reserve stdout for MCP JSON-RPC.
90
51
 
91
- Before serving a Tier 0 response, **ContextGuard** checks:
52
+ ### LegionIO CLI
92
53
 
93
- - **Staleness**: Pattern not hit in > 1 hour
94
- - **Rapid-fire**: > 5 requests in 10 minutes (possible loop)
95
- - **Anomaly**: 2+ consecutive misses (pattern may be stale)
54
+ When running inside LegionIO, use the framework command:
96
55
 
97
- If any guard triggers, the request escalates to Tier 1.
56
+ ```bash
57
+ legionio serve mcp stdio
58
+ legionio serve mcp http --host 127.0.0.1 --port 9393
59
+ ```
98
60
 
99
- ### Storage Layers
61
+ `stdio` is the default subcommand. HTTP uses the MCP SDK streamable-HTTP transport and Puma through the LegionIO CLI. The current CLI checks a bearer token when `mcp.auth.enabled` is true, but uses the shared `Legion::MCP.server`; that token check does not automatically bind JWT claims to an identity-scoped server. Hosts that require per-identity policy must authenticate the request and select a trusted identity-scoped server explicitly.
100
62
 
101
- PatternStore degrades gracefully across 3 layers:
63
+ ## What is registered by default
102
64
 
103
- | Layer | Backend | Requirement |
104
- |-------|---------|-------------|
105
- | L0 | In-memory hash | Always available |
106
- | L1 | Legion::Cache (memcached/redis) | `defined?(Legion::Cache)` |
107
- | L2 | Legion::Data::Local (SQLite) | `defined?(Legion::Data::Local)` |
65
+ `Legion::MCP::Server::MCP_SPECIFIC_TOOLS` is the authoritative built-in MCP registry. It contains these ten tools:
108
66
 
109
- All persistence wraps in `begin/rescue => nil` -- failed writes never block Tier 0.
67
+ | Tool | Purpose |
68
+ | --- | --- |
69
+ | `legion.plan` | Rank matching tools into an ordered plan; an optional narrative is generated only when a Legion LLM integration is available. |
70
+ | `legion.tools` | Discover tools by category or intent, or resolve full schemas by name. |
71
+ | `legion.structural_index` | Query the precomputed extension, runner, actor, and tool index. |
72
+ | `legion.tool_audit` | Audit registered tool metadata and quality. |
73
+ | `legion.state_diff` | Read state changes since a supplied point in time. |
74
+ | `legion.search_sessions` | Search available conversation sessions. |
75
+ | `legion.skill.list` | List registered skills. |
76
+ | `legion.skill.describe` | Describe a skill. |
77
+ | `legion.skill.invoke` | Invoke a skill for a conversation. |
78
+ | `legion.skill.cancel` | Cancel an active skill run. |
110
79
 
111
- ## Tools
80
+ `lib/legion/mcp/tools_loader.rb` requires additional tool classes, including `legion.run_task` and Legion Data CRUD classes, so those constants are available to the Ruby process. Loading a class does **not** make it a default MCP catalog entry. Extension-owned and runner-derived tools are added only when the Legion settings/extension registry and exposure rules provide them; data-backed tools also require their corresponding runtime services.
112
81
 
113
- 28 built-in MCP tools in the `legion.*` namespace (10 MCP-specific + 18 legion-data CRUD). Extension-owned tools are auto-discovered at runtime via `Legion::Settings::Extensions`.
82
+ Remote tools are separate registry entries created by the federation client with `dispatch_type: :mcp_remote`. They are not part of the ten-tool built-in registry.
114
83
 
115
- | Tool | Purpose |
116
- |------|---------|
117
- | `legion.do` | Natural language intent routing (Tier 0 fast path) |
118
- | `legion.tools` | Dynamic tool discovery by category, intent, or schema resolution |
119
- | `legion.plan` | Multi-step workflow planning with LLM narrative |
120
- | `legion.structural_index` | Precomputed structural index of extensions/runners/actors/tools |
121
- | `legion.tool_audit` | Quality audit of registered tools (summary/matrix/issues) |
122
- | `legion.state_diff` | Delta state polling since a given timestamp |
123
- | `legion.search_sessions` | Search past conversation sessions by keyword |
124
- | `legion.skill.list` | List all registered LLM skills |
125
- | `legion.skill.describe` | Describe a specific skill |
126
- | `legion.skill.invoke` | Invoke a skill for a conversation |
127
- | `legion.skill.cancel` | Cancel an active skill run |
128
- | `legion.run_task` | Execute a runner function via dot notation |
129
- | `legion.describe_runner` | Runner/function discovery |
130
- | `legion.list_tasks` / `get_task` / `delete_task` / `get_task_logs` | Task CRUD + logs |
131
- | `legion.list_chains` / `create_chain` / `update_chain` / `delete_chain` | Chain management |
132
- | `legion.list_relationships` / `create_*` / `update_*` / `delete_*` | Relationship CRUD |
133
- | `legion.list_schedules` / `create_*` / `update_*` / `delete_*` | Schedule CRUD |
134
-
135
- ## Resources
136
-
137
- | URI | Description |
138
- |-----|-------------|
139
- | `legion://runners` | All registered extension.runner.function paths |
140
- | `legion://extensions/{name}` | Extension detail template |
141
-
142
- ## MCP Client (Federation)
143
-
144
- Connect to remote MCP servers via stdio or HTTP transport:
84
+ Every MCP tool descriptor has an `inputSchema`. Deferred descriptors may omit optional metadata, but they do not omit the schema or required arguments.
145
85
 
146
- ```ruby
147
- # Via settings (loaded at boot)
148
- # settings/mcp.json:
149
- # { "mcp": { "servers": { "code_server": { "transport": "stdio", "command": "npx @example/mcp-server" } } } }
86
+ ## Tool dispatch and resources
150
87
 
151
- Legion::MCP::Client.boot
88
+ The server builds MCP tools from three sources:
152
89
 
153
- # Or register at runtime
154
- Legion::MCP::Client.register(:my_server, transport: :http, url: 'http://localhost:9393/mcp')
90
+ 1. the ten MCP-specific classes above;
91
+ 2. entries in `Legion::Settings::Extensions`, adapted by `Legion::MCP::ToolAdapter`; and
92
+ 3. runner functions discovered and exposed by Legion's function-discovery path.
155
93
 
156
- # All remote tools are registered into Settings::Extensions with dispatch_type: :mcp_remote
157
- tools = Legion::MCP::Client::Pool.all_tools
158
- ```
94
+ Dispatch depends on the registry entry. A loaded tool class may be called directly, a catalog-generated runner tool uses `Legion::Ingress` when that integration is available, and an MCP-remote entry calls its federation connection. Do not assume every MCP call follows the catalog/Ingress path.
159
95
 
160
- ## Usage
96
+ The server also registers:
161
97
 
162
- ### Standalone MCP server
98
+ - `legion://runners`, an application runner catalog; and
99
+ - `legion://extensions/{name}`, an extension information resource template.
163
100
 
164
- ```ruby
165
- require 'legion/mcp'
166
- require 'mcp/server/transports/stdio_transport'
101
+ The catalog uses the settings extension registry when populated, otherwise it requires the relevant Legion Data connection.
167
102
 
168
- # Keep structured logs off the JSON-RPC stdout stream.
169
- Legion::Logging.setup(log_stdout: false)
170
- MCP::Server::Transports::StdioTransport.new(Legion::MCP.server).open
171
- ```
103
+ ## Deferred schemas and discovery
172
104
 
173
- ### Within LegionIO
105
+ Deferred loading is enabled by default. The `tools/list` handler returns full definitions for always-loaded tools and a reduced descriptor for deferred tools. The reduced descriptor still includes the name, description, and actual `inputSchema`.
174
106
 
175
- ```bash
176
- # stdio transport (default)
177
- legionio mcp stdio
107
+ To request complete definitions for selected tools, call `legion.tools` with `tool_names` and `schema: true`:
178
108
 
179
- # HTTP transport
180
- legionio mcp http --port 9393
109
+ ```json
110
+ {
111
+ "tool_names": ["legion.skill.describe"],
112
+ "schema": true
113
+ }
181
114
  ```
182
115
 
183
- ### Tier 0 direct usage
116
+ Schema resolution is evaluated against the identity-scoped, governed tool registry. A tool that is not registered or not permitted for that identity is not returned.
184
117
 
185
- ```ruby
186
- result = Legion::MCP::TierRouter.route(
187
- intent: "list all running tasks",
188
- params: { status: "running" },
189
- context: {}
190
- )
118
+ ## Configuration and settings registration
191
119
 
192
- case result[:tier]
193
- when 0 then puts "Cached: #{result[:response]}"
194
- when 1 then puts "Escalate to local model"
195
- when 2 then puts "Escalate to cloud LLM"
196
- end
197
- ```
120
+ Loading `legion/mcp` registers two separate settings payloads:
121
+
122
+ - `Legion::MCP::Settings.default` is the **flat contents of the `:mcp` namespace**.
123
+ - `Legion::MCP::Settings.codegen` is merged separately under `:codegen`.
198
124
 
199
- ### Identity-scoped server
125
+ The entrypoint calls:
200
126
 
201
127
  ```ruby
202
- server = Legion::MCP.server_for(token: jwt_token)
203
- # Returns governance-filtered tool set based on JWT claims
128
+ Legion::Settings.merge_settings(:mcp, Legion::MCP::Settings.default)
129
+ Legion::Settings.merge_settings(:codegen, Legion::MCP::Settings.codegen)
204
130
  ```
205
131
 
206
- ## Configuration
207
-
208
- Configuration lives in the required `Legion::Settings` tree. Loading `legion/mcp` registers defaults under `:mcp` and `:codegen` without replacing user configuration. Deferred-loading and role-permission changes are read from the live tree; explicitly setting a role or its `tools` value to `false` denies that role all tools.
132
+ Application configuration is normally supplied through the Legion settings loader. The following shows the principal MCP keys and their defaults; it is a configuration shape, not a requirement to enable every feature:
209
133
 
210
134
  ```json
211
135
  {
212
136
  "mcp": {
137
+ "servers": {},
138
+ "overrides": {},
139
+ "tool_cache_ttl": 300,
140
+ "connect_timeout": 10,
141
+ "call_timeout": 30,
142
+ "auto_expose_runners": false,
213
143
  "auth": {
214
144
  "enabled": false,
215
145
  "require_auth": false,
@@ -223,6 +153,7 @@ Configuration lives in the required `Legion::Settings` tree. Loading `legion/mcp
223
153
  "audit_invocations": true,
224
154
  "tool_risk_tiers": {}
225
155
  },
156
+ "roles": {},
226
157
  "deferred_loading": {
227
158
  "enabled": true,
228
159
  "always_loaded": []
@@ -238,90 +169,186 @@ Configuration lives in the required `Legion::Settings` tree. Loading `legion/mcp
238
169
  "rapid_fire_window_seconds": 600
239
170
  }
240
171
  },
241
- "auto_expose_runners": false,
242
- "servers": {},
243
172
  "cold_start": {
244
173
  "patterns_path": null
245
- },
246
- "roles": {}
174
+ }
175
+ },
176
+ "codegen": {
177
+ "self_generate": {
178
+ "enabled": false,
179
+ "cycle_interval": 300,
180
+ "cooldown_seconds": 300,
181
+ "max_gaps_per_cycle": 5
182
+ }
183
+ }
184
+ }
185
+ ```
186
+
187
+ For a standalone host, configure logging first, then load the saved JSON before
188
+ requiring MCP:
189
+
190
+ ```ruby
191
+ require 'legion/settings'
192
+ Legion::Settings.load(config_file: File.expand_path('settings/mcp.json'))
193
+ require 'legion/mcp'
194
+ Legion::Settings.validate!
195
+ ```
196
+
197
+ The full self-generation payload also contains tiering, validation, approval, hot-registration, corroboration, runner/extension output, and GitHub settings in `Legion::MCP::Settings.codegen`. Self-generation is disabled by default. Enabling it publishes detected gaps to the Legion transport when that integration is present; it does not itself generate, validate, bundle, or merge code synchronously in an MCP request.
198
+
199
+ The global `tool_cache_ttl`, `connect_timeout`, and `call_timeout` keys are declared defaults, but the current federation wrapper does not read them. `Client::Connection` currently uses its fixed 300-second tool-cache constant; do not rely on those global keys to change transport behavior.
200
+
201
+ ## Authentication and governance boundaries
202
+
203
+ Authentication and trusted identity are separate concerns:
204
+
205
+ - Authentication is disabled by default. `Legion::MCP.server` builds an unscoped server with `identity: nil`; `server_for` falls back to the anonymous low-risk identity when token authentication is inactive.
206
+ - `server_for(token: ...)` authenticates when `auth.enabled` is true, or when `auth.require_auth` is true and a token was supplied. `require_auth` alone does not reject a missing token; the host must enforce its authentication boundary.
207
+ - `Legion::MCP.server_for(identity: ...)` accepts an identity supplied by a trusted host. Do not treat a caller-provided identity as proof of authentication.
208
+ - JWT claims provide `sub`, optional `risk_tier`, `tenant_id`, and `worker_id`; role authorization must be supplied by the host/application identity path.
209
+ - Risk-tier filtering is disabled by default. A supplied role is filtered independently of that switch. Both policies are checked again immediately before each SDK tool call.
210
+ - Missing or unknown roles are permissive unless a role is explicitly configured with `false` or with an empty tool allowlist. Set explicit roles and risk tiers when a restrictive policy is required.
211
+
212
+ For example, an identity-scoped server can be built after an upstream authenticator has established the identity:
213
+
214
+ ```ruby
215
+ require 'legion/mcp'
216
+
217
+ Legion::Settings.loader.settings[:mcp][:roles][:operator] = { tools: ['legion.tools'] }
218
+ server = Legion::MCP.server_for(
219
+ identity: {
220
+ user_id: 'example-operator',
221
+ role: 'operator',
222
+ risk_tier: :low
223
+ }
224
+ )
225
+ ```
226
+
227
+ The gem provides tool-level filtering and optional audit events. Deployment-level TLS, proxy policy, token delivery, network isolation, and the trustworthiness of an externally supplied identity remain application responsibilities.
228
+
229
+ Revocation and regrant apply to tools already registered on a retained server. Rebuild the server when its available tool set changes. Direct Ruby APIs such as `TierRouter.route` execute outside the SDK `tools/call` wrapper and are not an authorization boundary for untrusted requests.
230
+
231
+ ## Federation with remote MCP servers
232
+
233
+ The client supports configured `stdio`, `http`, and `streamable_http` server entries. This example documents the expected configuration shape only; it does not claim that the named remote endpoint exists or that connectivity has been verified:
234
+
235
+ ```json
236
+ {
237
+ "mcp": {
238
+ "servers": {
239
+ "local_server": {
240
+ "transport": "stdio",
241
+ "command": ["bundle", "exec", "ruby", "mcp_stdio.rb"]
242
+ },
243
+ "remote_server": {
244
+ "transport": "http",
245
+ "url": "http://127.0.0.1:9393/mcp"
246
+ }
247
+ }
247
248
  }
248
249
  }
249
250
  ```
250
251
 
252
+ The registry APIs are available for application integration:
253
+
254
+ ```ruby
255
+ require 'legion/mcp'
256
+
257
+ Legion::MCP::Client.boot # loads mcp.servers into the server registry
258
+ Legion::MCP::Client.register(
259
+ :another_server,
260
+ transport: :http,
261
+ url: ENV.fetch('MCP_REMOTE_URL')
262
+ )
263
+
264
+ # Remove configured/dynamic servers and close any created connections.
265
+ Legion::MCP::Client.shutdown
266
+ ```
267
+
268
+ `Pool.all_tools` is intended to fetch healthy-server catalogs and register
269
+ remote entries as `:mcp_remote`. In the 0.9.3 wrapper, do not treat it as a
270
+ working connectivity probe: the current pool/connection path can recursively
271
+ lock while creating a connection, and the connection path does not perform the
272
+ MCP SDK `connect` handshake before its first request. These are known
273
+ federation limitations of this release, so test the selected MCP SDK transport
274
+ and remote service in the target deployment before relying on federation.
275
+
276
+ ## Tiered routing and learned patterns
277
+
278
+ `Legion::MCP::TierRouter.route` is a local confidence gate over stored tool chains. It is not an automatic local/cloud LLM router:
279
+
280
+ - **Tier 0** (`confidence >= 0.8`): after context guards pass, execute the cached tool chain locally and return its response.
281
+ - **Tier 1** (`0.6 <= confidence < 0.8`, or a guard fails): return pattern metadata with `response: nil` and a reason for escalation.
282
+ - **Tier 2** (no matching pattern or `confidence < 0.6`): return `response: nil` with a reason.
283
+
284
+ The method returns a hash. Only a Tier 0 execution includes a generated response and measured `latency_ms`; Tier 1 and Tier 2 do not invoke an LLM automatically:
285
+
286
+ ```ruby
287
+ require 'legion/mcp'
288
+ require 'legion/mcp/tier_router'
289
+
290
+ result = Legion::MCP::TierRouter.route(
291
+ intent: 'list running tasks',
292
+ params: { status: 'running' },
293
+ context: {}
294
+ )
295
+
296
+ case result[:tier]
297
+ when 0
298
+ puts result[:response]
299
+ when 1, 2
300
+ puts "Escalation required: #{result[:reason]}"
301
+ end
302
+ ```
303
+
304
+ Learning is observation-driven rather than a claim that every tool call becomes a pattern:
305
+
306
+ 1. Successful intent/tool observations are accumulated; `legion.do` handles promotion with knowledge of its resolved tool.
307
+ 2. A candidate is promoted after three observations for the candidate key and starts at confidence `0.5`.
308
+ 3. Successful Tier 0 hits add `0.02`; misses subtract `0.05`, bounded to `0.0..1.0`.
309
+ 4. Exact and, when an embedding index is populated, semantic lookups can find stored patterns.
310
+ 5. Context guards cover staleness, rapid-fire requests, and consecutive misses before Tier 0 execution.
311
+
312
+ Patterns are held in memory first. When connected, Legion Cache and Legion Data Local provide optional persistence layers. Persistence failures are logged and handled so the in-memory path can continue; they are not silent successes. `mcp.cold_start.patterns_path` can import community patterns when the in-memory store is empty.
313
+
251
314
  ## Dependencies
252
315
 
253
- | Gem | Required | Purpose |
254
- |-----|----------|---------|
255
- | `mcp` (>= 1.2.0, < 2.0) | Yes | MCP server/client SDK with patched OAuth discovery |
256
- | `base64` (>= 0.2) | Yes | SDK OAuth client encoding on Ruby 3.4+ |
257
- | `legion-data` (>= 1.4) | Yes | Sequel models, migrations |
258
- | `legion-json` (>= 1.2) | Yes | JSON serialization |
259
- | `legion-logging` (>= 1.4.3) | Yes | Structured logging via Helper |
260
- | `legion-settings` (>= 1.4.0) | Yes | Configuration + Settings::Extensions |
261
- | `legion-cache` | Optional | L1 pattern cache (memcached/redis) |
262
- | `legion-llm` | Optional | Embeddings for semantic matching, Tier 1/2 LLM |
263
-
264
- ## Guard Strategy
265
-
266
- All optional dependencies use `defined?()` guards:
267
- - `defined?(Legion::Cache)` for L1 cache operations
268
- - `defined?(Legion::Data::Local)` for L2 SQLite persistence
269
- - `defined?(Legion::LLM)` for embedding generation and tiered LLM routing
270
- - `defined?(Legion::Settings::Extensions)` for central tool registry
271
- - `defined?(Legion::MCP::EmbeddingIndex)` for semantic matching
272
- - `defined?(Legion::MCP::TierRouter)` for Tier 0 routing
273
-
274
- Every storage write wraps in `begin/rescue => nil` -- failed persistence never blocks Tier 0.
275
-
276
- ## Key Conventions
277
-
278
- - `Legion::JSON.load` returns **symbol keys** -- use `body[:data]`, not `body['data']`
279
- - `Legion::JSON.dump` takes exactly 1 positional arg -- wrap kwargs in explicit `{}`
280
- - `::Process` and `::JSON` must be explicit inside the `Legion::` namespace
281
- - `Legion::MCP.server` is a memoized singleton -- call `Legion::MCP.reset!` in tests
282
- - MCP tool naming: `legion.snake_case_name` (dot namespace)
283
- - Every rescue block calls `handle_exception(e, level:, handled:, operation:)`
284
- - Logging via `extend Legion::Logging::Helper` (modules) or `include Legion::Logging::Helper` (classes/class << self)
316
+ Required runtime dependencies from the gemspec:
317
+
318
+ | Gem | Minimum/range | Role |
319
+ | --- | --- | --- |
320
+ | `mcp` | `>= 1.9, < 2` | MCP server/client SDK and transports |
321
+ | `base64` | `>= 0.2` | SDK OAuth client support on Ruby 3.4+ |
322
+ | `concurrent-ruby` | `>= 1.2` | Concurrent registries and synchronization |
323
+ | `legion-data` | `>= 1.4.19` | Legion data models and optional local persistence integration |
324
+ | `legion-json` | `>= 1.2.0` | Legion JSON serialization |
325
+ | `legion-logging` | `>= 1.4.3` | Structured logging and exception handling |
326
+ | `legion-settings` | `>= 1.4.5` | Settings and the central extension/tool registry |
327
+
328
+ `legion-cache`, Legion LLM integrations, Legion Crypt, Legion Transport, and the LegionIO runtime are optional integrations. Their presence enables additional behavior; they are not dependencies declared by this gemspec. The `Legion::Settings::Extensions` registry API itself comes from the required `legion-settings` dependency.
285
329
 
286
330
  ## Development
287
331
 
332
+ From this repository:
333
+
288
334
  ```bash
289
335
  bundle install
290
- bundle exec rspec # 0 failures
291
- bundle exec rubocop -A # auto-fix
292
- bundle exec rubocop # lint check
336
+ bundle exec rspec --format json --out tmp/rspec_results.json --format progress --out tmp/rspec_progress.txt
337
+ bundle exec rubocop -A
338
+ bundle exec rubocop
293
339
  ```
294
340
 
295
- ## File Map
296
-
297
- | Path | Purpose |
298
- |------|---------|
299
- | `lib/legion/mcp.rb` | Entry point: `Legion::MCP.server` singleton factory |
300
- | `lib/legion/mcp/version.rb` | `Legion::MCP::VERSION` constant |
301
- | `lib/legion/mcp/utils.rb` | Pure-function summarization and formatting helpers |
302
- | `lib/legion/mcp/server.rb` | MCP::Server builder, governance-aware build; reads tools from Settings::Extensions |
303
- | `lib/legion/mcp/auth.rb` | JWT + API key authentication |
304
- | `lib/legion/mcp/patterns.rb` | Barrel file for 13 Tier 0 pattern routing modules |
305
- | `lib/legion/mcp/discovery.rb` | Barrel file for 12 tool discovery and adaptation modules |
306
- | `lib/legion/mcp/tool_adapter.rb` | MCP::ToolAdapter -- wraps tools for MCP SDK; handles :mcp_remote dispatch |
307
- | `lib/legion/mcp/deferred_registry.rb` | Deferred/always-loaded tool list management |
308
- | `lib/legion/mcp/catalog_dispatcher.rb` | Dispatch layer routing through Legion::Ingress |
309
- | `lib/legion/mcp/dynamic_injector.rb` | Context-aware tool injection/removal |
310
- | `lib/legion/mcp/client.rb` | Client boot/shutdown, server registration |
311
- | `lib/legion/mcp/client/pool.rb` | Connection pool; all_tools registers into Settings::Extensions |
312
- | `lib/legion/mcp/client/connection.rb` | stdio/HTTP transport connections |
313
- | `lib/legion/mcp/client/server_registry.rb` | Server health tracking and registration |
314
- | `lib/legion/mcp/tools/do_action.rb` | Natural language intent routing with Tier 0 fast path |
315
- | `lib/legion/mcp/tools/discover_tools.rb` | Dynamic tool discovery with context |
316
- | `lib/legion/mcp/tools/run_task.rb` | Execute runner function via dot notation |
317
- | `lib/legion/mcp/tools/plan_action.rb` | Agentic planning with action decomposition |
318
- | `lib/legion/mcp/tools/skills.rb` | Skill list/describe/invoke/cancel tools |
319
- | `lib/legion/mcp/tools/structural_index.rb` | Query precomputed structural index |
320
- | `lib/legion/mcp/tools/tool_audit.rb` | Audit registered tools quality |
321
- | `lib/legion/mcp/tools/state_diff.rb` | Changed system state since timestamp |
322
- | `lib/legion/mcp/tools/search_sessions.rb` | Search past conversation sessions |
323
- | `lib/legion/mcp/resources/runner_catalog.rb` | `legion://runners` resource |
324
- | `lib/legion/mcp/resources/extension_info.rb` | `legion://extensions/{name}` resource template |
341
+ Useful source entry points:
342
+
343
+ - [`lib/legion/mcp.rb`](lib/legion/mcp.rb) — requires MCP and registers the `:mcp` and `:codegen` settings payloads.
344
+ - [`lib/legion/mcp/settings.rb`](lib/legion/mcp/settings.rb) — default settings and self-generation settings.
345
+ - [`lib/legion/mcp/server.rb`](lib/legion/mcp/server.rb) — server construction, registry, resources, and per-call governance checks.
346
+ - [`lib/legion/mcp/tool_adapter.rb`](lib/legion/mcp/tool_adapter.rb) — registry-entry adaptation and dispatch selection.
347
+ - [`lib/legion/mcp/deferred_registry.rb`](lib/legion/mcp/deferred_registry.rb) — deferred descriptors and schema resolution.
348
+ - [`lib/legion/mcp/client/`](lib/legion/mcp/client/) — federation registry, pool, and connections.
349
+ - [`lib/legion/mcp/tier_router.rb`](lib/legion/mcp/tier_router.rb) and [`lib/legion/mcp/patterns/`](lib/legion/mcp/patterns/) — routing and pattern storage.
350
+ - [MCP Ruby SDK](https://github.com/modelcontextprotocol/ruby-sdk) — protocol and transport implementation.
351
+ - [LegionIO](https://github.com/LegionIO/LegionIO) — framework CLI and runtime integration.
325
352
 
326
353
  ## License
327
354
 
@@ -26,7 +26,7 @@ module Legion
26
26
  module_function
27
27
 
28
28
  def enabled?
29
- Legion::Settings[:mcp][:deferred_loading][:enabled] != false
29
+ Legion::Settings.dig(:mcp, :deferred_loading, :enabled) != false
30
30
  end
31
31
 
32
32
  def always_loaded_tools
@@ -35,7 +35,7 @@ module Legion
35
35
  always_entries = Legion::Settings::Extensions.filter_tools(deferred: false)
36
36
  base |= always_entries.map { |e| Legion::MCP::ToolAdapter.sanitize_tool_name(e[:name]) } if always_entries.is_a?(Array)
37
37
  end
38
- custom = Legion::Settings[:mcp][:deferred_loading][:always_loaded]
38
+ custom = Legion::Settings.dig(:mcp, :deferred_loading, :always_loaded)
39
39
  custom.is_a?(Array) ? (base | custom) : base
40
40
  end
41
41
 
@@ -47,11 +47,7 @@ module Legion
47
47
  end
48
48
 
49
49
  def deferred_entry(tool_class)
50
- { name: tool_class.tool_name, description: tool_class.description }
51
- end
52
-
53
- def full_entry(tool_class)
54
- tool_class.to_h
50
+ tool_class.to_h.slice(:name, :description, :inputSchema)
55
51
  end
56
52
 
57
53
  def build_tools_list(tool_classes)
@@ -62,7 +58,7 @@ module Legion
62
58
  deferred_count += 1
63
59
  deferred_entry(tc)
64
60
  else
65
- full_entry(tc)
61
+ tc.to_h
66
62
  end
67
63
  end
68
64
  log.debug("[mcp][deferred] action=build_tools_list total=#{result.size} " \