@nest-mcp/client 1.0.2 → 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.
Files changed (54) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +845 -69
  3. package/dist/ai-sdk/index.d.mts +14 -0
  4. package/dist/ai-sdk/index.d.mts.map +1 -0
  5. package/dist/ai-sdk/index.mjs +27 -0
  6. package/dist/ai-sdk/index.mjs.map +1 -0
  7. package/dist/bootstrap-BIAcDnHp.d.mts +394 -0
  8. package/dist/bootstrap-BIAcDnHp.d.mts.map +1 -0
  9. package/dist/index.d.mts +480 -0
  10. package/dist/index.d.mts.map +1 -0
  11. package/dist/index.mjs +1960 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/dist/oauth/dynamic-registration.d.mts +92 -0
  14. package/dist/oauth/dynamic-registration.d.mts.map +1 -0
  15. package/dist/oauth/dynamic-registration.mjs +392 -0
  16. package/dist/oauth/dynamic-registration.mjs.map +1 -0
  17. package/dist/oauth/index.d.mts +422 -0
  18. package/dist/oauth/index.d.mts.map +1 -0
  19. package/dist/oauth/index.mjs +3349 -0
  20. package/dist/oauth/index.mjs.map +1 -0
  21. package/dist/scope-CxGBCDdr.mjs +22 -0
  22. package/dist/scope-CxGBCDdr.mjs.map +1 -0
  23. package/package.json +76 -50
  24. package/scripts/external-smoke.mjs +693 -0
  25. package/dist/decorators/inject-mcp-client.decorator.d.ts +0 -3
  26. package/dist/decorators/inject-mcp-client.decorator.js +0 -12
  27. package/dist/decorators/on-notification.decorator.d.ts +0 -7
  28. package/dist/decorators/on-notification.decorator.js +0 -13
  29. package/dist/health/mcp-client.health.d.ts +0 -20
  30. package/dist/health/mcp-client.health.js +0 -42
  31. package/dist/index.d.ts +0 -21
  32. package/dist/index.js +0 -64
  33. package/dist/interfaces/client-options.interface.d.ts +0 -139
  34. package/dist/interfaces/client-options.interface.js +0 -3
  35. package/dist/mcp-client.module.d.ts +0 -20
  36. package/dist/mcp-client.module.js +0 -188
  37. package/dist/mcp-client.service.d.ts +0 -558
  38. package/dist/mcp-client.service.js +0 -532
  39. package/dist/mcp-clients.service.d.ts +0 -39
  40. package/dist/mcp-clients.service.js +0 -104
  41. package/dist/testing/mock-client.d.ts +0 -67
  42. package/dist/testing/mock-client.js +0 -154
  43. package/dist/transport/apply-auth-headers.d.ts +0 -3
  44. package/dist/transport/apply-auth-headers.js +0 -13
  45. package/dist/transport/client-transport.factory.d.ts +0 -4
  46. package/dist/transport/client-transport.factory.js +0 -21
  47. package/dist/transport/sse-client.transport.d.ts +0 -4
  48. package/dist/transport/sse-client.transport.js +0 -15
  49. package/dist/transport/stdio-client.transport.d.ts +0 -4
  50. package/dist/transport/stdio-client.transport.js +0 -14
  51. package/dist/transport/streamable-client.transport.d.ts +0 -4
  52. package/dist/transport/streamable-client.transport.js +0 -17
  53. package/dist/utils/format-error-message.d.ts +0 -2
  54. package/dist/utils/format-error-message.js +0 -7
