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.
- checksums.yaml +4 -4
- data/AGENTS.md +192 -26
- data/CHANGELOG.md +13 -0
- data/CLAUDE.md +196 -108
- data/README.md +253 -226
- data/lib/legion/mcp/deferred_registry.rb +4 -8
- data/lib/legion/mcp/server.rb +41 -29
- data/lib/legion/mcp/settings.rb +32 -15
- data/lib/legion/mcp/tool_governance.rb +1 -1
- data/lib/legion/mcp/tools/discover_tools.rb +4 -4
- data/lib/legion/mcp/version.rb +1 -1
- metadata +1 -1
data/README.md
CHANGED
|
@@ -1,215 +1,145 @@
|
|
|
1
1
|
# legion-mcp
|
|
2
2
|
|
|
3
|
-
Model Context Protocol (MCP) server
|
|
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
|
-
**
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
17
|
+
gem 'legion-mcp', '~> 0.9', '>= 0.9.3'
|
|
21
18
|
```
|
|
22
19
|
|
|
23
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
30
|
+
### Standalone stdio
|
|
73
31
|
|
|
74
|
-
|
|
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
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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
|
-
|
|
43
|
+
require 'legion/mcp'
|
|
44
|
+
require 'mcp/server/transports/stdio_transport'
|
|
83
45
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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
|
-
|
|
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
|
-
|
|
52
|
+
### LegionIO CLI
|
|
92
53
|
|
|
93
|
-
|
|
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
|
-
|
|
56
|
+
```bash
|
|
57
|
+
legionio serve mcp stdio
|
|
58
|
+
legionio serve mcp http --host 127.0.0.1 --port 9393
|
|
59
|
+
```
|
|
98
60
|
|
|
99
|
-
|
|
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
|
-
|
|
63
|
+
## What is registered by default
|
|
102
64
|
|
|
103
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
88
|
+
The server builds MCP tools from three sources:
|
|
152
89
|
|
|
153
|
-
|
|
154
|
-
Legion::
|
|
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
|
-
|
|
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
|
-
|
|
96
|
+
The server also registers:
|
|
161
97
|
|
|
162
|
-
|
|
98
|
+
- `legion://runners`, an application runner catalog; and
|
|
99
|
+
- `legion://extensions/{name}`, an extension information resource template.
|
|
163
100
|
|
|
164
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
180
|
-
|
|
109
|
+
```json
|
|
110
|
+
{
|
|
111
|
+
"tool_names": ["legion.skill.describe"],
|
|
112
|
+
"schema": true
|
|
113
|
+
}
|
|
181
114
|
```
|
|
182
115
|
|
|
183
|
-
|
|
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
|
-
|
|
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
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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
|
-
|
|
125
|
+
The entrypoint calls:
|
|
200
126
|
|
|
201
127
|
```ruby
|
|
202
|
-
|
|
203
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
254
|
-
|
|
255
|
-
|
|
|
256
|
-
|
|
|
257
|
-
| `
|
|
258
|
-
| `
|
|
259
|
-
| `
|
|
260
|
-
| `legion-
|
|
261
|
-
| `legion-
|
|
262
|
-
| `legion-
|
|
263
|
-
|
|
264
|
-
|
|
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
|
|
291
|
-
bundle exec rubocop -A
|
|
292
|
-
bundle exec rubocop
|
|
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
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
61
|
+
tc.to_h
|
|
66
62
|
end
|
|
67
63
|
end
|
|
68
64
|
log.debug("[mcp][deferred] action=build_tools_list total=#{result.size} " \
|