@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/README.md CHANGED
@@ -59,8 +59,8 @@ imported):
59
59
  npm install @ai-sdk/openai # or @ai-sdk/anthropic, @ai-sdk/google, @ai-sdk/xai, @ai-sdk/deepseek, @ai-sdk/openai-compatible
60
60
  # local WebGPU models
61
61
  npm install @browser-ai/web-llm @mlc-ai/web-llm
62
- # optional: HTTP MCP
63
- npm install @modelcontextprotocol/sdk
62
+ # optional: HTTP MCP (the official 2.x client SDK; see "Upgrading to the 2.x MCP SDK")
63
+ npm install @modelcontextprotocol/client
64
64
  ```
65
65
 
66
66
  ### CDN / standalone bundle (no build step)
@@ -212,6 +212,14 @@ Browsers can only speak the **HTTP (StreamableHTTP)** transport — stdio MCP is
212
212
  Node-only. The connector lives in the `./mcp` subpath so the MCP SDK never
213
213
  enters your core bundle.
214
214
 
215
+ The MCP client is the official 2.x SDK, **`@modelcontextprotocol/client`** (an
216
+ optional peer: install it when you import `./mcp`; `@modelcontextprotocol/sdk`
217
+ 1.x is no longer used — [what to change](#upgrading-to-the-2x-mcp-sdk)). It
218
+ negotiates the 2025 protocol revisions with the unchanged `initialize`
219
+ handshake, so servers see the same requests and the same headers as before. A
220
+ server that speaks **only** the 2026-07-28 revision fails to connect, at once,
221
+ with `Unsupported protocol version: 2025-11-25` in `results[].error`.
222
+
215
223
  Pass several servers at once — they connect concurrently, each with its own
216
224
  deadline (`connectTimeoutMs`, default 30 s), every page of a paginated
217
225
  `tools/list` is read, and tools a server marks `readOnlyHint` are treated as
@@ -219,7 +227,23 @@ read-only by the consent gate. A failing server is reported in `results`; the
219
227
  others still mount. With hundreds of tools the agent switches to tool search
220
228
  automatically (see [docs/capabilities.md](docs/capabilities.md#large-tool-catalogues-several-mcp-servers)).
221
229
 
222
- `connectMcpHttp` returns `{ tools, catalog, results, refreshServer, close }`.
230
+ A server's `instructions` (from its `initialize` result) reach the planner's and
231
+ the executor's system prompts, marked as third-party text and capped; a tool's
232
+ `structuredContent` reaches the model once, as JSON, and a result that breaks
233
+ its `outputSchema` is passed on with a note instead of failing the call. See
234
+ [docs/capabilities.md](docs/capabilities.md#mcp-server-instructions-and-structured-results);
235
+ the instructions are a prompt-injection surface
236
+ ([docs/security.md](docs/security.md#mcp-server-instructions-third-party-text-in-a-system-prompt)) —
237
+ `mcpInstructions: false` switches them off.
238
+
239
+ A tool the server refuses with a JSON-RPC error (what a 2.x server answers for
240
+ an unknown tool, `-32602`) is a failed call like an `isError` result; its
241
+ message is the server's own, without the `MCP error <code>: ` prefix the 1.x
242
+ SDK added — read `error.code` for the number. A paginated `tools/list` is
243
+ followed for up to 100 pages (a repeated cursor ends the walk; past the cap a
244
+ `warn` line says the rest is not mounted).
245
+
246
+ `connectMcpHttp` returns `{ tools, catalog, results, instructions, refreshServer, close }`.
223
247
  `tools` and `catalog` are mutated **in place** by `refreshServer(name)`, so an
224
248
  agent built from them picks up a server's new tool list (react to it via the
225
249
  `onToolsChanged` option) without being rebuilt. Filtering is plain object work:
@@ -279,6 +303,41 @@ on `provider.authorizationUrl` and the app decides when to use it.
279
303
  (local development). Change any field through `clientMetadata`.
280
304
  - `provider.reset()` forgets tokens, registration and discovery - use it when a
281
305
  server moved to another authorization server.
306
+ - **Discovery is stored** next to the tokens (the authorization server and its
307
+ metadata), so later calls skip it and the issuer check has something to
308
+ compare with. A code is exchanged only when that record is still there: a
309
+ flow whose discovery state is gone (started by a version that did not keep
310
+ it, or storage was cleared in between) is refused by `finishMcpOAuth` with
311
+ `Authorization cannot be completed: ... start the authorization again`.
312
+ Tokens already in storage are not touched; send the user to authorize again
313
+ and the new redirect completes.
314
+ - **Credentials belong to the authorization server that issued them.** The
315
+ registration and the tokens are stored with an `issuer` stamp and are never
316
+ presented to another authorization server: stamped for a different one, they
317
+ are read as absent and a new authorization is asked for. Storage written
318
+ before the stamp existed keeps working — its values are used as they are and
319
+ stamped on first use (the SDK says so once on the console). A custom
320
+ `McpOAuthStorage` only has to return what it was given.
321
+ - **A token endpoint must be https** (or loopback). The SDK refuses to send a
322
+ code or a refresh token to a plain-http token endpoint; the error names it,
323
+ and no new authorization is started in its place.
324
+ - **The metadata must be the server's own.** Authorization server metadata
325
+ whose `issuer` is not the URL it was fetched for is refused by the SDK
326
+ (RFC 8414 section 3.3): the connect fails with the two issuers named, and
327
+ nothing is registered. The 1.x SDK accepted such a document.
328
+ - **`403 insufficient_scope`.** When the server answers a request with `403` and
329
+ `WWW-Authenticate: Bearer error="insufficient_scope"`, the tool call fails
330
+ with `Insufficient scope: required "<scope>"` (the SDK's
331
+ `InsufficientScopeError`, with `requiredScope`; it is **not** an
332
+ `UnauthorizedError`). No authorization is started from inside a run: a new
333
+ authorization URL in the middle of a tool call would replace the state and
334
+ PKCE verifier of the one the user may have open. Ask for the scope up front
335
+ (`scope`), or authorize again with it. A provider **without** a human step
336
+ (no `redirectUrl`: the enterprise one below) asks once for the wider scope
337
+ and retries the request once.
338
+ - **A refresh whose result cannot be saved is an error**, not a new
339
+ authorization: when storage throws while saving refreshed tokens (a full
340
+ quota, a broken vault), the connect or the tool call fails with that error.
282
341
 
283
342
  ### Enterprise-managed authorization (ID-JAG)
284
343
 
@@ -370,6 +429,17 @@ Access-Control-Allow-Headers: Content-Type, Authorization, mcp-session-id,
370
429
  Access-Control-Expose-Headers: mcp-session-id, WWW-Authenticate
371
430
  ```
