@dudko.dev/agent-web 0.0.38 → 0.0.40

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/dist/mcp.d.cts CHANGED
@@ -1,16 +1,41 @@
1
- import { OAuthClientProvider, OAuthDiscoveryState } from '@modelcontextprotocol/sdk/client/auth.js';
2
- export { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
3
- import { StreamableHTTPReconnectionOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
4
- import { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
1
+ import { OAuthClientProvider, FetchLike, StreamableHTTPReconnectionOptions, OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthDiscoveryState } from '@modelcontextprotocol/client';
2
+ export { UnauthorizedError } from '@modelcontextprotocol/client';
5
3
  import { ToolSet } from 'ai';
6
- import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
7
4
  import { VaultOptions } from './index.cjs';
8
5
 
6
+ /**
7
+ * What the MCP connectors of the two agent packages share: how a server's `instructions` reach a
8
+ * system prompt, and how a tool result's `structuredContent` reaches the model. Pure, no imports.
9
+ *
10
+ * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/mcp-shared.ts`) and
11
+ * `@dudko.dev/agent-web` (`src/mcp/shared.ts`): change both. The Node package's
12
+ * `tests/mcp-shared.test.ts` compares the two files and tests every cap and guard here.
13
+ */
14
+ /** The `instructions` one connected MCP server returned in its `initialize` result. */
15
+ interface McpServerInstructions {
16
+ /** The server's name: its key in the host's configuration. */
17
+ server: string;
18
+ instructions: string;
19
+ }
20
+ /** The most one server's instructions take in a system prompt, in characters. */
21
+ declare const MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER = 2000;
22
+ /** The most all servers' instructions take together, in characters. */
23
+ declare const MCP_INSTRUCTIONS_MAX_CHARS_TOTAL = 8000;
24
+ /**
25
+ * The system-prompt section for the servers' instructions, or '' when no server sent any (the
26
+ * prompt is then exactly what it was). Each server's text is capped
27
+ * (MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER), so is the sum (MCP_INSTRUCTIONS_MAX_CHARS_TOTAL, in
28
+ * the order given: a server past the total is named as omitted), and every line of it is
29
+ * prefixed with "| ", so a server cannot write something that reads as a heading of this prompt
30
+ * or as another server's note.
31
+ */
32
+ declare const renderMcpInstructions: (list: readonly McpServerInstructions[] | undefined) => string;
33
+
9
34
  /**
10
35
  * A remote MCP server reached over StreamableHTTP. Browsers can ONLY speak the
11
36
  * HTTP transport — stdio (child processes) is Node-only and intentionally
12
37
  * unsupported here. This connector lives behind the `@dudko.dev/agent-web/mcp`
13
- * subpath so `@modelcontextprotocol/sdk` never enters the core bundle.
38
+ * subpath so `@modelcontextprotocol/client` never enters the core bundle.
14
39
  *
15
40
  * Three ways to authenticate, in ascending order of capability:
16
41
  * 1. `headers` — a static token you already hold.
@@ -63,6 +88,15 @@ interface ConnectedMcp {
63
88
  catalog: McpCatalogEntry[];
64
89
  /** Per-server connect outcome. */
65
90
  results: McpServerResult[];
91
+ /**
92
+ * The `instructions` each connected server returned in its `initialize`
93
+ * result, in declaration order; servers that sent none are absent. Read once
94
+ * per connection. Third-party text: the agent shows it to the model under a
95
+ * preamble that says so (`config.mcpInstructions`, on by default) — each
96
+ * mounted tool carries its server's instructions, so merging `tools` into
97
+ * the agent's config is all a host does.
98
+ */
99
+ instructions: McpServerInstructions[];
66
100
  /**
67
101
  * Re-list one server's tools and rewrite its entries in `tools`/`catalog`.
68
102
  * Both are mutated in place, so anything holding a reference (including a
@@ -209,7 +243,8 @@ interface BrowserOAuthProviderOptions {
209
243
  * `authorization_response_iss_parameter_supported: true`;
210
244
  * - no stored discovery state (storage written by an older version): `iss` is
211
245
  * compared with the issuer stamped on the stored client information, and with
212
- * nothing to compare against the response is accepted.
246
+ * nothing to compare against the response is accepted. ({@link finishMcpOAuth}
247
+ * does not exchange a code in that case: see there.)
213
248
  *
214
249
  * The Node package carries the same function; change both.
215
250
  */
@@ -259,11 +294,13 @@ declare class BrowserOAuthProvider implements OAuthClientProvider {
259
294
  redirectToAuthorization(url: URL): Promise<void>;
260
295
  /**
261
296
  * Called by the SDK when the server rejects what we hold: `'tokens'` after an
262
- * `invalid_grant` (dead refresh token), `'all'` after an `invalid_client`
263
- * (the AS forgot our dynamic registration). `'client'`, `'verifier'` and
264
- * `'discovery'` are in its type and handled the same way: one key each.
265
- * Clearing lets the SDK re-discover, re-register and re-authorize without the
266
- * user clearing site data.
297
+ * `invalid_grant` (dead refresh token); `'client'` and then `'tokens'` after
298
+ * an `invalid_client` (the AS forgot our dynamic registration) - what
299
+ * discovery found is kept on purpose, the SDK checks the next callback
300
+ * against it. `'verifier'` and `'discovery'` are in its type and handled the
301
+ * same way: one key each. `'all'` is what {@link reset} asks for. Clearing
302
+ * lets the SDK re-register and re-authorize without the user clearing site
303
+ * data.
267
304
  */
268
305
  invalidateCredentials(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): Promise<void>;
269
306
  /** True when there is no access token, or it expires within the skew window. */
@@ -303,6 +340,12 @@ declare const readOAuthCallback: (input?: string | URL) => McpOAuthCallback | un
303
340
  * an error, when `state` doesn't match what we issued, when `iss` names another
304
341
  * authorization server, or when the exchange fails — never resolves on a
305
342
  * half-finished authorization.
343
+ *
344
+ * A flow whose discovery state is not in storage any more (started by a
345
+ * version that did not keep it, or cleared in between) is not completed: the
346
+ * code is bound to the authorization server the user was sent to, and without
347
+ * the record of which one that was the SDK refuses the exchange. Start again
348
+ * with {@link beginMcpOAuth}; stored tokens are not touched.
306
349
  */
307
350
  declare const finishMcpOAuth: (provider: BrowserOAuthProvider, callback: McpOAuthCallback, opts?: McpOAuthRequestOptions) => Promise<void>;
308
351
  /**
@@ -624,5 +667,5 @@ declare class BrowserEnterpriseOAuthProvider implements OAuthClientProvider {
624
667
  /** Convenience factory mirroring the rest of the package's `createX` style. */
625
668
  declare const createEnterpriseOAuthProvider: (opts: EnterpriseOAuthProviderOptions) => BrowserEnterpriseOAuthProvider;
626
669
 
627
- export { BrowserEnterpriseOAuthProvider, BrowserOAuthProvider, ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION, EnterpriseOAuthError, MemoryOAuthStorage, VaultOAuthStorage, beginMcpOAuth, checkAuthorizationResponseIssuer, connectMcpHttp, createEnterpriseOAuthProvider, diagnoseMcpCors, finishMcpOAuth, flattenContent, readOAuthCallback };
628
- export type { BrowserOAuthProviderOptions, ConnectMcpOptions, ConnectedMcp, EnterpriseAssertionAlgorithm, EnterpriseAssertionAudience, EnterpriseAssertionType, EnterpriseIdpOptions, EnterpriseOAuthHop, EnterpriseOAuthLog, EnterpriseOAuthProviderOptions, EnterprisePrivateKey, McpCatalogEntry, McpHttpServerConfig, McpOAuthCallback, McpOAuthRequestOptions, McpOAuthStorage, McpServerResult };
670
+ export { BrowserEnterpriseOAuthProvider, BrowserOAuthProvider, ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION, EnterpriseOAuthError, MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER, MCP_INSTRUCTIONS_MAX_CHARS_TOTAL, MemoryOAuthStorage, VaultOAuthStorage, beginMcpOAuth, checkAuthorizationResponseIssuer, connectMcpHttp, createEnterpriseOAuthProvider, diagnoseMcpCors, finishMcpOAuth, flattenContent, readOAuthCallback, renderMcpInstructions };
671
+ export type { BrowserOAuthProviderOptions, ConnectMcpOptions, ConnectedMcp, EnterpriseAssertionAlgorithm, EnterpriseAssertionAudience, EnterpriseAssertionType, EnterpriseIdpOptions, EnterpriseOAuthHop, EnterpriseOAuthLog, EnterpriseOAuthProviderOptions, EnterprisePrivateKey, McpCatalogEntry, McpHttpServerConfig, McpOAuthCallback, McpOAuthRequestOptions, McpOAuthStorage, McpServerInstructions, McpServerResult };
package/dist/mcp.d.ts CHANGED
@@ -1,16 +1,41 @@
1
- import { OAuthClientProvider, OAuthDiscoveryState } from '@modelcontextprotocol/sdk/client/auth.js';
2
- export { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
3
- import { StreamableHTTPReconnectionOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
4
- import { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
1
+ import { OAuthClientProvider, FetchLike, StreamableHTTPReconnectionOptions, OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthDiscoveryState } from '@modelcontextprotocol/client';
2
+ export { UnauthorizedError } from '@modelcontextprotocol/client';
5
3
  import { ToolSet } from 'ai';
6
- import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
7
4
  import { VaultOptions } from './index.js';
8
5
 
6
+ /**
7
+ * What the MCP connectors of the two agent packages share: how a server's `instructions` reach a
8
+ * system prompt, and how a tool result's `structuredContent` reaches the model. Pure, no imports.
9
+ *
10
+ * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/mcp-shared.ts`) and
11
+ * `@dudko.dev/agent-web` (`src/mcp/shared.ts`): change both. The Node package's
12
+ * `tests/mcp-shared.test.ts` compares the two files and tests every cap and guard here.
13
+ */
14
+ /** The `instructions` one connected MCP server returned in its `initialize` result. */
15
+ interface McpServerInstructions {
16
+ /** The server's name: its key in the host's configuration. */
17
+ server: string;
18
+ instructions: string;
19
+ }
20
+ /** The most one server's instructions take in a system prompt, in characters. */
21
+ declare const MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER = 2000;
22
+ /** The most all servers' instructions take together, in characters. */
23
+ declare const MCP_INSTRUCTIONS_MAX_CHARS_TOTAL = 8000;
24
+ /**
25
+ * The system-prompt section for the servers' instructions, or '' when no server sent any (the
26
+ * prompt is then exactly what it was). Each server's text is capped
27
+ * (MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER), so is the sum (MCP_INSTRUCTIONS_MAX_CHARS_TOTAL, in
28
+ * the order given: a server past the total is named as omitted), and every line of it is
29
+ * prefixed with "| ", so a server cannot write something that reads as a heading of this prompt
30
+ * or as another server's note.
31
+ */
32
+ declare const renderMcpInstructions: (list: readonly McpServerInstructions[] | undefined) => string;
33
+
9
34
  /**
10
35
  * A remote MCP server reached over StreamableHTTP. Browsers can ONLY speak the
11
36
  * HTTP transport — stdio (child processes) is Node-only and intentionally
12
37
  * unsupported here. This connector lives behind the `@dudko.dev/agent-web/mcp`
13
- * subpath so `@modelcontextprotocol/sdk` never enters the core bundle.
38
+ * subpath so `@modelcontextprotocol/client` never enters the core bundle.
14
39
  *
15
40
  * Three ways to authenticate, in ascending order of capability:
16
41
  * 1. `headers` — a static token you already hold.
@@ -63,6 +88,15 @@ interface ConnectedMcp {
63
88
  catalog: McpCatalogEntry[];
64
89
  /** Per-server connect outcome. */
65
90
  results: McpServerResult[];
91
+ /**
92
+ * The `instructions` each connected server returned in its `initialize`
93
+ * result, in declaration order; servers that sent none are absent. Read once
94
+ * per connection. Third-party text: the agent shows it to the model under a
95
+ * preamble that says so (`config.mcpInstructions`, on by default) — each
96
+ * mounted tool carries its server's instructions, so merging `tools` into
97
+ * the agent's config is all a host does.
98
+ */
99
+ instructions: McpServerInstructions[];
66
100
  /**
67
101
  * Re-list one server's tools and rewrite its entries in `tools`/`catalog`.
68
102
  * Both are mutated in place, so anything holding a reference (including a
@@ -209,7 +243,8 @@ interface BrowserOAuthProviderOptions {
209
243
  * `authorization_response_iss_parameter_supported: true`;
210
244
  * - no stored discovery state (storage written by an older version): `iss` is
211
245
  * compared with the issuer stamped on the stored client information, and with
212
- * nothing to compare against the response is accepted.
246
+ * nothing to compare against the response is accepted. ({@link finishMcpOAuth}
247
+ * does not exchange a code in that case: see there.)
213
248
  *
214
249
  * The Node package carries the same function; change both.
215
250
  */
@@ -259,11 +294,13 @@ declare class BrowserOAuthProvider implements OAuthClientProvider {
259
294
  redirectToAuthorization(url: URL): Promise<void>;
260
295
  /**
261
296
  * Called by the SDK when the server rejects what we hold: `'tokens'` after an
262
- * `invalid_grant` (dead refresh token), `'all'` after an `invalid_client`
263
- * (the AS forgot our dynamic registration). `'client'`, `'verifier'` and
264
- * `'discovery'` are in its type and handled the same way: one key each.
265
- * Clearing lets the SDK re-discover, re-register and re-authorize without the
266
- * user clearing site data.
297
+ * `invalid_grant` (dead refresh token); `'client'` and then `'tokens'` after
298
+ * an `invalid_client` (the AS forgot our dynamic registration) - what
299
+ * discovery found is kept on purpose, the SDK checks the next callback
300
+ * against it. `'verifier'` and `'discovery'` are in its type and handled the
301
+ * same way: one key each. `'all'` is what {@link reset} asks for. Clearing
302
+ * lets the SDK re-register and re-authorize without the user clearing site
303
+ * data.
267
304
  */
268
305
  invalidateCredentials(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): Promise<void>;
269
306
  /** True when there is no access token, or it expires within the skew window. */
@@ -303,6 +340,12 @@ declare const readOAuthCallback: (input?: string | URL) => McpOAuthCallback | un
303
340
  * an error, when `state` doesn't match what we issued, when `iss` names another
304
341
  * authorization server, or when the exchange fails — never resolves on a
305
342
  * half-finished authorization.
343
+ *
344
+ * A flow whose discovery state is not in storage any more (started by a
345
+ * version that did not keep it, or cleared in between) is not completed: the
346
+ * code is bound to the authorization server the user was sent to, and without
347
+ * the record of which one that was the SDK refuses the exchange. Start again
348
+ * with {@link beginMcpOAuth}; stored tokens are not touched.
306
349
  */
307
350
  declare const finishMcpOAuth: (provider: BrowserOAuthProvider, callback: McpOAuthCallback, opts?: McpOAuthRequestOptions) => Promise<void>;
308
351
  /**
@@ -624,5 +667,5 @@ declare class BrowserEnterpriseOAuthProvider implements OAuthClientProvider {
624
667
  /** Convenience factory mirroring the rest of the package's `createX` style. */
625
668
  declare const createEnterpriseOAuthProvider: (opts: EnterpriseOAuthProviderOptions) => BrowserEnterpriseOAuthProvider;
626
669
 
627
- export { BrowserEnterpriseOAuthProvider, BrowserOAuthProvider, ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION, EnterpriseOAuthError, MemoryOAuthStorage, VaultOAuthStorage, beginMcpOAuth, checkAuthorizationResponseIssuer, connectMcpHttp, createEnterpriseOAuthProvider, diagnoseMcpCors, finishMcpOAuth, flattenContent, readOAuthCallback };
628
- export type { BrowserOAuthProviderOptions, ConnectMcpOptions, ConnectedMcp, EnterpriseAssertionAlgorithm, EnterpriseAssertionAudience, EnterpriseAssertionType, EnterpriseIdpOptions, EnterpriseOAuthHop, EnterpriseOAuthLog, EnterpriseOAuthProviderOptions, EnterprisePrivateKey, McpCatalogEntry, McpHttpServerConfig, McpOAuthCallback, McpOAuthRequestOptions, McpOAuthStorage, McpServerResult };
670
+ export { BrowserEnterpriseOAuthProvider, BrowserOAuthProvider, ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION, EnterpriseOAuthError, MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER, MCP_INSTRUCTIONS_MAX_CHARS_TOTAL, MemoryOAuthStorage, VaultOAuthStorage, beginMcpOAuth, checkAuthorizationResponseIssuer, connectMcpHttp, createEnterpriseOAuthProvider, diagnoseMcpCors, finishMcpOAuth, flattenContent, readOAuthCallback, renderMcpInstructions };
671
+ export type { BrowserOAuthProviderOptions, ConnectMcpOptions, ConnectedMcp, EnterpriseAssertionAlgorithm, EnterpriseAssertionAudience, EnterpriseAssertionType, EnterpriseIdpOptions, EnterpriseOAuthHop, EnterpriseOAuthLog, EnterpriseOAuthProviderOptions, EnterprisePrivateKey, McpCatalogEntry, McpHttpServerConfig, McpOAuthCallback, McpOAuthRequestOptions, McpOAuthStorage, McpServerInstructions, McpServerResult };
package/dist/mcp.js CHANGED
@@ -1,25 +1,32 @@
1
1
  import {
2
2
  IndexedDBVault,
3
- createLogger
4
- } from "./chunk-T6LZW7ML.js";
3
+ MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER,
4
+ MCP_INSTRUCTIONS_MAX_CHARS_TOTAL,
5
+ cleanMcpInstructions,
6
+ createLogger,
7
+ dropStructuredDuplicates,
8
+ isStructuredContent,
9
+ markMcpTool,
10
+ outputSchemaNote,
11
+ renderMcpInstructions,
12
+ withStructuredContent
13
+ } from "./chunk-A6ZJALLU.js";
5
14
  import "./chunk-CTXDKSDD.js";
6
15
 
7
16
  // src/mcp/http.ts
8
17
  import {
9
18
  auth as auth2,
19
+ Client,
20
+ StreamableHTTPClientTransport,
10
21
  UnauthorizedError
11
- } from "@modelcontextprotocol/sdk/client/auth.js";
12
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
13
- import {
14
- StreamableHTTPClientTransport
15
- } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
16
- import { ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
22
+ } from "@modelcontextprotocol/client";
23
+ import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/client/validators/cf-worker";
17
24
  import { dynamicTool, jsonSchema } from "ai";
18
25
 
19
26
  // src/mcp/oauth.ts
20
27
  import {
21
28
  auth
22
- } from "@modelcontextprotocol/sdk/client/auth.js";
29
+ } from "@modelcontextprotocol/client";
23
30
  var VaultOAuthStorage = class {
24
31
  vault;
25
32
  constructor(opts = {}) {
@@ -232,11 +239,13 @@ var BrowserOAuthProvider = class {
232
239
  }
233
240
  /**
234
241
  * Called by the SDK when the server rejects what we hold: `'tokens'` after an
235
- * `invalid_grant` (dead refresh token), `'all'` after an `invalid_client`
236
- * (the AS forgot our dynamic registration). `'client'`, `'verifier'` and
237
- * `'discovery'` are in its type and handled the same way: one key each.
238
- * Clearing lets the SDK re-discover, re-register and re-authorize without the
239
- * user clearing site data.
242
+ * `invalid_grant` (dead refresh token); `'client'` and then `'tokens'` after
243
+ * an `invalid_client` (the AS forgot our dynamic registration) - what
244
+ * discovery found is kept on purpose, the SDK checks the next callback
245
+ * against it. `'verifier'` and `'discovery'` are in its type and handled the
246
+ * same way: one key each. `'all'` is what {@link reset} asks for. Clearing
247
+ * lets the SDK re-register and re-authorize without the user clearing site
248
+ * data.
240
249
  */
241
250
  async invalidateCredentials(scope) {
242
251
  const targets = scope === "all" ? ["tokens", "client", "verifier", "state", "discovery"] : [scope];
@@ -299,14 +308,23 @@ var finishMcpOAuth = async (provider, callback, opts = {}) => {
299
308
  if (!await provider.verifyState(callback.state)) {
300
309
  throw new Error("Authorization state mismatch; refusing to exchange the code (possible CSRF)");
301
310
  }
311
+ const discovery = await provider.discoveryState();
302
312
  checkAuthorizationResponseIssuer(
303
313
  callback.iss,
304
- await provider.discoveryState(),
314
+ discovery,
305
315
  (await provider.clientInformation())?.issuer
306
316
  );
317
+ if (!discovery) {
318
+ throw new Error(
319
+ "Authorization cannot be completed: the record of which authorization server it was started with is not in the store (started by an older version, or cleared in between); start the authorization again"
320
+ );
321
+ }
307
322
  const result = await auth(provider, {
308
323
  serverUrl: provider.serverUrl,
309
324
  authorizationCode: callback.code,
325
+ // The SDK runs its own RFC 9207 check inside `auth()`, after ours: without
326
+ // the value it would read a response that carried `iss` as one that did not.
327
+ iss: callback.iss,
310
328
  fetchFn: opts.fetch
311
329
  });
312
330
  if (result !== "AUTHORIZED") {
@@ -319,16 +337,23 @@ var beginMcpOAuth = async (provider, opts = {}) => {
319
337
  };
320
338
 
321
339
  // src/mcp/http.ts
322
- var MAX_LIST_PAGES = 100;
323
- var listAllTools = async (client) => {
340
+ var MAX_TOOL_LIST_PAGES = 100;
341
+ var listAllTools = async (client, onTruncated) => {
324
342
  const all = [];
325
343
  let cursor;
326
- for (let page = 0; page < MAX_LIST_PAGES; page += 1) {
327
- const res = await client.listTools(cursor ? { cursor } : void 0);
344
+ const seen = /* @__PURE__ */ new Set();
345
+ for (let page = 0; page < MAX_TOOL_LIST_PAGES; page += 1) {
346
+ const res = await client.request({
347
+ method: "tools/list",
348
+ params: cursor ? { cursor } : void 0
349
+ });
328
350
  all.push(...res.tools);
329
- cursor = res.nextCursor;
330
- if (!cursor) break;
351
+ const next = typeof res.nextCursor === "string" && res.nextCursor ? res.nextCursor : void 0;
352
+ if (!next || seen.has(next)) return all;
353
+ seen.add(next);
354
+ cursor = next;
331
355
  }
356
+ onTruncated?.();
332
357
  return all;
333
358
  };
334
359
  var ConnectTimeoutError = class extends Error {
@@ -370,6 +395,19 @@ var flattenContent = (content) => {
370
395
  if (allText) return parts.map((p) => p.text).join("\n");
371
396
  return parts.map((p) => p?.type === "text" && typeof p.text === "string" ? p.text : p);
372
397
  };
398
+ var OUTPUT_SCHEMA_ERROR_MAX_CHARS = 200;
399
+ var outputSchemaViolation = (toolName, result, validate) => {
400
+ if (result.isError === true) return void 0;
401
+ if (result.structuredContent === void 0) {
402
+ return `Tool ${toolName} has an output schema but did not return structured content`;
403
+ }
404
+ try {
405
+ const checked = validate(result.structuredContent);
406
+ return checked.valid ? void 0 : `Structured content does not match the tool's output schema: ${checked.errorMessage}`;
407
+ } catch (err) {
408
+ return `Failed to validate structured content: ${err instanceof Error ? err.message : String(err)}`;
409
+ }
410
+ };
373
411
  var asEnterpriseProvider = (provider) => {
374
412
  const p = provider;
375
413
  return typeof p.extension === "string" && typeof p.authorize === "function" && typeof p.transportFetch === "function" ? provider : void 0;
@@ -385,13 +423,21 @@ var refreshOnly = (p) => ({
385
423
  get clientMetadata() {
386
424
  return p.clientMetadata;
387
425
  },
388
- clientInformation: () => p.clientInformation(),
426
+ get clientMetadataUrl() {
427
+ return p.clientMetadataUrl;
428
+ },
429
+ // The second argument is the authorization server the SDK resolved: a
430
+ // provider that keeps credentials per issuer reads and writes by it.
431
+ clientInformation: (ctx) => p.clientInformation(ctx),
389
432
  saveClientInformation: p.saveClientInformation?.bind(p),
390
- tokens: () => p.tokens(),
391
- saveTokens: (t) => p.saveTokens(t),
433
+ tokens: (ctx) => p.tokens(ctx),
434
+ saveTokens: (t, ctx) => p.saveTokens(t, ctx),
392
435
  invalidateCredentials: p.invalidateCredentials?.bind(p),
393
436
  addClientAuthentication: p.addClientAuthentication?.bind(p),
394
437
  validateResourceURL: p.validateResourceURL?.bind(p),
438
+ // What a refresh request is made of, when the provider says so.
439
+ scopeForRefresh: p.scopeForRefresh?.bind(p),
440
+ dpop: p.dpop?.bind(p),
395
441
  codeVerifier: () => p.codeVerifier(),
396
442
  state: () => {
397
443
  throw new RefreshOnlyAbort();
@@ -450,6 +496,10 @@ var diagnoseMcpCors = async (url, fetchFn = globalThis.fetch) => {
450
496
  }
451
497
  return hints.join(" ");
452
498
  };
499
+ var warnTruncated = (log, name) => log(
500
+ "warn",
501
+ `[mcp] ${name}: tools/list still paginating after ${MAX_TOOL_LIST_PAGES} pages; the rest of the tools are not mounted`
502
+ );
453
503
  var openConnection = async (name, cfg, opts, log) => {
454
504
  let client;
455
505
  let timedOut = false;
@@ -504,6 +554,15 @@ var connectAndList = async (name, cfg, opts, log, onClient) => {
504
554
  const transport = new StreamableHTTPClientTransport(new URL(cfg.url), {
505
555
  requestInit: headers ? { headers } : void 0,
506
556
  authProvider: cfg.authProvider,
557
+ // A 403 `insufficient_scope` in the middle of a session. A provider
558
+ // without a human step (no `redirectUrl`: the enterprise one) may ask
559
+ // again for the wider scope, once per request - the SDK's cap. One WITH a
560
+ // human step - in a browser nearly all of them - never does: the SDK would
561
+ // skip the refresh and start a new authorization from inside a tool call,
562
+ // replacing the stored state and PKCE verifier each time the model tried
563
+ // the tool again. The call fails with the scope the server asked for, and
564
+ // the host decides. The Node sibling's rule.
565
+ onInsufficientScope: cfg.authProvider?.redirectUrl ? "throw" : "reauthorize",
507
566
  // The enterprise provider reports a refused grant itself: a short typed
508
567
  // error for the caller, the server's words (redacted) to the log.
509
568
  fetch: cfg.authProvider && asEnterpriseProvider(cfg.authProvider)?.transportFetch(cfg.fetch, opts.onLog) || cfg.fetch,
@@ -521,10 +580,10 @@ var connectAndList = async (name, cfg, opts, log, onClient) => {
521
580
  await client.connect(transport);
522
581
  if (opts.onToolsChanged) {
523
582
  const notify = opts.onToolsChanged;
524
- client.setNotificationHandler(ToolListChangedNotificationSchema, () => notify(name));
583
+ client.setNotificationHandler("notifications/tools/list_changed", () => notify(name));
525
584
  }
526
- const listed = await listAllTools(client);
527
- return { name, client, listed };
585
+ const listed = await listAllTools(client, () => warnTruncated(log, name));
586
+ return { name, client, listed, instructions: cleanMcpInstructions(client.getInstructions()) };
528
587
  };
529
588
  var connectMcpHttp = async (servers, opts = {}) => {
530
589
  const log = opts.onLog ?? (() => {
@@ -533,6 +592,8 @@ var connectMcpHttp = async (servers, opts = {}) => {
533
592
  const tools = {};
534
593
  const catalog = [];
535
594
  const results = [];
595
+ const instructions = [];
596
+ const instructionsOf = /* @__PURE__ */ new Map();
536
597
  const mountedKeys = /* @__PURE__ */ new Map();
537
598
  const mountTools = (name, client, listed) => {
538
599
  const prefix = `${sanitizeName(name)}__`;
@@ -543,6 +604,7 @@ var connectMcpHttp = async (servers, opts = {}) => {
543
604
  if (catalog[i].server === name) catalog.splice(i, 1);
544
605
  }
545
606
  const keys = [];
607
+ let schemaValidator;
546
608
  let mounted = 0;
547
609
  for (const t of listed) {
548
610
  const prefixed = prefix + sanitizeName(t.name);
@@ -563,23 +625,55 @@ var connectMcpHttp = async (servers, opts = {}) => {
563
625
  }
564
626
  const description = t.description ?? "";
565
627
  const readOnly = t.annotations?.readOnlyHint === true;
628
+ let outputValidator;
629
+ const outputValidatorOf = () => {
630
+ if (!t.outputSchema || outputValidator) return outputValidator;
631
+ try {
632
+ schemaValidator ??= new CfWorkerJsonSchemaValidator();
633
+ outputValidator = schemaValidator.getValidator(t.outputSchema);
634
+ } catch (err) {
635
+ const reason = (err instanceof Error ? err.message : String(err)).slice(
636
+ 0,
637
+ OUTPUT_SCHEMA_ERROR_MAX_CHARS
638
+ );
639
+ throw new Error(`Tool '${t.name}' has an invalid outputSchema: ${reason}`);
640
+ }
641
+ return outputValidator;
642
+ };
566
643
  tools[key] = dynamicTool({
567
644
  description,
568
645
  inputSchema: jsonSchema(t.inputSchema),
569
646
  execute: async (args, options) => {
570
- const res = await client.callTool(
571
- { name: t.name, arguments: args ?? {} },
572
- void 0,
647
+ const validate = outputValidatorOf();
648
+ const res = await client.request(
649
+ {
650
+ method: "tools/call",
651
+ params: { name: t.name, arguments: args ?? {} }
652
+ },
573
653
  options?.abortSignal ? { signal: options.abortSignal } : void 0
574
654
  );
575
- const flat = flattenContent(res.content);
655
+ let schemaNote;
656
+ const violation = validate && outputSchemaViolation(t.name, res, validate);
657
+ if (violation) {
658
+ schemaNote = outputSchemaNote(t.name, violation);
659
+ log(
660
+ "warn",
661
+ `[mcp] ${key}: result does not follow the declared outputSchema - ${violation}; passed on with a note`
662
+ );
663
+ }
576
664
  if (res.isError) {
577
- throw new Error(typeof flat === "string" ? flat : JSON.stringify(flat));
665
+ const flat2 = flattenContent(res.content);
666
+ throw new Error(typeof flat2 === "string" ? flat2 : JSON.stringify(flat2));
578
667
  }
579
- return flat;
668
+ const structured = isStructuredContent(res.structuredContent) ? res.structuredContent : void 0;
669
+ const flat = flattenContent(
670
+ structured ? dropStructuredDuplicates(res.content, structured) : res.content
671
+ );
672
+ return withStructuredContent(flat, structured, schemaNote);
580
673
  }
581
674
  });
582
675
  if (readOnly) tools[key].readOnly = true;
676
+ markMcpTool(tools[key], name, instructionsOf.get(name));
583
677
  catalog.push({ name: key, description, server: name, ...readOnly ? { readOnly } : {} });
584
678
  keys.push(key);
585
679
  mounted += 1;
@@ -601,6 +695,14 @@ var connectMcpHttp = async (servers, opts = {}) => {
601
695
  continue;
602
696
  }
603
697
  clients.set(server.name, server.client);
698
+ if (server.instructions) {
699
+ log(
700
+ "info",
701
+ `[mcp] ${server.name}: the server sent instructions (${server.instructions.length} chars)`
702
+ );
703
+ instructions.push({ server: server.name, instructions: server.instructions });
704
+ instructionsOf.set(server.name, server.instructions);
705
+ }
604
706
  mountTools(server.name, server.client, server.listed);
605
707
  results.push({ name: server.name, connected: true });
606
708
  }
@@ -608,10 +710,11 @@ var connectMcpHttp = async (servers, opts = {}) => {
608
710
  tools,
609
711
  catalog,
610
712
  results,
713
+ instructions,
611
714
  refreshServer: async (name) => {
612
715
  const client = clients.get(name);
613
716
  if (!client) throw new Error(`MCP server "${name}" is not connected`);
614
- mountTools(name, client, await listAllTools(client));
717
+ mountTools(name, client, await listAllTools(client, () => warnTruncated(log, name)));
615
718
  },
616
719
  close: async () => {
617
720
  await Promise.allSettled([...clients.values()].map((c) => c.close()));
@@ -620,10 +723,13 @@ var connectMcpHttp = async (servers, opts = {}) => {
620
723
  };
621
724
 
622
725
  // src/mcp/index.ts
623
- import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/sdk/client/auth.js";
726
+ import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/client";
624
727
 
625
728
  // src/mcp/enterprise-oauth.ts
626
- import { auth as auth3 } from "@modelcontextprotocol/sdk/client/auth.js";
729
+ import {
730
+ auth as auth3,
731
+ OAuthError
732
+ } from "@modelcontextprotocol/client";
627
733
  var ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION = "io.modelcontextprotocol/enterprise-managed-authorization";
628
734
  var GRANT_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
629
735
  var GRANT_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
@@ -1354,7 +1460,7 @@ var BrowserEnterpriseOAuthProvider = class {
1354
1460
  throw new EnterpriseOAuthError(
1355
1461
  "discovery",
1356
1462
  `Enterprise MCP authorization: discovery failed (${message})`,
1357
- oauthCode(err?.errorCode)
1463
+ err instanceof OAuthError ? oauthCode(err.code) : void 0
1358
1464
  );
1359
1465
  }
1360
1466
  }
@@ -1369,6 +1475,8 @@ export {
1369
1475
  BrowserOAuthProvider,
1370
1476
  ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION,
1371
1477
  EnterpriseOAuthError,
1478
+ MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER,
1479
+ MCP_INSTRUCTIONS_MAX_CHARS_TOTAL,
1372
1480
  MemoryOAuthStorage,
1373
1481
  UnauthorizedError2 as UnauthorizedError,
1374
1482
  VaultOAuthStorage,
@@ -1379,6 +1487,7 @@ export {
1379
1487
  diagnoseMcpCors,
1380
1488
  finishMcpOAuth,
1381
1489
  flattenContent,
1382
- readOAuthCallback
1490
+ readOAuthCallback,
1491
+ renderMcpInstructions
1383
1492
  };
1384
1493
  //# sourceMappingURL=mcp.js.map