legion-mcp 0.9.1 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 79ba0ac270a1e93bfb9558d37194307398336a43d759c7a9457daa28ca2e01a6
4
- data.tar.gz: d97d87371fe9b4127d07a907abbd3b623015ce58be95425229eb17f9ad1885d6
3
+ metadata.gz: 5cffd8ebeca0dcb045542c91390ce37b824441aded4ceb0e34351ba6ec65a514
4
+ data.tar.gz: c4730925a599288c49f49a5ff9b65a4a65e226336e357b1ada950e13c1f76eed
5
5
  SHA512:
6
- metadata.gz: 633cef5680447266ec2276df835d4f571f3d3d7ece699c857e26cf2f2208d1823d655d2c9d8ecdf3a0431beaea0761d6c0fa0752fe92e134c7d82bede4f62c79
7
- data.tar.gz: 66ccd7b86d37ecb681c1fe83dd719c2fff4daa45a6b67bf4c9cd8eef5d51aa444068d8cb6f4edf24bf7271cdadb6eced92cc91eccaabe4326c6bc92b8cef1b54
6
+ metadata.gz: 53eeac0052765ecd224bf5f9e7d0a1bc60b18134bc194952c9819abb965c16b350d41c5f209e57d3bfe4639dc72da93b5f816c69a70a48fc6f66d3271f59e419
7
+ data.tar.gz: 9a2ba8aa5be470246b2639cf6ddd52654777f0da48316b07ffac8a76b91158bd8e21fa90a8bd4b9bb5d4e6676773dc9067d04e064379fb92a81a3920220c915f
@@ -6,13 +6,9 @@ updates:
6
6
  interval: weekly
7
7
  day: monday
8
8
  open-pull-requests-limit: 5
9
- labels:
10
- - "type:dependencies"
11
9
  - package-ecosystem: github-actions
12
10
  directory: /
13
11
  schedule:
14
12
  interval: weekly
15
13
  day: monday
16
14
  open-pull-requests-limit: 5
17
- labels:
18
- - "type:dependencies"
@@ -8,13 +8,17 @@ on:
8
8
 
9
9
  jobs:
10
10
  ci:
11
- uses: LegionIO/.github/.github/workflows/ci.yml@main
11
+ uses: LegionIO/.github/.github/workflows/ci.yml@e0fc7364b73f446d4cb9bdc162a66ed34bf0daa7
12
+ with:
13
+ companion-gems: ${{ github.event_name == 'pull_request' && '{"legion-settings":{"repository":"LegionIO/legion-settings","ref":"8e73a9ef3c13958e3e1e7fc98532e41283159706"}}' || '{}' }}
12
14
 
13
15
  lint:
14
16
  uses: LegionIO/.github/.github/workflows/lint-patterns.yml@main
15
17
 
16
18
  security:
17
- uses: LegionIO/.github/.github/workflows/security-scan.yml@main
19
+ uses: LegionIO/.github/.github/workflows/security-scan.yml@e0fc7364b73f446d4cb9bdc162a66ed34bf0daa7
20
+ with:
21
+ companion-gems: ${{ github.event_name == 'pull_request' && '{"legion-settings":{"repository":"LegionIO/legion-settings","ref":"8e73a9ef3c13958e3e1e7fc98532e41283159706"}}' || '{}' }}
18
22
 
19
23
  version-changelog:
20
24
  uses: LegionIO/.github/.github/workflows/version-changelog.yml@main
data/AGENTS.md CHANGED
@@ -1,37 +1,203 @@
1
- # legion-mcp Agent Notes
1
+ # legion-mcp Maintainer Guide
2
2
 
3
- ## Scope
3
+ `legion-mcp` is a LegionIO **core library**, not a LEX extension. It builds the `legion`
4
+ MCP SDK server and contains client-side remote-server integration. See [README.md](README.md)
5
+ for installation, operator configuration, transports, and capability limits. Keep `CLAUDE.md`
6
+ and `AGENTS.md` byte-for-byte identical; neither is a separate policy layer.
4
7
 