372
431
 
432
+ Nothing changed here with the 2.x MCP SDK: recorded on the wire against a raw
433
+ HTTP server, the old and the new client send the same requests with the same
434
+ headers (`Accept`, `Content-Type`, then `mcp-session-id` and
435
+ `MCP-Protocol-Version` after `initialize`, `Authorization` and `Last-Event-ID`
436
+ when they apply), and the browser tests run against a server with exactly this
437
+ list. **Later:** when this package opts into the 2026-07-28 protocol revision,
438
+ requests will also carry `Mcp-Method` and `Mcp-Name` (and `Mcp-Param-*` for
439
+ tool arguments a server asks to mirror) — a server that wants to keep working
440
+ with browser clients then should add those to `Access-Control-Allow-Headers`
441
+ now.
442
+
373
443
  Each line earns its place:
374
444
 
375
445
  - **`MCP-Protocol-Version` in Allow-Headers** is the one that bites hardest. The
@@ -452,12 +522,15 @@ needs. Subagents are tools too — `createSubagentTool({ config })` runs a child
452
522
  agent in-process, `createSubagentTool({ worker, workerConfig })` isolates it in a
453
523
  Web Worker served by `serveSubagentWorker()`. Add `profiles` and the parent model
454
524
  chooses, per call, between named variants of the same subagent — another model,
455
- thinking level, limits or system prompt. Give `persistence` a store
525
+ thinking level, limits or system prompt. With `subagents: { dynamic: true }` the model
526
+ starts helpers itself (`spawn_subagent`): a sub-task, an optional role and a subset of its own
527
+ tools — a helper can only have less than the run that starts it, and its spend counts against
528
+ that run's limits. Give `persistence` a store
456
529
  (`new IndexedDBRunStore()`) and a run interrupted by a reload or a crash resumes from its
457
530
  last checkpoint with `run('', { resumeFromRunId })` — the planner does not run again and
458
531
  no finished step is repeated. `createRunControl()` steers a run that is going: `send()`