package/README.md CHANGED
@@ -1,79 +1,855 @@
1
- # @nest-mcp/client
2
-
3
- [![npm version](https://img.shields.io/npm/v/@nest-mcp/client.svg)](https://www.npmjs.com/package/@nest-mcp/client)
4
- [![npm downloads](https://img.shields.io/npm/dm/@nest-mcp/client.svg)](https://www.npmjs.com/package/@nest-mcp/client)
5
- [![License](https://img.shields.io/npm/l/@nest-mcp/client)](https://github.com/btwld/nest-mcp/blob/v1/LICENSE)
6
- [![CI](https://github.com/btwld/nest-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/btwld/nest-mcp/actions/workflows/ci.yml)
7
-
8
- NestJS module for connecting to and consuming [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers with typed injection, notifications, health checks, and reconnection support.
9
-
10
- ## Installation
11
-
12
- ```bash
13
- npm install @nest-mcp/client @modelcontextprotocol/sdk zod@^4
14
- npm install @nestjs/common @nestjs/core reflect-metadata rxjs
15
- ```
16
-
17
- ## Quick start
18
-
19
- ```typescript
20
- // app.module.ts
21
- import { Module } from '@nestjs/common';
22
- import { McpClientModule } from '@nest-mcp/client';
23
- import { McpTransportType } from '@nest-mcp/client';
24
-
25
- @Module({
26
- imports: [
27
- McpClientModule.forRoot({
28
- connections: [
29
- {
30
- name: 'my-server',
31
- transport: {
32
- type: McpTransportType.STREAMABLE_HTTP,
33
- url: 'http://localhost:3000/mcp',
34
- },
35
- },
36
- ],
37
- }),
38
- ],
39
- })
40
- export class AppModule {}
41
- ```
42
-
43
- ```typescript
44
- // my.service.ts
45
- import { Injectable } from '@nestjs/common';
46
- import { InjectMcpClient, McpClient } from '@nest-mcp/client';
47
-
48
- @Injectable()
49
- export class MyService {
50
- constructor(@InjectMcpClient('my-server') private client: McpClient) {}
51
-
52
- async greet(name: string) {
53
- return this.client.callTool({ name: 'greet', arguments: { name } });
54
- }
1
+ # `@nest-mcp/client`
2
+
3
+ A production-oriented, framework-neutral MCP client runtime for Node.js. It manages many named
4
+ upstream servers while keeping the official `@modelcontextprotocol/client` v2 `Client` available
5
+ for advanced protocol features.
6
+
7
+ It targets Node.js 22.13 or newer, ESM, TypeScript 7, and the official MCP client SDK `>=2 <3`.
8
+
9
+ ## What it provides
10
+
11
+ - A registry of independently connected named servers
12
+ - Official Streamable HTTP and Node.js stdio transports
13
+ - `AuthProvider` and `OAuthClientProvider` pass-through for HTTP
14
+ - Official composable fetch middleware
15
+ - MCP v2 version negotiation in `auto` mode by default, with explicit legacy or pinned modes
16
+ - Discovery and host-managed `PriorDiscovery` reuse
17
+ - Shared `@nest-mcp/core` operation middleware, authorization, and lifecycle observation
18
+ - Deterministic connect, disconnect, disconnect-all, close, and async-disposal behavior
19
+ - Introspection snapshots without exposing auth tokens or operation payloads
20
+ - Typed delegation for tools, resources, resource templates, prompts, completion, and liveness
21
+ - Method-keyed protocol requests, schema-validated extension requests, and notifications
22
+ - Runtime-owned modern listen streams plus explicit legacy resource subscriptions
23
+ - Direct typed access to each connected official SDK `Client`
24
+ - Zod v4 projection for dynamically discovered tool schemas, with Standard Schema compatibility
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ pnpm add @nest-mcp/client @modelcontextprotocol/client@2
30
+ ```
31
+
32
+ ## HTTP runtime
33
+
34
+ ```ts
35
+ import { createMiddleware, withLogging } from "@modelcontextprotocol/client";
36
+ import { McpClientRuntime } from "@nest-mcp/client";
37
+
38
+ const correlation = createMiddleware(async (next, input, init) => {
39
+ const headers = new Headers(init?.headers);
40
+ headers.set("x-runtime", "artifact-agents");
41
+ return next(input, { ...init, headers });
42
+ });
43
+
44
+ const runtime = new McpClientRuntime({
45
+ clientInfo: { name: "artifact-agent-runtime", version: "1.0.0" },
46
+ servers: [
47
+ {
48
+ name: "knowledge",
49
+ transport: {
50
+ kind: "http",
51
+ url: "https://mcp.example.com/mcp",
52
+ authProvider: {
53
+ token: async () => process.env.MCP_ACCESS_TOKEN,
54
+ },
55
+ middleware: [correlation, withLogging({ statusLevel: 400 })],
56
+ },
57
+ },
58
+ ],
59
+ });
60
+
61
+ await runtime.connect("knowledge");
62
+
63
+ const { tools } = await runtime.listTools("knowledge");
64
+ const result = await runtime.callTool("knowledge", {
65
+ name: tools[0]!.name,
66
+ arguments: { query: "MCP runtime architecture" },
67
+ });
68
+
69
+ await runtime.close();
70
+ ```
71
+
72
+ When a host dynamically composes discovered tools, convert the remote JSON Schema into a real Zod
73
+ v4 schema instead of asserting it into a package-local type:
74
+
75
+ ```ts
76
+ import { createMcpClientToolSchema } from "@nest-mcp/client";
77
+
78
+ const { tools } = await runtime.listTools("knowledge");
79
+ const inputSchema = createMcpClientToolSchema(tools[0]!.inputSchema);
80
+ const parsed = inputSchema.parse(candidateArguments);
81
+ ```
82
+
83
+ Zod v4 implements Standard Schema and Standard JSON Schema, so the returned schema also works
84
+ directly with vendor-neutral consumers. The schema's Zod refinement delegates the validation
85
+ predicate to the official MCP validator. This retains every Draft 2020-12 constraint, does not
86
+ apply annotations such as `default` as transforms, and returns successful values unchanged. The
87
+ detached remote definition is preserved as immutable Zod metadata and through the Standard JSON
88
+ Schema hook. Explicit non-2020-12 declarations fail during construction, and the returned schema's
89
+ projection methods reject requests for another target instead of relabelling 2020-12 keywords.
90
+ Structured-output validation stays on the exact `McpClientRuntime.callTool()` path with the
91
+ discovered `toolDefinition`.
92
+
93
+ `middleware` uses the official SDK's `applyMiddlewares` implementation. A custom `fetch` can be
94
+ provided as the base of that chain. Authentication is passed directly to
95
+ `StreamableHTTPClientTransport`; the runtime does not copy tokens into snapshots or lifecycle
96
+ events.
97
+
98
+ For machine-to-machine OAuth, the package re-exports the official v2 providers:
99
+
100
+ ```ts
101
+ import { ClientCredentialsProvider, McpClientRuntime } from "@nest-mcp/client";
102
+
103
+ const authProvider = new ClientCredentialsProvider({
104
+ clientId: process.env.MCP_CLIENT_ID!,
105
+ clientSecret: process.env.MCP_CLIENT_SECRET!,
106
+ expectedIssuer: "https://identity.example.com",
107
+ scope: "mcp:tools mcp:resources",
108
+ });
109
+
110
+ const runtime = new McpClientRuntime({
111
+ servers: [
112
+ {
113
+ name: "secured",
114
+ transport: {
115
+ kind: "http",
116
+ url: "https://mcp.example.com/mcp",
117
+ authProvider,
118
+ },
119
+ },
120
+ ],
121
+ });
122
+ ```
123
+
124
+ `PrivateKeyJwtProvider`, `StaticPrivateKeyJwtProvider`, `CrossAppAccessProvider`, the OAuth
125
+ discovery helpers, and the official typed OAuth errors are also available from the package root.
126
+ Interactive providers can be passed through in the same way; authorization redirects and durable
127
+ token storage remain host-application responsibilities.
128
+
129
+ ## Strict host-managed OAuth
130
+
131
+ Multi-tenant hosts should use the dedicated `@nest-mcp/client/oauth` surface instead of allowing
132
+ the transport to start an interactive SDK flow. The strict facade only accepts clients that were
133
+ provisioned out of band. It has no Dynamic Client Registration operation, requires exact resource
134
+ and issuer bindings plus PKCE S256, validates the RFC 9207 authorization-response issuer parameter
135
+ when advertised or returned, and re-checks every discovered or credentialed endpoint through host
136
+ policy.
137
+
138
+ ```ts
139
+ import { McpClientOAuthProtocol } from "@nest-mcp/client/oauth";
140
+
141
+ const oauth = new McpClientOAuthProtocol({
142
+ // This must reject redirects, private/rebound addresses, oversized bodies, and timeouts.
143
+ fetch: ssrfGuardedOAuthFetch,
144
+ endpointPolicy({ endpoint, credentialed }) {
145
+ if (endpoint.port !== "" && endpoint.port !== "443") return false;
146
+ if (!allowedOAuthOrigins.has(endpoint.origin)) return false;
147
+ return !credentialed || credentialOrigins.has(endpoint.origin);
148
+ },
149
+ });
150
+
151
+ const authority = await oauth.discover({
152
+ serverUrl: "https://mcp.example.com/mcp",
153
+ resource: "https://mcp.example.com/mcp",
154
+ issuer: "https://identity.example.com/",
155
+ });
156
+
157
+ const started = await oauth.startAuthorization({
158
+ authority,
159
+ client: { clientId, authentication: { method: "none" } },
160
+ redirectUri: "https://studio.example.com/oauth/callback",
161
+ scopes: ["mcp:tools"],
162
+ });
163
+
164
+ // Persist `started.transaction` with authenticated encryption and browser-session binding.
165
+ // The plaintext state exists only in `started.authorizationUrl`; the record keeps its digest.
166
+ await savePendingAuthorization(started.transaction);
167
+ redirectUser(started.authorizationUrl);
168
+ ```
169
+
170
+ On callback, parse the parameters, derive the state lookup digest, and atomically take the pending
171
+ transaction before calling `exchangeAuthorization`. A consumed transaction stays consumed even
172
+ when token exchange has an ambiguous network result. The facade validates state lifetime, callback
173
+ issuer, client identity, and the authority/endpoints pinned before redirect. When the authority
174
+ advertises RFC 9207, callbacks without the exact `iss` value fail closed. An unadvertised but
175
+ present `iss` is still compared exactly; omission is accepted only when the authority did not
176
+ advertise it. The facade never rediscovers an endpoint while redeeming a code.
177
+
178
+ The subpath also provides a revisioned credential-store port and
179
+ `McpClientOAuthRefreshCoordinator`. Refreshes for one opaque identity and exact revision share one
180
+ operation. Before dispatch, the store must atomically claim the exact revision with a durable
181
+ fencing token; another process observing that claim never sends the same refresh token. A rotated
182
+ refresh token is committed only by that claim owner. Retry-safe pre-dispatch failure can release the
183
+ claim explicitly, while an abandoned or indeterminate post-dispatch claim must become terminal and
184
+ must never reactivate the old generation. If the outcome becomes unknowable after a refresh request
185
+ may have reached the authorization server, the old generation is invalidated instead of replayed.
186
+ Terminal invalidation or an observed external disappearance can evict credential-bound client
187
+ leases. Successful rotation and a newer winner remain within the same stable binding and do not
188
+ invoke the terminal invalidation hook. Identity keys must be non-secret and include every immutable
189
+ host isolation coordinate. The coordinator awaits its invalidation hook while the failed request
190
+ may still hold that same lease, so a lease-eviction hook must initiate retirement and return without
191
+ awaiting active-lease drain; observe and report the eventual drain separately.
192
+
193
+ Create one `McpClientOAuthAuthProvider` per credential binding and close it with that binding's
194
+ runtime lease. The bridge implements only the SDK's minimal `AuthProvider`: it loads the current
195
+ generation before each request and delegates a `401` refresh to the coordinator, but has no
196
+ `OAuthClientProvider` methods that could trigger redirects or registration. Set the HTTP transport's
197
+ `options.onInsufficientScope` to `"throw"` so scope escalation returns to host policy instead of
198
+ starting an implicit interactive flow. The bridge follows successful token revisions inside one
199
+ stable owner/authority binding. A host that treats every token revision as a new runtime identity
200
+ must close or reacquire that runtime after the operation instead of pooling it under the old
201
+ revision.
202
+
203
+ The SDK's minimal `onUnauthorized` callback does not identify the failed request's credential
204
+ revision. For isolated concurrent operations, pass `expectedCredentialRevision` when constructing
205
+ each provider. Every credential load is fenced to that exact revision, including the load before
206
+ refresh. Concurrent failures for the same revision share the coordinator's refresh, but after
207
+ rotation the old operations fail with `MCP_CLIENT_OAUTH_AUTH_PROVIDER_CREDENTIAL_REVISION_CHANGED`.
208
+ A delayed failure cannot refresh the replacement credential. A fresh, authorized acquisition can
209
+ use the published revision; the host must not automatically replay a dispatched tool operation.
210
+ Omitting the option retains the binding-following behavior and requires the host to coordinate
211
+ long-lived or concurrent requests appropriately.
212
+
213
+ When the bridge is admitted through `McpRuntimeManager`, the ordinary `ensureOnline()` keeper is a
214
+ pool and does not meet that close-on-release condition. Use the manager operation option
215
+ `{ leaseMode: "exclusive" }` without retaining the generation: it rejects overlapping work for the
216
+ same key and closes the dedicated runtime plus admitted material before settlement. Shared manager
217
+ generations remain appropriate only when the host provides the request-correlated refresh boundary
218
+ and exact revision fence described above. Manager-owned exclusive catalog refreshes serialize their
219
+ protocol requests; a custom exclusive `withClientRuntime` callback must also avoid parallel
220
+ credentialed requests when it relies on this no-concurrency guarantee.
221
+
222
+ Encryption, AAD construction, owner/scope authorization, RLS, callback-session checks, and the
223
+ atomic pending-transaction store remain application responsibilities. OAuth fetches should use a
224
+ separate guarded path from arbitrary MCP middleware: request logging or middleware that can inspect
225
+ headers and form bodies can expose bearer tokens, client secrets, codes, or refresh tokens. Treat
226
+ returned `id_token` values as opaque unless a separate OIDC validator verifies them. The guarded
227
+ fetch must never automatically retry a credentialed token `POST`; one durable refresh claim permits
228
+ at most one wire exchange, and an ambiguous result must return to the coordinator unchanged.
229
+
230
+ ## Stdio servers
231
+
232
+ ```ts
233
+ const runtime = new McpClientRuntime({
234
+ servers: [
235
+ {
236
+ name: "local-files",
237
+ transport: {
238
+ kind: "stdio",
239
+ command: "node",
240
+ args: ["./dist/files-server.mjs"],
241
+ env: { MCP_ROOT: "/srv/artifacts" },
242
+ stderr: "inherit",
243
+ },
244
+ },
245
+ ],
246
+ });
247
+
248
+ await runtime.connect("local-files");
249
+ ```
250
+
251
+ The default factory returns the official `StdioClientTransport` class exactly. That matters for
252
+ the SDK's v2 automatic negotiation path, which can probe stdio through a short-lived sibling
253
+ process before opening the session process.
254
+
255
+ Prefer `stderr: "inherit"` or `"ignore"` for a noisy child. The runtime does not expose an owned
256
+ stdio transport before the handshake, so an unread `"pipe"` can fill and block the child. To capture
257
+ stderr, provide a custom transport factory that attaches a reader before returning the transport.
258
+
259
+ The built-in transport definitions cover Streamable HTTP and stdio. A standalone legacy SSE-only
260
+ endpoint is not automatically detected or exposed as a first-class transport. OAuth transport
261
+ authentication applies to HTTP; stdio credentials are an out-of-band concern for the spawned
262
+ process and should be passed only through explicitly controlled configuration.
263
+
264
+ ## Opt-in external smoke test
265
+
266
+ The repository's default test and verification commands never contact external services. To check
267
+ the built package against a real Streamable HTTP or stdio server, run the package-local smoke
268
+ command with environment-only configuration:
269
+
270
+ ```sh
271
+ export MCP_SMOKE_TRANSPORT=http
272
+ export MCP_SMOKE_URL=https://mcp.example.com/mcp
273
+ export MCP_SMOKE_AUTH=bearer
274
+ export MCP_SMOKE_BEARER_TOKEN="$(read-token-from-your-secret-store)"
275
+ pnpm --filter @nest-mcp/client smoke:external
276
+ ```
277
+
278
+ Machine-to-machine OAuth uses the official client-credentials provider and requires issuer
279
+ binding:
280
+
281
+ ```sh
282
+ export MCP_SMOKE_AUTH=oauth-client-credentials
283
+ export MCP_SMOKE_OAUTH_CLIENT_ID=smoke-client
284
+ export MCP_SMOKE_OAUTH_CLIENT_SECRET="$(read-secret-from-your-secret-store)"
285
+ export MCP_SMOKE_OAUTH_EXPECTED_ISSUER=https://identity.example.com
286
+ export MCP_SMOKE_OAUTH_SCOPE="mcp:tools mcp:resources"
287
+ pnpm --filter @nest-mcp/client smoke:external
288
+ ```
289
+
290
+ For stdio, arguments are a JSON string array and only explicitly named environment variables are
291
+ forwarded in addition to the official SDK's safe default environment:
292
+
293
+ ```sh
294
+ export MCP_SMOKE_TRANSPORT=stdio
295
+ export MCP_SMOKE_COMMAND=node
296
+ export MCP_SMOKE_ARGS_JSON='["./dist/server.mjs"]'
297
+ export MCP_SMOKE_STDIO_ENV_NAMES=MCP_SERVER_TOKEN
298
+ export MCP_SERVER_TOKEN="$(read-token-from-your-secret-store)"
299
+ pnpm --filter @nest-mcp/client smoke:external
300
+ ```
301
+
302
+ The command connects, calls `server/discover` on the modern session transport, uses legacy `ping`
303
+ only when that method is valid for the negotiated era, lists advertised tools/resources/prompts,
304
+ and emits only counts and protocol metadata. Set `MCP_SMOKE_TOOL_NAME` and
305
+ `MCP_SMOKE_TOOL_ARGUMENTS_JSON` to opt into a real tool call; its result is not printed and all
306
+ nested scalar argument values are treated as secrets in harness diagnostics. `MCP_SMOKE_PROTOCOL`
307
+ accepts `auto` (default), `legacy`, or a valid modern calendar date on or after `2026-07-28` to pin.
308
+ Additional HTTP headers can be supplied through `MCP_SMOKE_HTTP_HEADERS_JSON`; their values are
309
+ also treated as secrets in diagnostics.
310
+
311
+ `MCP_SMOKE_TIMEOUT_MS` bounds the active phase starting before any development build and covering
312
+ the MCP requests. On timeout, an active development build is terminated and
313
+ in-flight MCP work is aborted. Runtime teardown then has a separate shutdown bound of the same
314
+ duration, so cleanup can extend total elapsed time. Stdio stderr defaults to `ignore`. Setting
315
+ `MCP_SMOKE_STDIO_STDERR=inherit` sends the child output directly to the terminal, outside the
316
+ harness redactor; use it only with a trusted server that does not log credentials or payloads.
317
+
318
+ The command refuses to run when `CI` is set unless `MCP_SMOKE_ALLOW_CI=true` is also set, and it is
319
+ not referenced by the normal CI workflow. Use that override only in a trusted, explicitly
320
+ configured job backed by a secret store. Interactive browser OAuth is intentionally not automated
321
+ here; use a short-lived bearer token obtained by the host flow, while the hermetic interoperability
322
+ suite covers authorization-code, PKCE, state, issuer, and reconnect behavior.
323
+
324
+ Run `node packages/client/scripts/external-smoke.mjs --help` for every supported variable.
325
+
326
+ ## Host-managed OAuth provisioning
327
+
328
+ ### Detect authentication before enrollment
329
+
330
+ `detectMcpClientAuthentication` from `@nest-mcp/client/oauth` performs credential-free,
331
+ passive Streamable HTTP detection:
332
+
333
+ ```ts
334
+ import { detectMcpClientAuthentication } from "@nest-mcp/client/oauth";
335
+
336
+ const result = await detectMcpClientAuthentication({
337
+ serverUrl: endpoint,
338
+ fetch: admittedEndpointLease.fetch,
339
+ discoveryFetch: ssrfGuardedOAuthFetch,
340
+ endpointPolicy: oauthEndpointPolicy,
341
+ signal: hostDeadlineSignal,
342
+ timeoutMs: 10_000,
343
+ maxResponseBytes: 262_144,
344
+ });
345
+ // Always release the host's admitted fetch lease in the host's finally block.
346
+ ```
347
+
348
+ - `anonymous`: the SDK validated modern `server/discover` or completed legacy
349
+ `initialize` / `notifications/initialized`. Includes `protocolVersion`, `protocolEra`, and
350
+ optional bounded `serverInfo` (`name`, `version`, `title`). Identity is self-reported display
351
+ data. This proves anonymous connection/discovery at inspection time, not anonymous access to
352
+ every future operation; a server may protect individual tools or change policy later.
353
+ - `oauth-required`: an MCP request received `401`, or `403` with a parsed Bearer challenge,
354
+ and existing OAuth bootstrap validated discovery. `discovery` retains its existing `ready`,
355
+ `authorization-server-selection-required`, or `strict-protocol-unsupported` discriminant.
356
+ The host still decides whether and how it can enroll that authority.
357
+ - `indeterminate`: a fixed `reason` and optional numeric `httpStatus` / bootstrap
358
+ `discoveryErrorCode`. Missing metadata, Basic/API-key authentication, redirects, malformed
359
+ responses, network errors, unsupported protocol, and deadline failures never mean anonymous.
360
+ Raw response bodies, challenge text, and provider errors are not returned.
361
+
362
+ `fetch` must already admit the MCP endpoint and support POST, optional legacy GET, and DELETE
363
+ cleanup. `discoveryFetch` defaults to `fetch`; provide it separately when the MCP fetch is
364
+ restricted to one exact endpoint. It must enforce the host's DNS/network policy for generated
365
+ OAuth metadata URLs. The same bootstrap `endpointPolicy` admits every generated metadata URL and
366
+ checks authorization/token endpoints without fetching them. The helper forces omitted
367
+ credentials, no caching, and rejected redirects, and installs no auth provider. Never supply a
368
+ fetch that injects cookies, bearer tokens, or other credentials.
369
+
370
+ Detection has a default 10-second total deadline (configurable up to 60 seconds), an aggregate
371
+ 256-KiB response budget including SSE framing and OAuth metadata (up to 1 MiB), and at most 12
372
+ requests plus one legacy session DELETE. It parses streaming responses incrementally through
373
+ the SDK; an SSE stream need not close after its result. It cancels remaining bodies and closes
374
+ the SDK client/transport, with at most one additional second for cleanup. Failed anonymous
375
+ session cleanup becomes `indeterminate`. Host cancellation rejects with the original reason.
376
+ The host must release its network lease even after failure or cancellation; the helper cannot
377
+ force an uncooperative fetch/cancel implementation to release sockets.
378
+
379
+ Only HTTP Streamable MCP is inspected; old HTTP+SSE endpoints are not followed. No tool/list
380
+ invocation, client registration, authorization navigation, token acquisition, persistence,
381
+ permission checks, or enrollment occurs. Inspection results are advisory and are not admission
382
+ receipts or activation credentials.
383
+
384
+ ### Plan OAuth enrollment
385
+
386
+ Use `planMcpClientOAuthProvisioning` from `@nest-mcp/client/oauth` to decide how to provision a
387
+ client after bootstrap returns `ready`. The planner takes captured discovery, the callback URL,
388
+ optional current CIMD identity, and public existing-client provenance. Supply `strategies` in your
389
+ preferred order, for example `["reuse", "client_id_metadata", "dynamic_registration"]`. An omitted
390
+ strategy cannot be selected. The result includes `kind`, `existingClientStatus`, and the exact
391
+ `authorizationScopes` to request.
392
+
393
+ Manual clients retain their configured scopes. Dynamically registered clients can reuse their
394
+ registered allowance for a narrower fresh request; absent discovery scopes request no scopes.
395
+ An expansion returns `registration_scope_insufficient` rather than selecting another registration
396
+ unless the host explicitly enables `allowRegistrationAfterScopeExpansion`. CIMD can be preferred
397
+ over that recovery result by its position in the strategy order. The planner supports private-key
398
+ clients through public authentication-availability evidence and never receives their signing keys.
399
+
400
+ The planner performs no network calls or state transitions. The host supplies authorized current
401
+ records and remains responsible for consent, durable dispatch claims, secret custody, and atomic
402
+ configuration changes. A `dynamic_registration` result does not authorize registration.
403
+
404
+ `probeMcpClientOAuthChallenge({ serverUrl, fetch, signal })` performs one unauthenticated GET using
405
+ an already-admitted host fetch. It forces omitted credentials and rejected redirects, cancels the
406
+ response body, and returns only a bounded raw 401 challenge for `bootstrap.discover`'s
407
+ `wwwAuthenticate` field. Other statuses return `undefined` for well-known discovery fallback.
408
+ The host must provide a deadline, DNS and response bounds, and close the fetch lease in `finally`.
409
+
410
+ ## Many servers
411
+
412
+ ```ts
413
+ const runtime = new McpClientRuntime({
414
+ servers: [githubDefinition, filesystemDefinition, databaseDefinition],
415
+ });
416
+
417
+ const clients = await runtime.connectAll({
418
+ github: { timeout: 10_000 },
419
+ database: { timeout: 5_000 },
420
+ });
421
+
422
+ for (const snapshot of runtime.snapshot()) {
423
+ console.log(snapshot.name, snapshot.state, snapshot.protocolEra);
55
424
  }
56
425
  ```
57
426
 
58
- ## Features
427
+ Concurrent calls to `connect(name)` share the same in-flight connection. Each server still owns a
428
+ separate SDK client, transport, session, negotiated protocol version, response cache, and failure
429
+ state. If any member of `connectAll()` fails, the runtime rolls back only connections whose atomic
430
+ connection transition was created by that `connectAll()` call. Connections that were already open
431
+ or won concurrently by another caller are preserved.
59
432
 
60
- - **`@InjectMcpClient(name)`** — inject a named client into any service
61
- - **`McpClientsService`** — programmatic access to all clients by name
62
- - **`@OnMcpNotification(method)`** — subscribe to server-sent notifications
63
- - **`McpClientHealthIndicator`** — health check integration (NestJS Terminus)
64
- - **Automatic reconnection** with configurable backoff
65
- - **OAuth** support for authenticated servers
433
+ `unregister(name)` retires the logical entry before awaiting teardown. New and middleware-paused
434
+ operations can no longer reach that entry, in-flight connection setup is closed before removal,
435
+ and an old operation is never rerouted to a later same-name registration. Runtime `close()` uses
436
+ the same non-bypassable cleanup path and is safely idempotent even when middleware re-enters it.
437
+ Each connection attempt owns an abort signal, linked to the initiating caller's signal, which is
438
+ also passed to custom transport factories and the official SDK handshake. Disconnect, unregister,
439
+ and close abort that signal before waiting. `shutdownTimeoutMs` is one absolute deadline for the
440
+ entire teardown—connection quiescence, subscription handles, and official client/transport close
441
+ (30 seconds by default). A factory, subscription, or SDK/client implementation that ignores
442
+ cancellation cannot hang shutdown indefinitely: cleanup rejects with `MCP_CLIENT_SHUTDOWN_TIMEOUT`,
443
+ retains failures observed before the deadline, and detaches stale work so it can never publish a
444
+ connection later.
66
445
 
67
- ## Transports
446
+ ## Identity-isolated client leases
447
+
448
+ Hosts that create separate client runtimes for different credential or authorization contexts can
449
+ use `McpClientLeaseManager`. Its identity key is opaque: the manager uses `Map` equality and passes
450
+ the key only to the host factory. Use a canonical, non-secret identifier that changes whenever any
451
+ credential, allowed capability, upstream configuration, or other isolation-relevant input changes.
452
+ Never place an access token, refresh token, authorization code, or other secret in the key.
453
+
454
+ ```ts
455
+ import { McpClientLeaseManager, McpClientRuntime } from "@nest-mcp/client";
456
+
457
+ const clients = new McpClientLeaseManager({
458
+ maxResources: 64,
459
+ idleTtlMs: 30_000,
460
+ async create(identityKey: string, { signal }) {
461
+ const definition = await loadServerDefinition(identityKey, { signal });
462
+ const runtime = new McpClientRuntime({ servers: [definition] });
463
+ await runtime.connect(definition.name, { signal });
464
+ return { runtime, serverName: definition.name };
465
+ },
466
+ async close(resource) {
467
+ await resource.runtime.close();
468
+ },
469
+ });
470
+
471
+ const lease = await clients.acquire(identityKey); // defaults to releaseMode: "close"
472
+ try {
473
+ await lease.resource.runtime.listTools(lease.resource.serverName);
474
+ } finally {
475
+ await lease.release(); // idempotent; closes after the final reference
476
+ }
477
+ ```
478
+
479
+ Concurrent acquisitions for one key share one in-flight factory and maintain independent
480
+ references. An existing generation pins its release mode and rejects a conflicting acquisition.
481
+ The default `"close"` mode is intended for credential-bound resources. Only resources that are
482
+ safe to retain and reuse should opt into `{ releaseMode: "idle" }`; they remain cached until
483
+ `idleTtlMs` expires and may be evicted earlier to admit another identity within `maxResources`.
484
+
485
+ Acquisition cancellation settles immediately by default while abandoned creation drains in the
486
+ background. An owner requiring cleanup before settlement can pass `awaitCleanupOnCancel: true`;
487
+ it then waits for cleanup caused by caller cancellation, invalidation, or shutdown before rejecting.
488
+ Cancelling one reservation never aborts another caller's shared creation. Exclusive managed
489
+ operations select this option so pending acquisition cleanup also precedes the next queued caller.
490
+
491
+ `invalidate(identityKey)` retires the matching generation before awaiting its close. It aborts a
492
+ pending factory and prevents a late result from publishing, even if a replacement generation has
493
+ already started. Active leases drain before their resource closes, so callers must release every
494
+ accepted lease. `close()` and `Symbol.asyncDispose` reject new acquisitions, abort all factories,
495
+ drain active leases, and settle all resource closes. The manager cannot forcibly stop a factory
496
+ that ignores its abort signal, so factories must honor cancellation. Snapshots are aggregate-only,
497
+ and manager-created errors never include identity keys or resources.
498
+
499
+ ## Configure the official client
500
+
501
+ Use `configureClient` before connection to register SDK request handlers, notification handlers,
502
+ roots, elicitation, sampling, or other client capabilities. Use `requireClient` after connection
503
+ for any official API that the convenience delegates do not wrap.
504
+
505
+ ```ts
506
+ const runtime = new McpClientRuntime({
507
+ servers: [
508
+ {
509
+ name: "interactive",
510
+ transport: { kind: "http", url: "https://mcp.example.com/mcp" },
511
+ clientOptions: {
512
+ capabilities: { elicitation: { form: {} } },
513
+ },
514
+ configureClient(client) {
515
+ client.setRequestHandler("elicitation/create", async (request) => {
516
+ return collectUserInput(request.params);
517
+ });
518
+ },
519
+ },
520
+ ],
521
+ });
522
+
523
+ await runtime.connect("interactive");
524
+ const officialClient = runtime.requireClient("interactive");
525
+ ```
526
+
527
+ The v2 SDK's modern protocol can also fulfill input-required rounds through these configured
528
+ handlers. The exact available handlers remain defined and typed by the official SDK.
529
+
530
+ ### Manual input-required rounds
531
+
532
+ For an agent or UI that must approve each round itself, use the explicit manual APIs. They always
533
+ set the official per-request `allowInputRequired: true` flag, so the SDK returns the continuation
534
+ without dispatching configured elicitation, sampling, or roots handlers:
535
+
536
+ ```ts
537
+ import { isInputRequiredResult, specTypeSchemas } from "@nest-mcp/client";
538
+
539
+ const original = {
540
+ method: "tools/call",
541
+ params: { name: "publish-artifact", arguments: { artifactId } },
542
+ } as const;
543
+
544
+ const first = await runtime.requestWithInputRequired(
545
+ "interactive",
546
+ original,
547
+ specTypeSchemas.CallToolResult,
548
+ );
549
+
550
+ if (isInputRequiredResult(first)) {
551
+ const complete = await runtime.resumeInputRequired(
552
+ "interactive",
553
+ original,
554
+ first,
555
+ { approval: { action: "accept", content: { approved: true } } },
556
+ specTypeSchemas.CallToolResult,
557
+ );
558
+ }
559
+ ```
560
+
561
+ `resumeInputRequired` creates a fresh protocol request, echoes `requestState` byte-for-byte, and
562
+ sends only the current round's `inputResponses`; it never carries continuation fields retained on
563
+ the immutable original request. Treat both fields as untrusted server/client exchange data. The
564
+ server must integrity-protect and verify any state that affects authorization or business logic.
565
+ Re-authorize every round and apply a host-level round count and whole-flow deadline.
566
+
567
+ The manual option type is deliberately limited to official `RequestOptions` and does not claim
568
+ `CallToolRequestOptions.toolDefinition`. The typed continuation path uses the SDK's explicit-schema
569
+ request primitive; tool-specific SEP-2243 header mirroring and output-schema conveniences belong to
570
+ the SDK's `callTool()` path and are not silently approximated here.
571
+
572
+ The method-keyed `request()` and high-level `callTool()`, `getPrompt()`, and `readResource()`
573
+ helpers likewise expose `InputRequiredResult` in their return type for an MRTR-capable method when
574
+ `allowInputRequired: true` is explicit. With the default or an explicit `false`, their
575
+ complete-result type remains narrow.
576
+
577
+ ## Completion and protocol extensions
578
+
579
+ Completion, ping, and all official method-keyed requests pass through the same runtime middleware
580
+ and lifecycle chain as tool calls:
581
+
582
+ ```ts
583
+ const { completion } = await runtime.complete("interactive", {
584
+ ref: { type: "ref/prompt", name: "review-code" },
585
+ argument: { name: "language", value: "typ" },
586
+ });
587
+
588
+ const pong = await runtime.request("interactive", { method: "ping" });
589
+ ```
590
+
591
+ Use `requestWithSchema` for a namespaced protocol extension. The official client validates the
592
+ response and TypeScript infers the output from the supplied Standard Schema:
593
+
594
+ ```ts
595
+ const result = await runtime.requestWithSchema(
596
+ "interactive",
597
+ { method: "acme/search", params: { query: "MCP" } },
598
+ SearchResultSchema,
599
+ );
600
+ ```
601
+
602
+ `notification(name, message, options)` is the corresponding one-way API. Both request forms and
603
+ notifications retain the protocol method in operation context without placing payloads in default
604
+ lifecycle events.
605
+
606
+ ## Change subscriptions
607
+
608
+ Register notification handlers before connection, then open a modern MCP 2026-07-28 listen stream
609
+ through the runtime:
610
+
611
+ ```ts
612
+ const runtime = new McpClientRuntime({
613
+ servers: [
614
+ {
615
+ name: "catalog",
616
+ transport: { kind: "http", url: "https://mcp.example.com/mcp" },
617
+ configureClient(client) {
618
+ client.setNotificationHandler("notifications/tools/list_changed", async () => {
619
+ await refreshTools();
620
+ });
621
+ },
622
+ },
623
+ ],
624
+ });
625
+
626
+ await runtime.connect("catalog");
627
+ const subscription = await runtime.listen("catalog", { toolsListChanged: true });
628
+
629
+ console.log(subscription.serverName, subscription.honoredFilter);
630
+ await subscription.close();
631
+ console.log(await subscription.closed); // "local"
632
+ ```
633
+
634
+ `listen` returns a runtime-owned `McpClientSubscription`. Its `close()` is idempotent and observed
635
+ by middleware; `disconnect`, `unregister`, and runtime `close` gracefully close every still-active
636
+ runtime-owned stream before closing the official client. `activeSubscriptions(name)` provides a
637
+ read-only view for diagnostics. If `ClientOptions.listChanged` asks the SDK to open a stream during
638
+ connect, the runtime adopts that handle too and exposes it through `getAutoOpenedSubscription(name)`.
639
+ Subscription teardown is non-bypassable: middleware may observe, wrap, or reject the cleanup
640
+ operation, but the runtime still invokes the official handle's `close()` and reports both failures
641
+ when middleware and SDK cleanup fail.
642
+
643
+ The SDK intentionally keeps the eras explicit: `listen` is modern-only, while
644
+ `subscribeResource` and `unsubscribeResource` are the legacy per-resource requests. Calling one on
645
+ the wrong era preserves the official typed SDK error; this package does not silently translate
646
+ between their different delivery models.
647
+
648
+ ## Operation middleware and observability
649
+
650
+ Every runtime connection action and delegated protocol request runs through `@nest-mcp/core`.
651
+ Lifecycle events intentionally contain context and timing, not MCP request or response payloads.
652
+
653
+ ```ts
654
+ import { createMcpAuthorizationMiddleware, type McpLifecycleObserver } from "@nest-mcp/core";
655
+ import {
656
+ McpClientRuntime,
657
+ createMcpClientPassthroughMiddleware,
658
+ defineMcpClientTransform,
659
+ } from "@nest-mcp/client";
660
+
661
+ const observer: McpLifecycleObserver = {
662
+ onEvent(event) {
663
+ telemetry.record(event);
664
+ },
665
+ };
666
+
667
+ const runtime = new McpClientRuntime({
668
+ servers,
669
+ principal: currentPrincipal,
670
+ attributes: { deployment: "artifact-runtime" },
671
+ middleware: [
672
+ createMcpAuthorizationMiddleware(policy),
673
+ createMcpClientPassthroughMiddleware(async (operation, next) => {
674
+ metrics.started(operation.input.method);
675
+ await next();
676
+ metrics.finished(operation.input.method);
677
+ }),
678
+ defineMcpClientTransform("tools/call", async (operation, next) => {
679
+ const result = await next(); // CallToolResult, without a cast
680
+ return { ...result, _meta: { ...result._meta, auditedTool: operation.input.params.name } };
681
+ }),
682
+ ],
683
+ observer,
684
+ });
685
+ ```
686
+
687
+ Middleware sees a stable `McpClientOperationInput` and context fields including `role: "client"`,
688
+ the protocol method, capability family, target server name, abort signal, session ID when known,
689
+ principal, and host attributes. Lifecycle observer failures are best-effort and do not replace the
690
+ operation result.
691
+
692
+ `createMcpClientPassthroughMiddleware` is the safer default for non-transforming concerns. Its
693
+ callback cannot inspect or replace the method-specific result; the runtime returns the exact value
694
+ produced downstream. `defineMcpClientTransform(method, transform)` is the deliberate transforming
695
+ path: its callback receives only that official method's request and `ResultTypeMap` result.
696
+
697
+ The runtime dispatches this helper only for operations whose public result is exactly the ordinary
698
+ official result. Custom-schema requests, manual MRTR/input-required calls, MRTR-capable calls with
699
+ `allowInputRequired: true`, and the runtime-managed high-level `listen()` handle are excluded even
700
+ when their method string matches. Request options are snapshotted and frozen before dispatch while
701
+ callback, signal, and deadline values retain their identities; a supplied tool definition is
702
+ detached and deeply frozen. Official requests and params are likewise detached and deeply frozen.
703
+ The policy, transform, and SDK terminal therefore observe the same method, arguments, and
704
+ result-affecting controls even if a caller later mutates its objects. Abort checks also surround
705
+ the transform, lifecycle observation stays outside it, and the shared `next()` continuation
706
+ remains callable once.
707
+
708
+ The runtime places exact transforms downstream of all general middleware, preserving relative
709
+ order within each group. A configured authorization middleware therefore always runs before an
710
+ exact transform, even if the transform appears first in the options array, and an exact `next()`
711
+ cannot receive an unrelated result returned by general middleware.
712
+
713
+ ## Discovery and prior verdicts
714
+
715
+ The runtime chooses `{ versionNegotiation: { mode: "auto" } }` when no mode is explicitly set.
716
+ This lets the official SDK negotiate modern MCP v2 and conservatively fall back to legacy MCP.
717
+
718
+ After connection, read a persistable verdict with `getPriorDiscovery`:
719
+
720
+ ```ts
721
+ await runtime.connect("knowledge");
722
+ const prior = runtime.getPriorDiscovery("knowledge");
723
+ await discoveryStore.set(authSubject, "knowledge", prior);
724
+ ```
725
+
726
+ Supply it on a later runtime definition or with `setPriorDiscovery`:
727
+
728
+ ```ts
729
+ runtime.setPriorDiscovery("knowledge", await discoveryStore.get(authSubject, "knowledge"));
730
+ await runtime.connect("knowledge");
731
+ ```
732
+
733
+ Prior verdicts are never reused automatically. Scope them to the same authorization context and
734
+ apply your own freshness policy. A stale legacy verdict can silently keep selecting legacy after a
735
+ server upgrade. A stale modern verdict fails loudly if it is no longer compatible.
736
+
737
+ For a deliberate legacy-only connection:
738
+
739
+ ```ts
740
+ {
741
+ name: "legacy",
742
+ transport: { kind: "http", url: "https://legacy.example.com/mcp" },
743
+ clientOptions: { versionNegotiation: { mode: "legacy" } },
744
+ }
745
+ ```
746
+
747
+ ## Main API
748
+
749
+ - Registry: `register`, `unregister`, `has`, `names`, `getDefinition`
750
+ - Lifecycle: `connect`, `connectAll`, `disconnect`, `disconnectAll`, `close`, `Symbol.asyncDispose`
751
+ - SDK access: `getClient`, `requireClient`
752
+ - Discovery: `discover`, `getPriorDiscovery`, `setPriorDiscovery`
753
+ - General protocol: `ping`, `request`, `requestWithSchema`, `requestWithInputRequired`,
754
+ `resumeInputRequired`, `notification`, `complete`
755
+ - Tools: `listTools`, `callTool`
756
+ - Resources: `listResources`, `listResourceTemplates`, `readResource`, `subscribeResource`,
757
+ `unsubscribeResource`
758
+ - Prompts: `listPrompts`, `getPrompt`
759
+ - Modern subscriptions: `listen`, `activeSubscriptions`, `getAutoOpenedSubscription`
760
+ - Deprecated compatibility: `setLoggingLevel`, `sendRootsListChanged`
761
+ - Introspection: `snapshot(name?)`
762
+ - Transports: `createMcpHttpClientTransport`, `createMcpStdioClientTransport`,
763
+ `createMcpClientTransport`, `defaultMcpClientTransportFactory`
764
+ - Fetch middleware: `composeMcpFetchMiddleware` plus re-exported `applyMiddlewares`,
765
+ `createMiddleware`, `withLogging`, and `withOAuth`
766
+ - Official SDK facade: `Client`, `StreamableHTTPClientTransport`, `StdioClientTransport`, OAuth
767
+ providers, discovery helpers, transport/client option types, and auth error classes
768
+
769
+ ## Security notes
770
+
771
+ - Never share private SDK response-cache stores or prior discovery verdicts across principals.
772
+ - Avoid logging authorization headers or sensitive MCP inputs and outputs.
773
+ - Treat stdio command, arguments, working directory, and environment as privileged configuration.
774
+ - Prefer an explicit environment allowlist for spawned servers.
775
+ - Keep authorization policy in operation middleware even when transport authentication succeeds;
776
+ authentication and authorization solve different problems.
777
+
778
+ ## Decode OAuth records from host storage
779
+
780
+ ```ts
781
+ import {
782
+ parseMcpClientOAuthAuthority,
783
+ parseMcpClientOAuthAuthorizationTransaction,
784
+ parseMcpClientOAuthBootstrapDiscoveryResult,
785
+ } from "@nest-mcp/client/oauth";
786
+
787
+ const bounds = { maxBytes: 65_536, maxUrlLength: 2_048 };
788
+ const authority = parseMcpClientOAuthAuthority(storedAuthority, bounds);
789
+ const transaction = parseMcpClientOAuthAuthorizationTransaction(storedTransaction, bounds);
790
+ const discovery = parseMcpClientOAuthBootstrapDiscoveryResult(storedDiscovery, bounds);
791
+ ```
792
+
793
+ These parsers accept `unknown`, reject unknown fields and executable/exotic values, and return
794
+ complete detached immutable snapshots. They share the protocol validators, including authority
795
+ identity, PKCE, redirect URI, scope, and transaction authority-digest checks. Explicit `undefined`
796
+ is rejected; omit optional persisted fields. Options may tighten the fixed 2 MiB and 4096-character
797
+ URL ceilings. Invalid input raises `McpClientOAuthSnapshotError` with the fixed code
798
+ `MCP_CLIENT_OAUTH_SNAPSHOT_INVALID`, without retaining a cause or input payload.
799
+
800
+ Parsing performs no I/O. The host must authenticate and decrypt storage, admit endpoints, enforce
801
+ session binding and expiry, and atomically consume pending authorization. A valid snapshot alone
802
+ does not authorize a connection or execution. Native clients may use protocol-approved HTTP
803
+ loopback redirects; browser products can retain a stricter HTTPS redirect policy.
804
+
805
+ ## Inspect an acquired runtime
806
+
807
+ ```ts
808
+ import { createMcpClientInspectionTarget } from "@nest-mcp/client";
809
+ import { createMcpPassiveDiscoveryPlan, runMcpConformancePlan } from "@nest-mcp/conformance";
810
+
811
+ await manager.withClientRuntime(
812
+ generationKey,
813
+ async ({ runtime, serverName, signal }) => {
814
+ const target = createMcpClientInspectionTarget({
815
+ runtime,
816
+ serverName,
817
+ leaseSignal: signal,
818
+ maxPages: 16,
819
+ maxItems: 4096,
820
+ });
821
+ const plan = createMcpPassiveDiscoveryPlan({
822
+ catalogDomain: "example/catalog/v1",
823
+ toolSchemaDomain: "example/schema/v1",
824
+ });
825
+ return runMcpConformancePlan(plan, { target, descriptor, runId, signal });
826
+ },
827
+ operationOptions,
828
+ );
829
+ ```
68
830
 
69
- - Streamable HTTP (`McpTransportType.STREAMABLE_HTTP`)
70
- - SSE (`McpTransportType.SSE`)
71
- - STDIO (`McpTransportType.STDIO`)
831
+ The target shares one fresh catalog per run, links cancellation to the existing lease, and compiles
832
+ schemas using the client package's existing schema compiler. `discoverMcpClientCatalog()` also
833
+ exposes the bounded raw traversal directly. It takes a signal, page and total-item bounds, and
834
+ optional sequential (default) or parallel mode. Parallel mode settles every request before
835
+ propagating failure. Repeated cursors fail; exceeded limits raise `McpClientCatalogLimitError`.
836
+ Only method-not-found on the optional resource-template list is tolerated.
72
837
 
73
- ## Documentation
838
+ This is passive diagnostic discovery, with no tool invocation, nested lease, durable state, or SDK
839
+ list-cache population. It retains raw provider definitions so diagnostics can inspect them.
840
+ Use manager refresh for the SDK's execution catalog filtering and schema-cache population.
74
841
 
75
- Full documentation: [github.com/btwld/nest-mcp/docs/client](https://github.com/btwld/nest-mcp/blob/v1/docs/client/README.md)
842
+ ### Optional AI SDK tools
76
843
 
77
- ## License
844
+ `@nest-mcp/client/ai-sdk` exports `createAiSdkMcpTools(descriptors, invoke)`.
845
+ Install AI SDK 7 only when using this subpath. The core client does not import AI.
78
846
 
79
- BSD-3-Clause
847
+ The adapter sets `strict: false` so providers preserve the MCP schema's optional fields.
848
+ Some tools distinguish omitted fields from empty arrays or null and reject combinations such as
849
+ detail fields with aggregate measures. The adapter forwards inputs unchanged to the protected
850
+ delegate, which remains responsible for execution authorization and input validation.
851
+ The host selects and sanitizes descriptors, owns names and exact source bindings,
852
+ and authorizes every call in `invoke(name, input, signal)`. The adapter rejects
853
+ empty or duplicate names, snapshots schemas, and propagates cancellation before
854
+ and after the delegate. It does not discover tools, rename them, acquire clients,
855
+ or replace an execution gateway.