5
- `legion-mcp` is the standalone MCP server gem for Legion. It owns tool/resource registration, tier routing, tool governance, semantic matching, and observation/pattern promotion.
8
+ ## Architecture and entrypoints
6
9
 
7
- ## Fast Start
10
+ | Path | Responsibility |
11
+ |---|---|
12
+ | [`lib/legion/mcp.rb`](lib/legion/mcp.rb) | `Legion::MCP.server` (memoized), `server_for(token:, identity:)`, `reset!`; optional integration loading |
13
+ | [`lib/legion/mcp/settings.rb`](lib/legion/mcp/settings.rb) | Flat MCP defaults and separate code-generation defaults; explicit framework merges |
14
+ | [`lib/legion/mcp/server.rb`](lib/legion/mcp/server.rb) | `Server.build`, authoritative registry, SDK server context, listing/invocation wrappers, tracing and audit |
15
+ | [`lib/legion/mcp/auth.rb`](lib/legion/mcp/auth.rb), [`tool_governance.rb`](lib/legion/mcp/tool_governance.rb) | Token authentication; independent live role/risk filtering |
16
+ | [`lib/legion/mcp/tools_loader.rb`](lib/legion/mcp/tools_loader.rb), [`tools/`](lib/legion/mcp/tools/) | Tool class loading and implementations; loading is not registration |
17
+ | [`lib/legion/mcp/function_discovery.rb`](lib/legion/mcp/function_discovery.rb), [`tool_adapter.rb`](lib/legion/mcp/tool_adapter.rb), [`catalog_dispatcher.rb`](lib/legion/mcp/catalog_dispatcher.rb) | Framework tool discovery, registry adapters, and runner dispatch through `Legion::Ingress` |
18
+ | [`lib/legion/mcp/deferred_registry.rb`](lib/legion/mcp/deferred_registry.rb), [`tools/discover_tools.rb`](lib/legion/mcp/tools/discover_tools.rb) | Protocol descriptors and identity-scoped schema lookup |
19
+ | [`lib/legion/mcp/context_compiler.rb`](lib/legion/mcp/context_compiler.rb), [`embedding_index.rb`](lib/legion/mcp/embedding_index.rb) | Keyword and optional semantic matching |
20
+ | [`lib/legion/mcp/tier_router.rb`](lib/legion/mcp/tier_router.rb), [`context_guard.rb`](lib/legion/mcp/context_guard.rb) | Confidence routing, cached-chain execution, staleness/rapid-fire/anomaly guards |
21
+ | [`lib/legion/mcp/observer.rb`](lib/legion/mcp/observer.rb), [`patterns/`](lib/legion/mcp/patterns/) | Usage observations, successful intent/tool learning, pattern compilation/storage/exchange |
22
+ | [`lib/legion/mcp/tracing_context.rb`](lib/legion/mcp/tracing_context.rb), [`audit.rb`](lib/legion/mcp/audit.rb), [`transport/`](lib/legion/mcp/transport/) | Request-local tracing and optional audit publication |
23
+ | [`lib/legion/mcp/resources/`](lib/legion/mcp/resources/) | Runner catalog and extension resources |
24
+ | [`lib/legion/mcp/client.rb`](lib/legion/mcp/client.rb), [`client/`](lib/legion/mcp/client/) | Remote-server configuration, connection lifecycle, pooling, and tool calls |
25
+ | [`lib/legion/mcp/self_generate.rb`](lib/legion/mcp/self_generate.rb), [`actors/`](lib/legion/mcp/actors/) | Optional self-generation integration |
8
26
 
