@dudko.dev/agent-web 0.0.39 → 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,9 +1,6 @@
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
 
9
6
  /**
@@ -38,7 +35,7 @@ declare const renderMcpInstructions: (list: readonly McpServerInstructions[] | u
38
35
  * A remote MCP server reached over StreamableHTTP. Browsers can ONLY speak the
39
36
  * HTTP transport — stdio (child processes) is Node-only and intentionally
40
37
  * unsupported here. This connector lives behind the `@dudko.dev/agent-web/mcp`
41
- * subpath so `@modelcontextprotocol/sdk` never enters the core bundle.
38
+ * subpath so `@modelcontextprotocol/client` never enters the core bundle.
42
39
  *
43
40
  * Three ways to authenticate, in ascending order of capability:
44
41
  * 1. `headers` — a static token you already hold.
@@ -246,7 +243,8 @@ interface BrowserOAuthProviderOptions {
246
243
  * `authorization_response_iss_parameter_supported: true`;
247
244
  * - no stored discovery state (storage written by an older version): `iss` is
248
245
  * compared with the issuer stamped on the stored client information, and with
249
- * 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.)
250
248
  *
251
249
  * The Node package carries the same function; change both.
252
250
  */
@@ -296,11 +294,13 @@ declare class BrowserOAuthProvider implements OAuthClientProvider {
296
294
  redirectToAuthorization(url: URL): Promise<void>;
297
295
  /**
298
296
  * Called by the SDK when the server rejects what we hold: `'tokens'` after an
299
- * `invalid_grant` (dead refresh token), `'all'` after an `invalid_client`
300
- * (the AS forgot our dynamic registration). `'client'`, `'verifier'` and
301
- * `'discovery'` are in its type and handled the same way: one key each.
302
- * Clearing lets the SDK re-discover, re-register and re-authorize without the
303
- * 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.
304
304
  */
305
305
  invalidateCredentials(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): Promise<void>;
306
306
  /** True when there is no access token, or it expires within the skew window. */
@@ -340,6 +340,12 @@ declare const readOAuthCallback: (input?: string | URL) => McpOAuthCallback | un
340
340
  * an error, when `state` doesn't match what we issued, when `iss` names another
341
341
  * authorization server, or when the exchange fails — never resolves on a
342
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.
343
349
  */
344
350
  declare const finishMcpOAuth: (provider: BrowserOAuthProvider, callback: McpOAuthCallback, opts?: McpOAuthRequestOptions) => Promise<void>;
345
351
  /**
package/dist/mcp.d.ts CHANGED
@@ -1,9 +1,6 @@
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
 
9
6
  /**
@@ -38,7 +35,7 @@ declare const renderMcpInstructions: (list: readonly McpServerInstructions[] | u
38
35
  * A remote MCP server reached over StreamableHTTP. Browsers can ONLY speak the
39
36
  * HTTP transport — stdio (child processes) is Node-only and intentionally
40
37
  * unsupported here. This connector lives behind the `@dudko.dev/agent-web/mcp`
41
- * subpath so `@modelcontextprotocol/sdk` never enters the core bundle.
38
+ * subpath so `@modelcontextprotocol/client` never enters the core bundle.
42
39
  *
43
40
  * Three ways to authenticate, in ascending order of capability:
44
41
  * 1. `headers` — a static token you already hold.
@@ -246,7 +243,8 @@ interface BrowserOAuthProviderOptions {
246
243
  * `authorization_response_iss_parameter_supported: true`;
247
244
  * - no stored discovery state (storage written by an older version): `iss` is
248
245
  * compared with the issuer stamped on the stored client information, and with
249
- * 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.)
250
248
  *
251
249
  * The Node package carries the same function; change both.
252
250
  */
@@ -296,11 +294,13 @@ declare class BrowserOAuthProvider implements OAuthClientProvider {
296
294
  redirectToAuthorization(url: URL): Promise<void>;
297
295
  /**
298
296
  * Called by the SDK when the server rejects what we hold: `'tokens'` after an
299
- * `invalid_grant` (dead refresh token), `'all'` after an `invalid_client`
300
- * (the AS forgot our dynamic registration). `'client'`, `'verifier'` and
301
- * `'discovery'` are in its type and handled the same way: one key each.
302
- * Clearing lets the SDK re-discover, re-register and re-authorize without the
303
- * 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.
304
304
  */
305
305
  invalidateCredentials(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): Promise<void>;
306
306
  /** True when there is no access token, or it expires within the skew window. */
@@ -340,6 +340,12 @@ declare const readOAuthCallback: (input?: string | URL) => McpOAuthCallback | un
340
340
  * an error, when `state` doesn't match what we issued, when `iss` names another
341
341
  * authorization server, or when the exchange fails — never resolves on a
342
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.
343
349
  */
344
350
  declare const finishMcpOAuth: (provider: BrowserOAuthProvider, callback: McpOAuthCallback, opts?: McpOAuthRequestOptions) => Promise<void>;
345
351
  /**
package/dist/mcp.js CHANGED
@@ -16,22 +16,17 @@ import "./chunk-CTXDKSDD.js";
16
16
  // src/mcp/http.ts
17
17
  import {
18
18
  auth as auth2,
19
+ Client,
20
+ StreamableHTTPClientTransport,
19
21
  UnauthorizedError
20
- } from "@modelcontextprotocol/sdk/client/auth.js";
21
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
22
- import {
23
- StreamableHTTPClientTransport
24
- } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
25
- import {
26
- CallToolResultSchema,
27
- ToolListChangedNotificationSchema
28
- } from "@modelcontextprotocol/sdk/types.js";
22
+ } from "@modelcontextprotocol/client";
23
+ import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/client/validators/cf-worker";
29
24
  import { dynamicTool, jsonSchema } from "ai";
30
25
 
31
26
  // src/mcp/oauth.ts
32
27
  import {
33
28
  auth
34
- } from "@modelcontextprotocol/sdk/client/auth.js";
29
+ } from "@modelcontextprotocol/client";
35
30
  var VaultOAuthStorage = class {
36
31
  vault;
37
32
  constructor(opts = {}) {
@@ -244,11 +239,13 @@ var BrowserOAuthProvider = class {
244
239
  }
245
240
  /**
246
241
  * Called by the SDK when the server rejects what we hold: `'tokens'` after an
247
- * `invalid_grant` (dead refresh token), `'all'` after an `invalid_client`
248
- * (the AS forgot our dynamic registration). `'client'`, `'verifier'` and
249
- * `'discovery'` are in its type and handled the same way: one key each.
250
- * Clearing lets the SDK re-discover, re-register and re-authorize without the
251
- * 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.
252
249
  */
253
250
  async invalidateCredentials(scope) {
254
251
  const targets = scope === "all" ? ["tokens", "client", "verifier", "state", "discovery"] : [scope];
@@ -311,14 +308,23 @@ var finishMcpOAuth = async (provider, callback, opts = {}) => {
311
308
  if (!await provider.verifyState(callback.state)) {
312
309
  throw new Error("Authorization state mismatch; refusing to exchange the code (possible CSRF)");
313
310
  }
311
+ const discovery = await provider.discoveryState();
314
312
  checkAuthorizationResponseIssuer(
315
313
  callback.iss,
316
- await provider.discoveryState(),
314
+ discovery,
317
315
  (await provider.clientInformation())?.issuer
318
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
+ }
319
322
  const result = await auth(provider, {
320
323
  serverUrl: provider.serverUrl,
321
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,
322
328
  fetchFn: opts.fetch
323
329
  });
324
330
  if (result !== "AUTHORIZED") {
@@ -331,16 +337,23 @@ var beginMcpOAuth = async (provider, opts = {}) => {
331
337
  };
332
338
 
333
339
  // src/mcp/http.ts
334
- var MAX_LIST_PAGES = 100;
335
- var listAllTools = async (client) => {
340
+ var MAX_TOOL_LIST_PAGES = 100;
341
+ var listAllTools = async (client, onTruncated) => {
336
342
  const all = [];
337
343
  let cursor;
338
- for (let page = 0; page < MAX_LIST_PAGES; page += 1) {
339
- 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
+ });
340
350
  all.push(...res.tools);
341
- cursor = res.nextCursor;
342
- 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;
343
355
  }
356
+ onTruncated?.();
344
357
  return all;
345
358
  };
346
359
  var ConnectTimeoutError = class extends Error {
@@ -382,10 +395,19 @@ var flattenContent = (content) => {
382
395
  if (allText) return parts.map((p) => p.text).join("\n");
383
396
  return parts.map((p) => p?.type === "text" && typeof p.text === "string" ? p.text : p);
384
397
  };
385
- var capturingResultSchema = (onResult) => CallToolResultSchema.refine((result) => {
386
- onResult(result);
387
- return true;
388
- });
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
+ };
389
411
  var asEnterpriseProvider = (provider) => {
390
412
  const p = provider;
391
413
  return typeof p.extension === "string" && typeof p.authorize === "function" && typeof p.transportFetch === "function" ? provider : void 0;
@@ -401,13 +423,21 @@ var refreshOnly = (p) => ({
401
423
  get clientMetadata() {
402
424
  return p.clientMetadata;
403
425
  },
404
- 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),
405
432
  saveClientInformation: p.saveClientInformation?.bind(p),
406
- tokens: () => p.tokens(),
407
- saveTokens: (t) => p.saveTokens(t),
433
+ tokens: (ctx) => p.tokens(ctx),
434
+ saveTokens: (t, ctx) => p.saveTokens(t, ctx),
408
435
  invalidateCredentials: p.invalidateCredentials?.bind(p),
409
436
  addClientAuthentication: p.addClientAuthentication?.bind(p),
410
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),
411
441
  codeVerifier: () => p.codeVerifier(),
412
442
  state: () => {
413
443
  throw new RefreshOnlyAbort();
@@ -466,6 +496,10 @@ var diagnoseMcpCors = async (url, fetchFn = globalThis.fetch) => {
466
496
  }
467
497
  return hints.join(" ");
468
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
+ );
469
503
  var openConnection = async (name, cfg, opts, log) => {
470
504
  let client;
471
505
  let timedOut = false;
@@ -520,6 +554,15 @@ var connectAndList = async (name, cfg, opts, log, onClient) => {
520
554
  const transport = new StreamableHTTPClientTransport(new URL(cfg.url), {
521
555
  requestInit: headers ? { headers } : void 0,
522
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",
523
566
  // The enterprise provider reports a refused grant itself: a short typed
524
567
  // error for the caller, the server's words (redacted) to the log.
525
568
  fetch: cfg.authProvider && asEnterpriseProvider(cfg.authProvider)?.transportFetch(cfg.fetch, opts.onLog) || cfg.fetch,
@@ -537,9 +580,9 @@ var connectAndList = async (name, cfg, opts, log, onClient) => {
537
580
  await client.connect(transport);
538
581
  if (opts.onToolsChanged) {
539
582
  const notify = opts.onToolsChanged;
540
- client.setNotificationHandler(ToolListChangedNotificationSchema, () => notify(name));
583
+ client.setNotificationHandler("notifications/tools/list_changed", () => notify(name));
541
584
  }
542
- const listed = await listAllTools(client);
585
+ const listed = await listAllTools(client, () => warnTruncated(log, name));
543
586
  return { name, client, listed, instructions: cleanMcpInstructions(client.getInstructions()) };
544
587
  };
545
588
  var connectMcpHttp = async (servers, opts = {}) => {
@@ -561,6 +604,7 @@ var connectMcpHttp = async (servers, opts = {}) => {
561
604
  if (catalog[i].server === name) catalog.splice(i, 1);
562
605
  }
563
606
  const keys = [];
607
+ let schemaValidator;
564
608
  let mounted = 0;
565
609
  for (const t of listed) {
566
610
  const prefixed = prefix + sanitizeName(t.name);
@@ -581,28 +625,40 @@ var connectMcpHttp = async (servers, opts = {}) => {
581
625
  }
582
626
  const description = t.description ?? "";
583
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
+ };
584
643
  tools[key] = dynamicTool({
585
644
  description,
586
645
  inputSchema: jsonSchema(t.inputSchema),
587
646
  execute: async (args, options) => {
588
- let res;
647
+ const validate = outputValidatorOf();
648
+ const res = await client.request(
649
+ {
650
+ method: "tools/call",
651
+ params: { name: t.name, arguments: args ?? {} }
652
+ },
653
+ options?.abortSignal ? { signal: options.abortSignal } : void 0
654
+ );
589
655
  let schemaNote;
590
- let received;
591
- try {
592
- res = await client.callTool(
593
- { name: t.name, arguments: args ?? {} },
594
- capturingResultSchema((r) => {
595
- received = r;
596
- }),
597
- options?.abortSignal ? { signal: options.abortSignal } : void 0
598
- );
599
- } catch (err) {
600
- if (!received) throw err;
601
- res = received;
602
- schemaNote = outputSchemaNote(t.name, err);
656
+ const violation = validate && outputSchemaViolation(t.name, res, validate);
657
+ if (violation) {
658
+ schemaNote = outputSchemaNote(t.name, violation);
603
659
  log(
604
660
  "warn",
605
- `[mcp] ${key}: result does not follow the declared outputSchema - ${err instanceof Error ? err.message : String(err)}; passed on with a note`
661
+ `[mcp] ${key}: result does not follow the declared outputSchema - ${violation}; passed on with a note`
606
662
  );
607
663
  }
608
664
  if (res.isError) {
@@ -658,7 +714,7 @@ var connectMcpHttp = async (servers, opts = {}) => {
658
714
  refreshServer: async (name) => {
659
715
  const client = clients.get(name);
660
716
  if (!client) throw new Error(`MCP server "${name}" is not connected`);
661
- mountTools(name, client, await listAllTools(client));
717
+ mountTools(name, client, await listAllTools(client, () => warnTruncated(log, name)));
662
718
  },
663
719
  close: async () => {
664
720
  await Promise.allSettled([...clients.values()].map((c) => c.close()));
@@ -667,10 +723,13 @@ var connectMcpHttp = async (servers, opts = {}) => {
667
723
  };
668
724
 
669
725
  // src/mcp/index.ts
670
- import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/sdk/client/auth.js";
726
+ import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/client";
671
727
 
672
728
  // src/mcp/enterprise-oauth.ts
673
- import { auth as auth3 } from "@modelcontextprotocol/sdk/client/auth.js";
729
+ import {
730
+ auth as auth3,
731
+ OAuthError
732
+ } from "@modelcontextprotocol/client";
674
733
  var ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION = "io.modelcontextprotocol/enterprise-managed-authorization";
675
734
  var GRANT_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
676
735
  var GRANT_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
@@ -1401,7 +1460,7 @@ var BrowserEnterpriseOAuthProvider = class {
1401
1460
  throw new EnterpriseOAuthError(
1402
1461
  "discovery",
1403
1462
  `Enterprise MCP authorization: discovery failed (${message})`,
1404
- oauthCode(err?.errorCode)
1463
+ err instanceof OAuthError ? oauthCode(err.code) : void 0
1405
1464
  );
1406
1465
  }
1407
1466
  }