459
532
  puts a message in front of the model at the next boundary (the replanner re-checks the plan
460
- against it), `stopSubagent(id)` stops one subagent. `egress` (off by default) gives the model one safe `web_fetch` tool with allow / deny lists. `sandbox` (off by default) gives the model `run_js`: the code it wrote runs in QuickJS-in-WebAssembly inside a Web Worker that is killed at the deadline, so "I ran it" is a tool call you can see. `learning` (off by default) lets the agent write down what it figured out as skills of its own — in memory, or in the file system across sessions. Details, defaults and events:
533
+ against it), `stopSubagent(id)` stops one subagent. `egress` (off by default) gives the model one safe `web_fetch` tool with allow / deny lists. `search` (off by default) adds `web_search` over a search API you name (Tavily, Brave through a gateway, your SearXNG) or a function of yours — the key stays in the credential store. `sandbox` (off by default) gives the model `run_js`: the code it wrote runs in QuickJS-in-WebAssembly inside a Web Worker that is killed at the deadline, so "I ran it" is a tool call you can see. `media` (off by default) mounts `generate_image`, `generate_speech` and `transcribe_audio` — each only when you configure its model — writes what they make into the virtual file system instead of the context, and turns attached audio into text for a model that cannot listen. `learning` (off by default) lets the agent write down what it figured out as skills of its own — in memory, or in the file system across sessions. Details, defaults and events:
461
534
  **[docs/capabilities.md](docs/capabilities.md)**.
462
535
 
463
536
  ## Pipelines: a graph of agents