9
- ```bash
10
- bundle install
11
- bundle exec rspec
12
- bundle exec rubocop -A
13
- bundle exec rubocop
27
+ The CLI is owned by the separate LegionIO gem: `legionio serve mcp stdio` or
28
+ `legionio serve mcp http`. This gem alone is not an HTTP hosting or authentication policy.
29
+ Runtime dependency versions are authoritative in [legion-mcp.gemspec](legion-mcp.gemspec):
30
+ Ruby >= 3.4 and MCP SDK >= 1.9, < 2. Check the installed SDK contract before changing wrappers.
31
+
32
+ ## Settings and real boot
33
+
34
+ `Legion::MCP::Settings.default` returns the **contents of `:mcp`**, not a multi-root tree.
35
+ Requiring `legion/mcp` loads `settings.rb`, which registers these two payloads explicitly:
36
+
37
+ ```ruby
38
+ Legion::Settings.merge_settings(:mcp, Legion::MCP::Settings.default)
39
+ Legion::Settings.merge_settings(:codegen, Legion::MCP::Settings.codegen)
14
40
  ```
15
41
 
16
- ## Primary Entry Points
42
+ Keep `Settings.codegen` separate (`self_generate` belongs under `:codegen`). Do not introduce
43
+ plural `defaults`, a namespace registration loop, or the LEX `default_settings` convention.
44
+ Include every consumed MCP top-level section in the default payload so real framework
45
+ `Legion::Settings.validate!` accepts configured auth, governance, roles, tier0, and cold_start.
46
+ Preserve preloaded configuration when registering defaults.
47
+
48
+ Optional configuration is nullable: exercise absent/nil `:mcp`, absent/nil `:deferred_loading`,
49
+ and nil `enabled`/`always_loaded`. Deferral remains enabled unless explicitly `false`; custom
50
+ always-loaded names are used only when configured as an array. Nullable configuration must
51
+ not lose captured identity, break listing, or remove argument schemas. Role semantics are
52
+ separate: missing/unknown roles are permissive; an explicitly false role or false tool list
53
+ denies access. Do not reinterpret explicit `false` as missing configuration.
54
+
55
+ Boot regressions belong in [`spec/legion/mcp/settings_boot_spec.rb`](spec/legion/mcp/settings_boot_spec.rb).
56
+ Use a fresh Ruby subprocess, isolated HOME/settings environment, the real framework loader,
57
+ optional JSON configuration loaded before `require 'legion/mcp'`, and `Settings.validate!`.
58
+ Assert observable listing/auth/configuration and retained-server revocation behavior. Do not
59
+ replace the loader or manually merge defaults in the child: that masks missing integration.
60
+ The in-process reset in `spec/spec_helper.rb` is test isolation, not proof of real boot.
61
+
62
+ ## Registry and protocol contracts
63
+
64
+ - `Server::MCP_SPECIFIC_TOOLS` defines ten built-ins: `legion.plan`, `legion.tools`,
65
+ `legion.structural_index`, `legion.tool_audit`, `legion.state_diff`, `legion.search_sessions`,
66
+ and `legion.skill.list`, `.describe`, `.invoke`, `.cancel`.
67
+ - `tools_loader.rb` also requires `legion.do` and job/CRUD classes. Their presence as Ruby
68
+ constants does **not** place them in the default server catalog. Extension/remote entries
69
+ enter through `Legion::Settings::Extensions` and the server registry; do not infer exposure
70
+ from loaded files or server instruction text. Keep registration and cache invalidation
71
+ centralized in the existing server builder/registry APIs.
72
+ - Built-in protocol names use `legion.*`; registry adapters sanitize names. Use the actual
73
+ advertised name, not a guessed universal naming transformation.
74
+ - Every `tools/list` descriptor carries the real `inputSchema`, including required arguments
75
+ and property types. Deferred descriptors trim optional metadata, not schemas. Schema lookup
76
+ returns the full tool definition with the same argument schema, not a placeholder.
77
+ - `Legion::MCP.server` is memoized; use `Legion::MCP.reset!` when a test needs a fresh singleton.
78
+ Registry, settings, observer, and trace state have separate lifetimes: restore only the state
79
+ a test changes, and do not assume resetting the singleton resets everything else.
80
+
81
+ ## Identity, authorization, and SDK boundaries
82
+
83
+ `Server.build` captures identity, conversation ID, and trace ID in each server's context.
84
+ Keep closures bound to that server; module-level `current_identity`/trace fields are not
85
+ execution authority. A later or overlapping build must not change a retained server's caller.
86
+ `DiscoverTools` schema resolution receives identity through the SDK `server_context`.
87
+
88
+ Authentication and supplying trusted identity are different operations. `server_for(identity:)`
89
+ accepts a supplied identity; the host must establish its trust. Auth and risk governance are
90
+ both disabled by default. Role filtering can apply independently of risk governance, and
91
+ missing/unknown roles do not form a deny-by-default policy.
92
+
93
+ Filter listing and recheck live role/risk settings immediately before each SDK tool invocation.
94
+ For tools already registered on a retained server, revoke/regrant and changed risk mappings
95
+ must take effect without rebuilding. Rebuild when the available tool set changes.
96
+ Do not replace invocation checks with a build-time filter, or infer authorization from discovery.
97
+
98
+ The tracing wrapper forwards `call_tool(request, **options)` to the SDK with all keyword options
99
+ intact. Preserve SDK session/auth/scope and cancellation behavior; do not bypass the SDK to call
100
+ classes directly from that wrapper. Preserve the distinction between MCP tool error responses
101
+ (`isError`) and JSON-RPC errors. Unknown tools, invalid arguments, tool exceptions, scope denial,
102
+ and cancellation need protocol-level coverage. Clear request tracing in `ensure`, including
103
+ failures and cancelled calls; audit against the captured caller/session, not global build state.
104
+
105
+ Direct Ruby APIs such as `TierRouter.route` execute outside the SDK invocation wrapper;
106
+ they are not an authorization boundary for untrusted requests.
17
107
 
18
- - `lib/legion/mcp.rb`
19
- - `lib/legion/mcp/server.rb`
20
- - `lib/legion/mcp/context_compiler.rb`
21
- - `lib/legion/mcp/tier_router.rb`
22
- - `lib/legion/mcp/pattern_store.rb`
23
- - `lib/legion/mcp/observer.rb`
24
- - `lib/legion/mcp/tools/`
108
+ ## Optional services and failure behavior
25
109
 
26
- ## Guardrails
110
+ Gem dependencies and connected runtime services are different requirements. `legion-data` is a
111
+ gem dependency, but database connectivity is not required merely to load this library. Backend
112
+ operations still need their actual services/models. Check the individual tool before claiming
113
+ that a successful server build makes it executable.
27
114
 
28
- - Keep optional dependencies guarded (`legion-cache`, `legion-llm`, `Data::Local`); this gem must degrade cleanly.
29
- - Tier confidence behavior is core contract: Tier 0 (>= 0.8), Tier 1 (0.6-0.8), Tier 2 (< 0.6).
30
- - Pattern storage failures must not block tool execution.
31
- - Tool registration remains centralized through server builder/registry; avoid ad hoc registration paths.
32
- - Preserve governance checks and audit trails for tool invocation.
115
+ - Patterns use L0 memory, optional connected `Legion::Cache` at L1, and optional connected
116
+ `Legion::Data::Local` SQLite at L2. Persistence failures call `handle_exception` and degrade;
117
+ they are not silent success and do not establish durable storage.
118
+ - Default semantic embeddings require a started `Legion::LLM`; keyword discovery remains a
119
+ separate path. Skills require `Legion::LLM::Skills::Registry`; invocation additionally needs
120
+ `ConversationStore`, and actual pipeline execution needs its executor/request classes.
121
+ Missing skill services return explicit error or non-executed/queued results as appropriate.
122
+ - Runner catalog dispatch needs `Legion::Ingress`. Optional audit transport needs the transport
123
+ classes loaded and a connected transport. Preserve the existing availability checks rather
124
+ than making all optional integrations mandatory at require time.
125
+ - Remote-server registration/configuration is not evidence of a working connection. Current
126
+ `Client::Connection` limitations with SDK 1.9: an unconnected `tools` call recursively acquires
127
+ the same mutex through `fetch_tools`/`connect` (`ThreadError`); explicit `connect` requests the
128
+ tool list without first calling the SDK client's `connect` (a connect-required error).
129
+ See [`client/connection.rb`](lib/legion/mcp/client/connection.rb). Do not present this wrapper
130
+ as a working federation quick-start. Connection lifecycle and actual SDK transport round
131
+ trips need smoke coverage; metadata or mocked client examples alone do not prove connectivity.
132
+
133
+ Use `Legion::Logging::Helper` and `log.*`; every rescue must log/`handle_exception` or re-raise.
134
+ Keep stdout free of application logs for stdio MCP: configure file logging before requiring
135
+ `legion/mcp` (see the README recipe). Use `Legion::JSON` for application JSON; its loaded keys
136
+ are symbols. Qualify root constants such as `::Process` and any necessary `::JSON` references
137
+ inside the `Legion::` namespace.
138
+
139
+ ## Tier routing and learning
140
+
141
+ `TierRouter.route` executes a cached tool chain only at Tier 0:
142
+
143
+ | Decision | Current behavior |
144
+ |---|---|
145
+ | Confidence >= 0.8 and guards pass | Tier 0: execute the chain and return its response |
146
+ | 0.6 <= confidence < 0.8 | Tier 1: return pattern/reason metadata and `response: nil` |
147
+ | Confidence < 0.6 or no matching pattern | Tier 2: return reason metadata and `response: nil` |
148
+ | Guard rejection or Tier 0 execution exception | Escalate to Tier 1 metadata; log execution failures |
149
+
150
+ Tiers 1/2 do not automatically invoke local/fleet/cloud models. No latency or cost guarantee
151
+ follows from these labels. Guards cover staleness (default 3600 seconds), rapid-fire requests
152
+ (more than 5 within 600 seconds), and repeated misses.
153
+
154
+ `Observer.record_intent_with_result` promotes successful explicit intent/tool observations;
155
+ ordinary tool-call counters alone do not create learned patterns. The default candidate
156
+ threshold is 3 observations, seeded confidence is 0.5, and hit/miss adjustments are +0.02/-0.05.
157
+ A newly promoted pattern is therefore not immediately Tier 0. Test routing boundaries, guard
158
+ escalation, success/failure learning, and observable execution, not just constant equality.
159
+ Changes to these semantics require deliberate contract/spec/documentation updates, not blindly
160
+ changing assertions to match new constants.
161
+
162
+ ## Tests and maintainer workflow
163
+
164
+ Useful entrypoints under [`spec/legion/mcp/`](spec/legion/mcp/):
165
+
166
+ - `settings_boot_spec.rb`, `settings_spec.rb`: real boot and configured-default preservation.
167
+ - `server_authorization_spec.rb`, `server_tracing_spec.rb`, `tool_governance_spec.rb`: retained
168
+ server identity, live grants/risk policy, SDK scope/cancellation/error behavior, trace cleanup.
169
+ - `server_spec.rb`, `deferred_registry_spec.rb`, `tools/discover_tools_spec.rb`: protocol listing,
170
+ real schemas, nullable options, and schema-discovery authority.
171
+ - `tier_router_spec.rb`, `context_guard_spec.rb`, `observer_pattern_promotion_spec.rb`,
172
+ `pattern_store_spec.rb`, `tier0_integration_spec.rb`: routing, learning, persistence boundaries.
173
+ - `client/connection_spec.rb`, `client/connection_tracing_spec.rb`, `client/pool_spec.rb`,
174
+ `client_boot_spec.rb`: remote-client lifecycle and propagation boundaries.
175
+
176
+ The suite loads real Legion libraries but also uses doubles and an ingress fallback; it is not
177
+ universally mock-free and does not prove a live external backend works. Prefer real boot/SDK
178
+ boundary tests where integration is the contract, with controlled doubles for unrelated services.
179
+ Never weaken tests or substitute a manually initialized environment to make a regression pass.
180
+
181
+ For Ruby changes, use the applicable release/RSpec/RuboCop guidance, update version/changelog
182
+ when required, and run these **full-repository** gates from the checkout root once changes land:
183
+
184
+ ```bash
185
+ bundle install
186
+ bundle exec rspec --format json --out tmp/rspec_results.json --format progress --out tmp/rspec_progress.txt
187
+ bundle exec rubocop -A
188
+ bundle exec rubocop
189
+ ```
33
190
 
34
- ## Validation
191
+ Do not substitute targeted specs or file-scoped lint. Inspect failed examples when needed;
192
+ do not dump successful JSON/progress artifacts. Docs-only work should check examples/links and
193
+ `cmp -s CLAUDE.md AGENTS.md`; report only checks actually run. Delegated workers leave integrated
194
+ verification to their owner unless explicitly assigned to run it.
35
195
 
36
- - Run specs for changed tools/router/compiler paths.
37
- - Before handoff, run `bundle exec rspec`, `bundle exec rubocop -A`, then `bundle exec rubocop`.
196
+ Work in the existing development checkout. Preserve unrelated user edits and concurrent work;
197
+ do not reset, overwrite, or relocate them. [Gemfile](Gemfile) may resolve `legion-settings` from
198
+ a companion checkout, so account for the dependency actually used by local development.
199
+ Use explicit staging filenames (`git add README.md CLAUDE.md AGENTS.md` for that exact docs scope),
200
+ never `git add .` or `git add -A`, and never force-push. Do not stage generated lockfiles, gems,
201
+ coverage, or tmp artifacts. Do not add personal/company identifiers. Keep changes scoped, follow
202
+ workspace Ruby conventions, and never modify an already-published migration without explicit
203
+ per-file approval.
data/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # legion-mcp Changelog
2
2
 
3
+ ## [0.9.3] - 2026-11-06
4
+
5
+ ### Security
6
+ - Recheck live role and risk-tier policy before each tool invocation so revoked tools cannot execute through an existing server.
7
+ - Keep identity and tracing context scoped to each server for tool listings, schema discovery, and invocation audits.
8
+
9
+ ### Fixed
10
+ - Expose the flat core-library `Settings.default` payload and merge MCP and code-generation settings explicitly through the framework's `merge_settings` API.
11
+ - Declare authentication, governance, role, tier-guard, cold-start, and self-generation interval settings so configured MCP installations pass framework validation.
12
+ - Preserve default deferred-loading behavior when optional MCP configuration or its deferred-loading section is null.
13
+ - Include the real input schema and required arguments in deferred tool descriptors for MCP client compatibility.
14
+ - Configure an explicit log-file destination before loading the standalone stdio server so diagnostics cannot corrupt JSON-RPC stdout.
15
+
16
+ ## [0.9.2] - 2026-10-30
17
+
18
+ ### Security
19
+ - Exclude MCP SDK versions affected by OAuth discovery SSRF advisory GHSA-4m5j-jjfc-97gx.
20
+
21
+ ### Fixed
22
+ - Forward the complete SDK tool-call context through tracing, including authentication, cancellation, and request-envelope keywords.
23
+ - Declare the Base64 dependency required by the SDK OAuth client on Ruby versions where it is no longer bundled.
24
+ - Return the protocol `tools/list` result object rather than an unwrapped array with the supported SDK.
25
+ - Register MCP and code-generation defaults in their canonical Settings namespaces; read deferred-loading configuration live instead of caching it across configuration changes.
26
+ - Preserve explicit `false` role and tool permissions as denials rather than falling through to unrestricted tools.
27
+
28
+ ### Changed
29
+ - Raise the MCP SDK dependency from `~> 1.2` to `~> 1.9` (`>= 1.9.0, < 2.0`).
30
+ - Exercise the supported SDK with the real Legion logging helper in the test suite instead of a no-op replacement.
31
+
3
32
  ## [0.9.1] - 2026-04-30
4
33
 
5
34
  ### Fixed