@nest-mcp/manager 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,90 @@
1
+ # @nest-mcp/manager
2
+
3
+ ## 2.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 4ddbd56: First stable release of the 2.x line. The packages build on the v2 MCP TypeScript SDK, implement the `2026-07-28` protocol revision, target NestJS 12 and Node.js 22.13 or newer, and are ESM-only. From this release the line follows Semantic Versioning: no breaking changes to the public API within 2.x.
8
+
9
+ The 1.x line stays available under a `1` version range (`@nest-mcp/server@1`, `@nest-mcp/client@1`, `@nest-mcp/gateway@1`). 2.x has a different package layout and API, so moving to it is a migration rather than an in-place upgrade.
10
+
11
+ ### Minor Changes
12
+
13
+ - fea134c: Add `McpRuntimeOwnership`, a framework-neutral bounded coordinator for shared opaque runtime
14
+ generations. Cooperative final release, force-retirement fencing, manager-retirement barriers,
15
+ idempotent owner settlement, manager-close handling, aggregate cleanup failures, and key-free
16
+ snapshots and errors let hosts delete projection-ownership bookkeeping without moving durable state
17
+ or product policy into the SDK.
18
+ - fea134c: Add immediate bounded admission for concurrent isolated operations keyed by a host-owned connector identity. Preserve exclusive ordering across generations, cancellation, close-before-settlement, and quarantine after uncertain cleanup. Hosts must supply the same admission key to all isolated operations for a connector and explicitly authorize independent concurrency.
19
+ - fea134c: Add an explicit exclusive operation lease mode for non-pooled, close-before-settlement managed MCP
20
+ runtimes, including same-generation conflict fencing and retirement coverage. Shared catalog refresh
21
+ now waits for every parallel discovery request before releasing its lease, while exclusive refresh
22
+ serializes those requests for minimal OAuth providers. The public docs identify `refreshCatalog`
23
+ plus `digestMcpRuntimeCatalog` as the generic freshness/change boundary.
24
+ - fea134c: Add a published, framework-neutral manager for bounded dynamic MCP client generations, including
25
+ deterministic draining, cleanup quarantine, key-free state lifecycle subscriptions, catalog and
26
+ operation delegation, a lease-scoped client-runtime integration callback, and optional lifecycle
27
+ observation for every managed client runtime.
28
+
29
+ Expose a thin Nest adapter at `@nest-mcp/nestjs/manager` with synchronous and asynchronous module
30
+ configuration, provider-token generation resolvers and observers, an injectable manager service,
31
+ and deterministic module shutdown.
32
+
33
+ - fea134c: Publish `MCP_RUNTIME_PHASES` and `MCP_RUNTIME_PROTOCOL_ERAS` as frozen tuples that mirror the
34
+ `McpRuntimePhase` and `McpRuntimeProtocolEra` unions through a compile-time exhaustiveness fence,
35
+ together with `mcpRuntimeStateSnapshotSchema`, `mcpRuntimeProbeSnapshotSchema`, and
36
+ `mcpRuntimeCapabilitiesSnapshotSchema`. The validators implement Standard Schema v1 without adding
37
+ a runtime dependency: they accept exactly what the manager emits, reject unknown properties and
38
+ unpublished phases, eras, or state error codes, and return a frozen normalized snapshot so hosts
39
+ can validate persisted projections on the way back in.
40
+
41
+ Accept an `McpRuntimeToolCallOptions` object as the fourth `callTool` argument. A positional
42
+ `AbortSignal` stays source compatible as the cancellation-only form, and pinning `toolDefinition`
43
+ threads that exact definition to the managed client runtime so structured output is validated
44
+ against it instead of a cached `tools/list` view. `McpManagerService` from `@nest-mcp/nestjs/manager`
45
+ inherits the widened call surface.
46
+
47
+ - fea134c: Add opt-in bounded FIFO admission for exclusive operations with `exclusiveContention: "queue"`.
48
+ Concurrent callers each acquire fresh admitted transport material after prior cleanup, while the
49
+ existing exclusive default remains fail-fast. Queue waiting shares the request deadline, respects
50
+ caller cancellation, and is fenced by retirement, shutdown, and cleanup quarantine. Expose a global
51
+ `maxQueuedOperations` bound and key-free queue diagnostics.
52
+
53
+ Add `awaitCleanupOnCancel` to client lease acquisition. Exclusive manager operations select it so
54
+ cancellation during acquisition drains their abandoned material before a queued operation starts;
55
+ ordinary client acquisitions retain immediate, caller-local cancellation by default.
56
+
57
+ ### Patch Changes
58
+
59
+ - fea134c: Preserve the waiting caller's async context when a different caller releases capacity and wakes transport allocation. Tenant context and request-local diagnostics remain attached to the admitted caller.
60
+ - fea134c: Add opt-in bounded concurrent admission across process and connector capacity, nullable connector ceilings, fair FIFO scheduling across connector keys, and distinct queue-full and admission-timeout diagnostics. Reserve transports against the existing lease ledger and retain charges through cleanup; cancellation, retirement, and shutdown remove queued work without redispatch. Expose key-free admission timing and capacity notifications.
61
+ - fea134c: Expose an awaited admitted-generation onConnected hook with the immutable negotiated state so hosts can retain connection observations without extending runtime leases or probing twice.
62
+ - Updated dependencies [4ddbd56]
63
+ - Updated dependencies [fea134c]
64
+ - Updated dependencies [fea134c]
65
+ - Updated dependencies [fea134c]
66
+ - Updated dependencies [fea134c]
67
+ - Updated dependencies [fea134c]
68
+ - Updated dependencies [fea134c]
69
+ - Updated dependencies [fea134c]
70
+ - Updated dependencies [fea134c]
71
+ - Updated dependencies [fea134c]
72
+ - Updated dependencies [fea134c]
73
+ - Updated dependencies [fea134c]
74
+ - Updated dependencies [fea134c]
75
+ - Updated dependencies [fea134c]
76
+ - Updated dependencies [fea134c]
77
+ - Updated dependencies [fea134c]
78
+ - Updated dependencies [fea134c]
79
+ - Updated dependencies [fea134c]
80
+ - Updated dependencies [fea134c]
81
+ - Updated dependencies [fea134c]
82
+ - Updated dependencies [fea134c]
83
+ - @nest-mcp/core@2.0.0
84
+ - @nest-mcp/client@2.0.0
85
+
86
+ ## 2.0.0-alpha.0
87
+
88
+ ### Major Changes
89
+
90
+ - First prerelease of the 2.x line, built on the official MCP TypeScript SDK v2 and NestJS 12.
package/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, btwld
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,256 @@
1
- # Temporary Holding Version
1
+ # `@nest-mcp/manager`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A framework-neutral, process-local lifecycle manager for dynamic MCP client generations.
4
+
5
+ It accepts only an opaque generation key and a host-owned resolver that returns already-admitted
6
+ transport material. Connection records, endpoints, credentials, tenancy, approval policy, and
7
+ persistence remain in the host application.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ pnpm add @nest-mcp/manager @nest-mcp/client @modelcontextprotocol/client
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { McpRuntimeManager } from "@nest-mcp/manager";
19
+
20
+ const manager = new McpRuntimeManager({
21
+ generationResolver: {
22
+ async resolve(generationKey, signal) {
23
+ const admitted = await resolveAdmittedTransport(generationKey, signal);
24
+ return {
25
+ transport: admitted.transport,
26
+ close: () => admitted.close(),
27
+ };
28
+ },
29
+ },
30
+ maxConnections: 16,
31
+ maxStateEntries: 1_000,
32
+ shutdownTimeoutMs: 30_000,
33
+ });
34
+
35
+ await manager.ensureOnline("opaque-generation-capability");
36
+ const catalog = await manager.refreshCatalog("opaque-generation-capability");
37
+ await manager.close();
38
+ ```
39
+
40
+ ## Shared and exclusive operation leases
41
+
42
+ The ordinary manager path is generation-shared. `ensureOnline(key)` retains a keeper, and calls for
43
+ that key reuse its connected runtime until `setOffline()` or `retire()` drains it. This is suitable
44
+ only when the admitted transport and every attached collaborator are safe to pool.
45
+
46
+ Use `leaseMode: "exclusive"` when one operation must own a fresh runtime and close it before the
47
+ operation promise settles:
48
+
49
+ ```ts
50
+ const result = await manager.callTool(
51
+ "opaque-generation-capability",
52
+ "search",
53
+ { query: "lease fencing" },
54
+ {
55
+ leaseMode: "exclusive",
56
+ toolDefinition: approvedDefinition,
57
+ },
58
+ );
59
+ ```
60
+
61
+ An exclusive operation does not require `ensureOnline()`. It receives a unique internal lease
62
+ identity, never joins another acquisition, and holds its global `maxConnections` slot through
63
+ runtime and admitted-material cleanup. Shared or second exclusive work for the same generation
64
+ fails with `MCP_LEASE_MODE_CONFLICT`; the manager does not hide contention behind an unbounded
65
+ queue. Retirement and shutdown still abort the operation and wait for its lease cleanup. A cleanup
66
+ failure remains quarantined and capacity-charging.
67
+
68
+ For concurrent callers that must each use a fresh transport, opt into bounded FIFO waiting:
69
+
70
+ ```ts
71
+ const result = await manager.callTool(
72
+ generationKey,
73
+ "search",
74
+ { query },
75
+ {
76
+ leaseMode: "exclusive",
77
+ exclusiveContention: "queue",
78
+ signal,
79
+ },
80
+ );
81
+ ```
82
+
83
+ Queued callers wait only behind exclusive operations of the same generation. Each caller resolves
84
+ fresh admitted material after the prior operation's runtime and material have fully closed; no
85
+ request or result is reused or retried. `requestTimeoutMs` includes queue waiting, admission, and
86
+ execution. Caller cancellation removes just that waiter. `setOffline`, `retire`, and `close` reject
87
+ pending waiters before they can start; uncertain cleanup rejects them as quarantined. Shared work
88
+ or an online keeper remains a lease-mode conflict even when waiting is requested.
89
+
90
+ `maxQueuedOperations` bounds waiting callers across all generations (default 100). Excess callers
91
+ receive `MCP_CAPACITY_EXCEEDED`. Waiting does not consume a connection slot, while active transports
92
+ remain bounded by `maxConnections` through cleanup. `snapshot().queuedOperationCount` reports
93
+ waiting callers without exposing generation identities. The ordinary exclusive default remains
94
+ fail-fast.
95
+
96
+ This is the manager-side close-on-release primitive for a credential-bound transport that cannot
97
+ provide request-correlated OAuth refresh fencing. Do not also retain that generation with
98
+ `ensureOnline()`. A host that supplies request-correlated refresh and exact revision fencing may
99
+ use the ordinary shared mode instead. Generation keys stay opaque and non-secret in either mode.
100
+
101
+ `probe`, `refreshCatalog`, `withClientRuntime`, `callTool`, `readResource`, and `getPrompt` accept the
102
+ same operation options (or the existing positional `AbortSignal`). `withClientRuntime` remains the
103
+ generic route to other protocol methods under an exclusive lease; its callback must not start
104
+ parallel credentialed requests when it relies on the minimal OAuth provider's no-concurrency
105
+ alternative. The manager-owned exclusive catalog refresh runs its list requests sequentially for
106
+ that reason.
107
+
108
+ ## Catalog freshness and change detection
109
+
110
+ An admitted generation may provide `onConnected(snapshot, signal)`. The manager awaits it once
111
+ after successful negotiation and before handing the runtime to an operation. The frozen snapshot
112
+ contains the negotiated protocol version, era, capabilities, and connection timestamp. Hosts can
113
+ persist a last observation there without keeping a runtime online or making a second probe.
114
+ Connection records, timestamp ordering, configuration invalidation, and persistence remain host
115
+ policy. This callback is part of acquisition: rejection closes the runtime and admitted material;
116
+ best-effort persistence must catch its own errors. Honor the generation signal and keep work bounded.
117
+ Ordinary operation cleanup still transitions the current state to offline and removes its active
118
+ connection metadata. The hook does not change that lifecycle or the key-free metrics event contract.
119
+
120
+ `refreshCatalog(key, options)` is the reusable freshness seam. It performs protocol liveness first,
121
+ forces every supported list delegate through `cacheMode: "refresh"`, applies the configured page and
122
+ item bounds, and only then releases the generation lease. Shared mode runs the list wave in parallel
123
+ but waits for every request to settle before release; exclusive mode runs it sequentially so one
124
+ minimal OAuth bridge never has concurrent credentialed requests. The frozen `discoveredAt` timestamp
125
+ is recorded after the complete successful wave.
126
+
127
+ The manager deliberately does not persist a baseline or turn list-change notifications into product
128
+ state. Compare snapshots with `digestMcpRuntimeCatalog` from `@nest-mcp/conformance`; that canonical,
129
+ domain-separated digest is the change seam for approval, persistence, or scheduling owned by the
130
+ host. Credential-bound refreshes can combine both guarantees:
131
+
132
+ ```ts
133
+ const catalog = await manager.refreshCatalog("opaque-generation-capability", {
134
+ leaseMode: "exclusive",
135
+ });
136
+ const digest = digestMcpRuntimeCatalog(catalog, {
137
+ domain: "example/mcp/catalog/v1",
138
+ toolSchemaDomain: "example/mcp/tool-schema/v1",
139
+ });
140
+ ```
141
+
142
+ ## Shared runtime ownership
143
+
144
+ Use `McpRuntimeOwnership` when several host projections can retain the same opaque manager
145
+ generation. It composes the manager's existing `retire()` port without taking over product records,
146
+ key construction, admission, tenancy, or persistence:
147
+
148
+ ```ts
149
+ import { McpRuntimeManager, McpRuntimeOwnership } from "@nest-mcp/manager";
150
+
151
+ const manager = new McpRuntimeManager({
152
+ generationResolver,
153
+ maxConnections: 16,
154
+ });
155
+ const ownership = new McpRuntimeOwnership({
156
+ manager,
157
+ maxOwners: 1_000,
158
+ maxGenerations: 1_000,
159
+ maxReferences: 10_000,
160
+ });
161
+
162
+ const workspaceProjection = ownership.createOwner();
163
+ await workspaceProjection.retain("opaque-generation-capability");
164
+
165
+ // The final cooperative owner release retires the manager generation.
166
+ await workspaceProjection.release();
167
+ ```
168
+
169
+ An owner-to-generation retention is idempotent. Concurrent calls for the same owner and key share
170
+ one task. If an older retirement is unsettled, `retain()` waits for that barrier and rechecks the
171
+ owner and generation before it acquires, so consumers do not implement a retry race. Releasing an
172
+ owner is terminal and repeated calls share one settlement. If several final retirements fail,
173
+ `release()` rejects with an `AggregateError` containing only fixed, generation-key-free ownership
174
+ errors; failed cleanup remains fenced and charged against `maxGenerations`.
175
+
176
+ `forceRetire(key)` immediately revokes every current reference and fences every owner that existed
177
+ when the force began. An owner created after that boundary may reuse an equal `Map` key only after
178
+ the manager retirement fully settles; old retirement work can therefore never overlap its
179
+ replacement. A manager-closed result counts as settled because manager shutdown already owns every
180
+ runtime generation.
181
+
182
+ Reversible desired-state transitions stay separate: call `manager.setOffline(key)` without
183
+ releasing the owner, then call `manager.ensureOnline(key)` when the host wants that retained
184
+ generation online again. Ownership finalization and `forceRetire()` call only `manager.retire()`.
185
+ `snapshot()` reports bounded aggregate counts and never emits generation keys or manager failures.
186
+
187
+ `subscribe(listener)` emits key-free, bounded state transitions. Pass an optional
188
+ `McpLifecycleObserver` as `observer` to observe operations performed by each managed
189
+ `McpClientRuntime`. Runtime server names are random and never derived from the generation key;
190
+ telemetry exporters should omit operation targets when aggregating across dynamic generations.
191
+
192
+ `callTool(generationKey, name, arguments, options)` accepts either a positional `AbortSignal` or an
193
+ `McpRuntimeToolCallOptions` object. Pinning `toolDefinition` keeps the managed client runtime's
194
+ structured output validation bound to that exact definition instead of its cached `tools/list`
195
+ view, so a host that already holds an approved definition never validates a result against a
196
+ drifted schema.
197
+
198
+ Retained state is bounded by `maxStateEntries` (1,000 by default and always at least
199
+ `maxConnections`). Live and quarantined projections are protected; older offline or failed
200
+ diagnostics are evicted first. State listeners still receive each bounded transition event even
201
+ when its projection cannot be retained.
202
+
203
+ `MCP_RUNTIME_PHASES` and `MCP_RUNTIME_PROTOCOL_ERAS` publish every lifecycle phase and negotiated
204
+ protocol era as frozen tuples for hosts that persist state projections. The matching
205
+ `mcpRuntimeStateSnapshotSchema`, `mcpRuntimeProbeSnapshotSchema`, and
206
+ `mcpRuntimeCapabilitiesSnapshotSchema` validators implement [Standard
207
+ Schema](https://standardschema.dev) v1 with no added runtime dependency: they accept exactly what
208
+ the manager emits, reject unknown properties, and return a frozen normalized snapshot.
209
+
210
+ Cleanup failures quarantine and continue charging the affected generation against the configured
211
+ capacity. Runtime cleanup runs before admitted-material cleanup, and both are bounded by
212
+ `shutdownTimeoutMs`; a timed-out host `close()` remains quarantined. The manager is in memory only
213
+ and implements both `close()` and `AsyncDisposable`.
214
+
215
+ ## Concurrent isolated operations
216
+
217
+ Use `leaseMode: "concurrent"` with an opaque `admissionKey` for host-authorized independent
218
+ operations. Each admitted call creates its own client and closes it before settlement; no online
219
+ keeper or shared session is retained. The default `maxConcurrentOperationsPerAdmissionKey` is four;
220
+ set it to `null` to use only process capacity. A call's `maxConcurrentOperations` can override this
221
+ with a positive integer or `null`. Across related active calls, the strictest supplied ceiling
222
+ applies, including calls from older configuration generations.
223
+
224
+ Opt into `concurrentContention: "queue"` to wait for both connector and process capacity before
225
+ allocating a transport. Without this option, saturation returns `MCP_CAPACITY_EXCEEDED` immediately.
226
+ One transport ledger charges acquisition, execution, cleanup, and failed cleanup against
227
+ `maxConnections`. Waiting neither restarts the operation deadline nor redispatches an operation.
228
+
229
+ Queued calls rotate fairly across connector keys and remain FIFO within each key. A blocked
230
+ connector does not block eligible work for another connector. The queue is bounded by
231
+ `maxQueuedOperations` (100 by default). Queue overflow returns `MCP_QUEUE_FULL`; expiry before
232
+ admission returns `MCP_ADMISSION_TIMEOUT`. Cancellation removes the waiter immediately. The
233
+ optional per-call `onAdmission` observer receives outcome, elapsed admission time, queued count,
234
+ and occupied connection count, without keys, credentials, or provider payloads. Observer errors
235
+ cannot affect admission. Hosts retain responsibility for authorization and configuration checks
236
+ inside the protected operation callback, after admission and before dispatch.
237
+
238
+ Supply the same stable `admissionKey` to **every isolated operation for that connector**, including
239
+ exclusive discovery, probes, OAuth, and tool calls, across actors and configuration generations.
240
+ The host owns this identity and the eligibility policy; tool annotations are not authorization.
241
+ Keys are bounded to 1–1024 characters and are never emitted in manager diagnostics. Shared/retained
242
+ runtimes cannot use keyed admission and must not be mixed into a keyed connector's lifecycle.
243
+
244
+ An exclusive call with `exclusiveContention: "queue"` waits for related concurrent calls to drain
245
+ and blocks new concurrent arrivals until it settles or is cancelled. Waiting remains bounded by
246
+ `maxQueuedOperations` and the call deadline. Retirement cancels that generation's calls and waiting
247
+ operations, without retiring sibling generations. Uncertain cleanup quarantines its generation
248
+ and admission identity until manager replacement, retaining the failed transport's capacity charge.
249
+ A successful sibling cleanup cannot clear quarantine.
250
+
251
+ Limits are local to one manager/process. Hosts operating several processes must allocate their
252
+ provider budget across them; this is not a fleet-wide semaphore.
253
+
254
+ For concurrent runtimes, generation `state()` is the latest lifecycle observation, not an aggregate
255
+ connection count. Use `snapshot()` for bounded aggregate pending, active, closing, and quarantined
256
+ transport counts. Quarantine is sticky even when a sibling reports another lifecycle transition.