@@ -522,6 +595,8 @@ Loading a definition someone else wrote: [docs/security.md](docs/security.md#pip
522
595
  | --- | --- | --- |
523
596
  | `model` | — | a `LanguageModel` or `ProviderModelSpec` (the executor/default) |
524
597
  | `planner` / `synthesizer` | = `model` | per-stage model overrides (inherit base provider/creds if partial) |
598
+ | `executorTiers` | off | `{ light?, standard?, strong? }`, each a model like `planner`: the planner rates every step low / medium / high and the executor runs it on that tier's model; a tier that is not configured falls back to the nearest one; the smallest window among them governs the run ([model tiers](docs/capabilities.md#model-tiers-and-escalation)) |
599
+ | `escalation` | on with tiers | `false`, or `{ maxPerStep?, maxPerRun? }` (1 / 3): a step that fails in a way a stronger model could fix is retried on the next stronger tier before the replanner is asked - continuing the step, never writing twice. Nothing without tiers |
525
600
  | `credentials` | — | a `CredentialStore` for `credentialRef` keys |
526
601
  | `tools` | `{}` | host tools (`defineTool`) |
527
602
  | `availableTools` / `excludedTools` | — | whitelist / blacklist of tool names mounted from `tools` |
@@ -530,6 +605,11 @@ Loading a definition someone else wrote: [docs/security.md](docs/security.md#pip
530
605
  | `toolApproval` | autopilot | consent policy: `{ mode, rules, onRequest, timeoutMs }`; `agent.setToolApprovalMode()` |
531
606
  | `skills` | — | SKILL.md bundles (`defineSkill` / `parseSkillMarkdown` / `loadSkillFromUrl`) |
532
607
  | `egress` | off | what the **model** may fetch (`web_fetch`): `true` = any public host over https, or `{ allow, deny, protocols, allowPrivateNetwork, fetch, ... }`; a browser can't pin DNS, so prefer an `allow` list — see [Egress](docs/capabilities.md#egress-what-the-model-may-fetch) |
608
+ | `search` | off | the model may **search the web** (`web_search`: a short list of title / url / snippet): `{ provider: 'tavily' \| 'brave' \| 'searxng', credentialRef, baseURL, maxResults, allowPrivateNetwork, readOnly, fetch }` or `{ engine: fn }`. No key ships with the library and none is written in the config (`credentialRef` names it in `credentials`); the request reaches only the search API; with `egress`, results the model could not fetch are left out. Brave needs a gateway from a page (no CORS) — see [Search](docs/capabilities.md#search-finding-the-page-to-fetch) |
609
+ | `media` | off | image generation, speech and transcription as tools, each mounted only when its model is set: `{ imageModel, speechModel, transcriptionModel, maxCalls, timeoutMs, files, folder, voice, speechFormat, transcribeAttachments }`. A model is an AI SDK image / speech / transcription model object or a `ProviderModelSpec` (key by `credentialRef`). Generated files go to the virtual file system and the model gets a path, never the bytes; attached audio is transcribed to text; calls are counted in `usage.mediaCalls` (and the other media fields) and capped per run — see [Media](docs/capabilities.md#media-images-speech-and-transcription) |
610
+ | `decisionModel` | off | a **decision model** - answers a closed question with one option and a probability instead of writing text: `{ providerType: 'google', model: 'gemini-decision-1', credentialRef }` (the key stays in `credentials`; the request reaches only that API) or an object with `decide(question, { abortSignal })`. Where it is confident it replaces the replanner's continue / finish call and a pipeline node's route call; never consulted for tool approval or egress — see [Decision models](docs/capabilities.md#decision-models) |
611
+ | `decision` | `{}` | `{ confidenceThreshold, timeoutMs, replan, route }` (defaults 0.8, 5000 ms, on, on): below the threshold, on an error, a timeout or an answer that is not an option, the ordinary model call runs unchanged |
612
+ | `subagents` | off | the **model** may start helper agents itself (`spawn_subagent`): `{ dynamic: true }`, or `{ dynamic: { maxDepth, maxChildren, maxConcurrent, budgetShare, minTokens, timeoutMs, defaultTools } }`. A helper gets a subset of the caller's tools by name (read-only ones by default), a share of what is left of its budgets, the same models and the same consent gate — it can only have less than the run that starts it. See [docs/capabilities.md](docs/capabilities.md#dynamic-subagents-helpers-the-model-starts-itself) |
533
613
  | `sandbox` | off | the model may **run JavaScript it wrote** (`run_js`) and read the real output: `true`, or `{ worker, timeoutMs, memoryLimitBytes, maxOutputChars, maxCodeChars, files, engine }`. QuickJS in WebAssembly (optional peer `quickjs-emscripten`), in a Web Worker you supply (`@dudko.dev/agent-web/sandbox-worker`) that is killed at the deadline; with `createFileTools` the guest can import / require workspace files and use `fs` — see [Running code](docs/capabilities.md#running-code-the-sandbox) |
534
614
  | `learning` | off | the agent writes down lessons as skills (`save_skill` / `forget_skill`): `true` = this session, `{ store: new VfsSkillStore(vfs) }` = across sessions — see [Learning](docs/capabilities.md#learning-lessons-that-outlive-the-task) |
535
615
  | `thinking` / `stageThinking` | provider default | `true`, a level (`'low'`…`'xhigh'`, `'none'`), or `{ level, budgetTokens, includeThoughts }` |
@@ -539,6 +619,7 @@ Loading a definition someone else wrote: [docs/security.md](docs/security.md#pip
539
619
  | `promptCaching` | `true` | stable system prefixes, Anthropic breakpoints, OpenAI cache key |
540
620
  | `vision` / `inputs` | inferred | what the model takes as attachments (`run(goal, { images, files })`); see `agent.capabilities` |
541
621
  | `systemPrompt` / `prompts` | — | prepended to every phase / override any phase's prompt builder |
622
+ | `mcpInstructions` | `true` | show the model the `instructions` MCP servers send on connect (planner + executor, marked third-party, capped); `false` keeps them out |
542
623
  | `describeState` | — | serialize world state into prompt context |
543
624
  | `memory` | — | `ContextStore` (`IndexedDBStore` / `MemoryStore`); recent turns are read back into the planner prompt |
544
625
  | `sessionId` | — | names the stored conversation in `memory`, and the bucket `agent.sessionUsage()` counts into |
@@ -546,13 +627,67 @@ Loading a definition someone else wrote: [docs/security.md](docs/security.md#pip
546
627
  | `maxIterations` / `maxStepsPerTask` / `maxRevisions` | 8 / 4 / 2 | loop caps |
547
628
  | `chatTimeoutMs` | 120000 | per-call watchdog |
548
629
  | `temperature` | provider default | sampling temperature for every stage |
549
- | `budgets` | — | legacy per-phase output caps; `limits.perCall` wins, and the defaults are shares of the model's window |
630
+ | `budgets` | — | legacy per-phase output caps; `limits.perCall` wins, `0` = no cap, and the defaults are shares of the model's window (none for a phase that thinks) |
550
631
  | `clientName` | — | sent as the openai-compatible provider name and the MCP client name |
551
632
  | `logLevel` / `logger` | `'warn'` / `console` | verbosity (`'silent' \| 'error' \| 'warn' \| 'info' \| 'debug'`) and the console-like sink the logs go to |
552
633
  | `replan` / `synthesize` | `true` | toggle phases |
553
634
  | `replanAfter` | `'failure'` | replan trigger: `'failure'` \| `'always'` \| `(stepResult) => boolean \| Promise<boolean>` |
554
635
  | `compressAfterChars` | 12000 | legacy: summarize old history past this size (when `compaction` is unset) |
555
636
 
637
+ ## Upgrading to the 2.x MCP SDK
638
+
639
+ The `./mcp` subpath moved from `@modelcontextprotocol/sdk` 1.x to the official
640
+ 2.x client, `@modelcontextprotocol/client`, in one step. **The optional peer
641
+ dependency is renamed — that is the breaking change.** Nothing changes on the
642
+ wire, and nothing changes if you never import `@dudko.dev/agent-web/mcp`.
643
+
644
+ If you do import it:
645
+
646
+ 1. **Install the new package, remove the old one.**
647
+ `npm uninstall @modelcontextprotocol/sdk && npm install @modelcontextprotocol/client`
648
+ (`^2.4.0`). With only the old package installed, a bundler cannot resolve
649
+ `@modelcontextprotocol/client` and the build fails. The new SDK needs
650
+ `zod ^4.2` (this package already depends on zod 4) and declares Node >= 20
651
+ for tooling.
652
+ 2. **Import SDK types from the new package.** `McpHttpServerConfig.authProvider`
653
+ is the `OAuthClientProvider` of `@modelcontextprotocol/client`, `fetch` its
654
+ `FetchLike`, `reconnection` its `StreamableHTTPReconnectionOptions`. Change
655
+ `@modelcontextprotocol/sdk/client/auth.js`, `.../shared/auth.js`,
656
+ `.../shared/transport.js` and `.../client/streamableHttp.js` to
657
+ `@modelcontextprotocol/client`; the member names are the same. A provider
658
+ that is only structurally an `OAuthClientProvider` (no import) keeps
659
+ compiling, and a plain `fetch`-shaped function is still a `FetchLike`. If you
660
+ only use `BrowserOAuthProvider` / `createEnterpriseOAuthProvider`, there is
661
+ nothing to change in code.
662
+ 3. **Errors.** `UnauthorizedError` (re-exported from `./mcp`) is the new
663
+ package's class: an `instanceof` against a class imported from the 1.x
664
+ package no longer matches. It now sets `name` to `'UnauthorizedError'`, and
665
+ `instanceof` holds across two copies of the SDK. Other classes: `ProtocolError`
666
+ (was `McpError`), `SdkError` / `SdkHttpError` (was `StreamableHTTPError`; the
667
+ HTTP status is `.status`). Messages lost the `MCP error <code>: ` prefix.
668
+ 4. **Your own `OAuthClientProvider`.** `tokens`, `saveTokens`,
669
+ `clientInformation` and `saveClientInformation` get an optional last argument
670
+ `ctx: { issuer }`; ignore it if you keep one credential set. The objects
671
+ handed to the two `save*` methods carry an `issuer` field: store and return
672
+ them **verbatim**. `invalidateCredentials` is called with `'client'` and then
673
+ `'tokens'` on an `invalid_client` (it was `'all'`). When the provider
674
+ implements `saveDiscoveryState`, `discoveryState()` must still return it when
675
+ the code comes back, or the exchange is refused. A `saveTokens` that throws
676
+ after a refresh now fails the request instead of starting a new
677
+ authorization.
678
+ 5. **Stored tokens need no migration.** What `BrowserOAuthProvider` wrote
679
+ before (no `issuer` stamp) loads as it is and is stamped on first use. One
680
+ thing does not carry over: an authorization that was *started* before the
681
+ upgrade and comes back after it, if that version stored no discovery state —
682
+ `finishMcpOAuth` refuses it and the user authorizes again.
683
+ 6. **Behaviour that is new on purpose** (each in the sections above): a
684
+ `tools/call` answered with a JSON-RPC error keeps the server's message
685
+ verbatim; an `outputSchema` that cannot be compiled fails only that tool's
686
+ calls, where it used to fail the whole server at connect; a
687
+ `403 insufficient_scope` fails the call instead of starting an
688
+ authorization; a server that speaks only 2026-07-28 is refused with a clear
689
+ error.
690
+
556
691
  ## Docs
557
692
 
558
693
  - [docs/design.md](docs/design.md) — architecture & rationale.