@dudko.dev/agent-web 0.0.39 → 0.0.41

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 (40) hide show
  1. package/README.md +407 -13
  2. package/dist/agent-web.js +169 -161
  3. package/dist/agent-web.js.map +1 -1
  4. package/dist/chunk-4FBTBE74.js +510 -0
  5. package/dist/chunk-4FBTBE74.js.map +1 -0
  6. package/dist/{chunk-TZITKUFW.js → chunk-L7Y3QRAM.js} +152 -20
  7. package/dist/chunk-L7Y3QRAM.js.map +1 -0
  8. package/dist/{chunk-V3JOK7EW.js → chunk-YPCHD6DV.js} +4 -2
  9. package/dist/chunk-YPCHD6DV.js.map +1 -0
  10. package/dist/chunk-YUA2BHRM.js +584 -0
  11. package/dist/chunk-YUA2BHRM.js.map +1 -0
  12. package/dist/elicitation-BA1knkdA.d.cts +566 -0
  13. package/dist/elicitation-BA1knkdA.d.ts +566 -0
  14. package/dist/index.cjs +1819 -223
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +690 -117
  17. package/dist/index.d.ts +690 -117
  18. package/dist/index.js +1281 -187
  19. package/dist/index.js.map +1 -1
  20. package/dist/mcp.cjs +2240 -95
  21. package/dist/mcp.cjs.map +1 -1
  22. package/dist/mcp.d.cts +303 -21
  23. package/dist/mcp.d.ts +303 -21
  24. package/dist/mcp.js +1675 -91
  25. package/dist/mcp.js.map +1 -1
  26. package/dist/{sandbox-KG6OUG24.js → sandbox-ZDQIIZS7.js} +21 -8
  27. package/dist/sandbox-ZDQIIZS7.js.map +1 -0
  28. package/dist/sandbox-worker.cjs +3 -1
  29. package/dist/sandbox-worker.cjs.map +1 -1
  30. package/dist/sandbox-worker.js +1 -1
  31. package/package.json +5 -5
  32. package/dist/chunk-A6ZJALLU.js +0 -254
  33. package/dist/chunk-A6ZJALLU.js.map +0 -1
  34. package/dist/chunk-CTXDKSDD.js +0 -39
  35. package/dist/chunk-CTXDKSDD.js.map +0 -1
  36. package/dist/chunk-TZITKUFW.js.map +0 -1
  37. package/dist/chunk-V3JOK7EW.js.map +0 -1
  38. package/dist/sandbox-KG6OUG24.js.map +0 -1
  39. package/dist/vault-BatBaRQP.d.cts +0 -36
  40. package/dist/vault-BatBaRQP.d.ts +0 -36
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,67 @@ 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)). By
218
+ default it negotiates the 2025 protocol revisions with the unchanged
219
+ `initialize` handshake, so servers see the same requests and the same headers
220
+ as before; a server that speaks **only** the 2026-07-28 revision then fails to
221
+ connect, at once, with `Unsupported protocol version: 2025-11-25` in
222
+ `results[].error`.
223
+
224
+ **The 2026-07-28 revision is a per-server opt-in**, `protocol`:
225
+
226
+ ```ts
227
+ const mcp = await connectMcpHttp({
228
+ docs: { url: 'https://docs.example.com/mcp' }, // 'legacy', the default
229
+ crm: { url: 'https://crm.example.com/mcp', protocol: 'auto' },
230
+ files: { url: 'https://files.example.com/mcp', protocol: 'modern' },
231
+ })
232
+ mcp.protocols // [{ server: 'docs', version: '2025-11-25', era: 'legacy' }, { server: 'crm', version: '2026-07-28', era: 'modern' }, …]
233
+ ```
234
+
235
+ | `protocol` | What is spoken | Against a server of the other kind |
236
+ | --- | --- | --- |
237
+ | `'legacy'` (default, same as leaving it out) | The 2025 revisions: exactly the requests and the request headers sent before the option existed (a test compares them with a recording made before it). | Only 2026-07-28: `Unsupported protocol version: 2025-11-25`, at once. |
238
+ | `'auto'` | The server is asked first (`server/discover`). One that answers with 2026-07-28 is spoken to that way; any other gets the 2025 handshake. | Works with both. An HTTP 5xx, an answer that is not JSON-RPC or no answer fails the connect: an outage is not read as "an old server". |
239
+ | `'modern'` | 2026-07-28 only. | A 2025 server: `the server did not offer pinned protocol version 2026-07-28 …`, at once. |
240
+
241
+ The revision is decided **once, at connect**; no tool call is ever sent again in
242
+ another revision. `protocols` says what each connected server negotiated, and
243
+ for a server with `protocol` set an `info` line goes to `onLog`
244
+ (`[mcp] crm: protocol 2026-07-28 (modern: …; configured 'auto')`).
245
+
246
+ On 2026-07-28: there is no session (`mcp-session-id`), no GET stream and no
247
+ `initialize`; `instructions`, `isError`, `structuredContent` and the
248
+ `outputSchema` note work as before; OAuth is unchanged. Three things differ:
249
+
250
+ - **CORS.** Every request carries `Mcp-Method` and `Mcp-Name`, and
251
+ `MCP-Protocol-Version` from the first one on: the server must allow them
252
+ ([below](#cors-what-the-server-must-send)). A server that does not cannot be
253
+ reached that way from a page. `'modern'` then fails, and the error names the
254
+ missing headers. `'auto'` cannot tell a blocked probe from an old server (the
255
+ browser says nothing), so it falls back to the 2025 revisions and logs a
256
+ `warn` line that names the headers - or, when the server speaks only
257
+ 2026-07-28, fails with that same explanation.
258
+ - **Tool list changes** arrive over a `subscriptions/listen` stream, which the
259
+ connector opens at connect when you pass `onToolsChanged` and the server
260
+ advertises `tools.listChanged`. When that stream ends while the connection is
261
+ open - dropped, or closed by the server with its result - it is **opened
262
+ again**, with backoff (at most 1 s, 2 s, 4 s, ... up to 60 s, less a random
263
+ share of up to half; the count starts over after a stream that stayed up a
264
+ minute), and once it is back `onToolsChanged(name)` fires once, exactly as
265
+ for a notice: a change made in the gap was announced to nobody. After 10
266
+ attempts in a row it gives up; a 401 / 403 / 404 / 405 (or `-32601`) stops
267
+ it at once. One `warn` per loss with the attempt and the delay, one `info`
268
+ when it is back, one `warn` on giving up. `close()` takes down a pending
269
+ retry and an attempt in flight. `refreshServer(name)` always works. No
270
+ setting: see [docs/design.md](docs/design.md#mcp-the-listen-stream-is-opened-again).
271
+ - **`input_required` needs `onElicitation`.** Without it, a tool that asks the
272
+ user something (elicitation), or asks for the call to be sent again with a
273
+ state, fails with `MCP tool "x" did not finish: the server asked for more
274
+ input …`; the call is not repeated. With it, see [Elicitation](#elicitation-a-server-asks-the-user).
275
+
215
276
  Pass several servers at once — they connect concurrently, each with its own
216
277
  deadline (`connectTimeoutMs`, default 30 s), every page of a paginated
217
278
  `tools/list` is read, and tools a server marks `readOnlyHint` are treated as
@@ -228,19 +289,204 @@ the instructions are a prompt-injection surface
228
289
  ([docs/security.md](docs/security.md#mcp-server-instructions-third-party-text-in-a-system-prompt)) —
229
290
  `mcpInstructions: false` switches them off.
230
291
 
231
- `connectMcpHttp` returns `{ tools, catalog, results, instructions, refreshServer, close }`.
292
+ A tool the server refuses with a JSON-RPC error (what a 2.x server answers for
293
+ an unknown tool, `-32602`) is a failed call like an `isError` result; its
294
+ message is the server's own, without the `MCP error <code>: ` prefix the 1.x
295
+ SDK added — read `error.code` for the number. A paginated `tools/list` is
296
+ followed for up to 100 pages (a repeated cursor ends the walk; past the cap a
297
+ `warn` line says the rest is not mounted).
298
+
299
+ `connectMcpHttp` returns `{ tools, catalog, results, instructions, protocols, refreshServer, close }`.
232
300
  `tools` and `catalog` are mutated **in place** by `refreshServer(name)`, so an
233
301
  agent built from them picks up a server's new tool list (react to it via the
234
302
  `onToolsChanged` option) without being rebuilt. Filtering is plain object work:
235
303
  delete the keys you don't want before merging.
236
304
 
305
+ ### MCP skills (experimental): a server's instructions as skills
306
+
307
+ A server may serve **skills** (the [Skills extension](https://github.com/modelcontextprotocol/ext-skills),
308
+ `io.modelcontextprotocol/skills`, Beta, written against 2026-07-28): `SKILL.md` instruction files
309
+ and the files they bundle. Opt in per server - they come with its tools:
310
+
311
+ ```ts
312
+ const mcp = await connectMcpHttp({
313
+ docs: { url: 'https://docs.example.com/mcp', protocol: 'auto', skills: true },
314
+ // a server you vetted: its skills load without a question
315
+ ours: { url: 'https://mcp.internal.example/mcp', protocol: 'auto', skills: { consent: 'never' } },
316
+ })
317
+ const agent = await createAgent({
318
+ model,
319
+ tools: { ...mcp.tools },
320
+ toolApproval: { onRequest: askThePerson }, // a request with `skill`: show it, then answer
321
+ })
322
+ agent.skills // [{ name: 'docs/pdf-processing', description: '… [from the MCP server "docs" - third-party]', server: 'docs' }, …]
323
+ ```
324
+
325
+ | | |
326
+ | --- | --- |
327
+ | Off by default | Without `skills` (`true`, or `{ consent }`) the extension is not declared and nothing of it is sent. It is declared only where 2026-07-28 may be spoken (`protocol: 'auto'` / `'modern'`); `'legacy'` (or none) logs a `warn` and asks nothing, an `'auto'` connection that ends on 2025 lists nothing. No agent-wide switch. |
328
+ | One catalog, namespaced | The server's skills join your `skills` and the agent's lessons as `<server>/<skill>` (the server by its key in `connectMcpHttp`, never its `serverInfo`). No other skill name can hold a `/`: a server cannot shadow yours, a lesson or another server's - your `git-workflow` keeps its name and the clash is logged. Same-named skills of one server are kept by their paths. |
329
+ | On demand, verified | The prompts carry the name, the description (one line, ≤ 300 characters) and the origin. Nothing is read at connect; `SKILL.md` is read when `load_skill` or the planner asks, a file when `read_skill_file` asks - each checked against the server's entry (size, SHA-256, and for `SKILL.md` the frontmatter): a mismatch is refused, nothing of it used. A file only from the skill's own server, only if its entry lists it, as text. |
330
+ | Knowledge, never policy | Loaded under a preamble saying it is third-party text that cannot grant permissions, approve a call or change the approval mode, widen egress or the sandbox, or make the agent run anything. Nothing of its frontmatter beyond `name` / `description` is read (`allowed-tools` grants nothing). While a run acts on an MCP skill, a tool that runs code (`run_js`, or yours marked with `markCodeExecution`) is always asked - whatever the mode or a rule say; with no `onRequest` it is refused. |
331
+ | Caps | 32 skills per server, 64 in all; 16 000 characters of instructions, 32 000 of a file - every cut said. Entries over the extension's limits (512 files, 16 MiB), `"dynamic"` ones and ones whose URI and frontmatter name disagree are refused with a `warn`. |
332
+ | Changes | Announced as a resource list change: `onToolsChanged(name)` fires (also for that notice), and `refreshServer(name)` lists the skills again. An agent built afterwards has the new ones. |
333
+ | A person sees it first | Before a server's skill enters the model's context (`load_skill`, the planner's pick, a resumed run, `read_skill_file`), its verified `SKILL.md` is put to `toolApproval.onRequest`: a request with `toolName: 'load_skill'` and `skill` (`McpSkillConsentView`: server, name, description, size, files, `byUri`, `nestedIn`, `consent`, and `body` - the very text the model would read). Yes lets it in; `remember: true` = "Always for this server" (nested skills excepted); no keeps all of it out and the model is told. Asked whatever the approval mode says - autopilot too; without `onRequest` it is not loaded. When: `skills: { consent }` per server, else `mcpSkills: { consent }` on the agent, else `'once-per-skill'` (the first time per skill in the agent's life, again if its files change); `'ask'` (every run); `'never'` (a vetted server). A nested skill is asked about on its own. |
334
+ | By URI | A skill the listing leaves out, named by URI in a server's text: `load_skill({ server, uri })` (its description says so). A `skill://…/SKILL.md` URI and a server whose skills are on - checked before any request - and room under the per-server cap; then `skills/get` to THAT server only (its `-32602` reaches the model), the same entry rules, verification, consent (`byUri`) and preamble. It stays in the catalog, under a name no other skill has. |
335
+
336
+ A server's skills come with its tools, like its instructions: a server whose tools are all
337
+ filtered out (or that has none) offers none. Details: [docs/capabilities.md](docs/capabilities.md#mcp-skills-experimental),
338
+ what a server's skill can and cannot do: [docs/security.md](docs/security.md#mcp-skills-third-party-instructions).
339
+
340
+ ### Elicitation: a server asks the user
341
+
342
+ A tool may need something only the user has - a name to confirm, a choice, a
343
+ page to visit - and ask for it **in the middle of the call**. Off until you give
344
+ the connection a callback:
345
+
346
+ ```ts
347
+ const pending = new Map<string, (r: McpElicitationResult) => void>()
348
+
349
+ const mcp = await connectMcpHttp(servers, {
350
+ // The HOST decides, never the model. `request` is the SERVER's text: show it as such.
351
+ onElicitation: (request, { signal }) =>
352
+ new Promise((resolve) => {
353
+ pending.set(request.id, resolve) // your UI resolves it: accept / decline / cancel
354
+ signal.addEventListener('abort', () => pending.delete(request.id)) // no longer wanted
355
+ }),
356
+ elicitation: { timeoutMs: 300_000, maxPerToolCall: 5, maxPerRun: 20 }, // the defaults
357
+ })
358
+ // later, from the form the user filled in:
359
+ pending.get(id)?.({ action: 'accept', content: { name: 'Ada' } })
360
+ ```
361
+
362
+ - **Off = nothing changes.** Without `onElicitation` no capability is declared, a
363
+ server cannot ask, and every request is byte for byte what it was (no new
364
+ request header either: a server's CORS list needs nothing for this).
365
+ - **The request** (`McpElicitationRequest`): `id`, `server`, `tool` (the call
366
+ that asks), `mode: 'form' | 'url'`, `message`, and `requestedSchema` (a flat
367
+ form: strings, numbers, booleans, selects) or `url`. All of it is third-party
368
+ text, cleaned and capped; none of it reaches a prompt. A form that is not flat,
369
+ or too large, is declined without the callback being called.
370
+ - **The answer** is checked against the form before it is sent (types, limits,
371
+ required fields, no field the form did not ask for) and goes **only to the
372
+ server that asked**: not into the model's context, an event, a log or a run
373
+ checkpoint.
374
+ - **URL mode** is opt-in (`elicitation: { url: true }`). The link is only handed
375
+ to your callback: this package never fetches it and never calls
376
+ `window.open`. Only `https:` (or loopback `http:`) links get that far. Open it
377
+ from a user gesture, in a new tab, showing the host name first.
378
+ - **Nobody decided = the call fails.** A callback that throws or does not answer
379
+ within `timeoutMs`, an answer that does not fit, a cap: the question is
380
+ cancelled, the tool call fails with one sentence that says why, and nothing is
381
+ retried.
382
+ - **Subagents do not ask** unless the connection says so
383
+ (`elicitation: { subagents: true }`): a helper the model started, and a
384
+ subagent tool's child that was handed these tools, have their questions
385
+ cancelled without the callback being called.
386
+ - **Time.** A question waits `timeoutMs` (5 minutes) at most; `0` or
387
+ `Infinity` removes that limit (the question waits until the run is stopped),
388
+ and so does a value above 2^31 - 1 ms (about 24.8 days, the longest delay a
389
+ timer holds). A negative number or `NaN` fails the connect. The step it
390
+ belongs to does not run out of time meanwhile: `chatTimeoutMs` (default
391
+ 120 s) **is stopped while a question waits** - like the `timeoutMs` of a
392
+ subagent the question holds up - and goes on with the time it had left. The
393
+ same holds while a person decides a tool approval (whose own bound is
394
+ `toolApproval.timeoutMs`, also 5 minutes by default). Stopping the run ends a
395
+ wait at once.
396
+ - **Events** inside a run: `mcp.elicitation-requested` and
397
+ `mcp.elicitation-answered` (field names, never a value).
398
+
399
+ The whole of it, with every guard: [docs/capabilities.md](docs/capabilities.md#mcp-elicitation-a-server-asks-the-user)
400
+ and [docs/security.md](docs/security.md#mcp-elicitation-a-server-asks-the-user-in-the-middle-of-a-tool-call).
401
+
402
+ ### MCP Apps: a server's own interface for a tool
403
+
404
+ With [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) (the stable extension
405
+ `io.modelcontextprotocol/ui`, revision 2026-01-26) a tool declares an HTML app
406
+ (`_meta.ui.resourceUri: 'ui://…'`) that shows its result - a flight list, a chart, a form. This
407
+ package is the host's data side: it reads the declaration, tells the run when such a tool
408
+ returned, reads the app from its server, and makes the calls the app asks for. **Drawing** the
409
+ app is the UI's job: the React package's `<AgentChat mcpApps>` does it in a sandboxed frame.
410
+ Off until you ask:
411
+
412
+ ```ts
413
+ const mcp = await connectMcpHttp(servers, { apps: true })
414
+ const agent = await createAgent({ model, tools: mcp.tools })
415
+
416
+ agent.run(goal, {
417
+ onEvent: async (e) => {
418
+ if (e.type !== 'mcp.app') return
419
+ // e.server, e.tool / e.toolName, e.resourceUri, e.input, e.result: what the app is shown
420
+ const app = await mcp.apps!.readUiResource(e.server, e.resourceUri) // { html, csp, permissions, … }
421
+ // ... frame app.html with a policy built from app.csp (connectDomains / resourceDomains only)
422
+ },
423
+ })
424
+
425
+ // The app asks to call a tool of ITS server: consent first, then the call.
426
+ const tool = mcp.apps!.appTool('travel', 'flights.book') // undefined: not one an app may call
427
+ await agent.approveAppToolCall({ tool: tool!.key, toolName: 'flights.book', server: 'travel',
428
+ resourceUri, input: args, readOnly: tool!.readOnly }) // throws ToolDeniedError when refused
429
+ const result = await mcp.apps!.callAppTool('travel', 'flights.book', args)
430
+ ```
431
+
432
+ - **Off = nothing changes.** Without `apps` no extension is declared, `_meta` is not read, every
433
+ tool is mounted as before and the wire is byte for byte what it was. On, the only difference on
434
+ the wire is the extension in the handshake (`capabilities.extensions`).
435
+ - **The HTML never reaches the model**: it is in no tool result, event, log or checkpoint. The
436
+ model's tool result is what it would be without apps. `mcp.app` carries the call's arguments
437
+ and the result for the app (`content`, `structuredContent`, `isError`, `_meta`; left out above
438
+ `MCP_APP_MAX_RESULT_CHARS`, 512 000).
439
+ - **An app is read only from the server that declared it**, and only a `ui://` URI that a tool of
440
+ THAT server declares in its current listing - nothing is asked of a server otherwise; checked
441
+ (the exact URI, the MIME type `text/html;profile=mcp-app`, at most 2 000 000 characters, `text`
442
+ or base64 `blob`) and cached per connection; a refused read is not kept. Its declared CSP is
443
+ cleaned to origins (`https://host`, `wss://…`, `https://*.example.com`, loopback `http`): a
444
+ keyword, a scheme, a path, `*` or a `;` never gets through. The permissions it asks for
445
+ (camera, microphone, …) are reported, never granted here. Each read logs the policy (`onLog`).
446
+ - **Who may call what** (`_meta.ui.visibility`): a tool for its app only (`['app']`) is not
447
+ mounted for the model; `appTool` / `callAppTool` refuse a tool whose visibility leaves out
448
+ `'app'`, or that the server does not list - before anything is sent.
449
+ - **Consent for an app's calls** - `agent.approveAppToolCall` - is the agent's own gate
450
+ (`toolApproval`: its rules, handler and timeout) with two differences: under `'autopilot'` a
451
+ write still asks (read-only tools run, as in `'ask-writes'`), and "always allow" given to an app
452
+ is remembered for apps only. The request carries `app: { server, tool, resourceUri }`.
453
+ `callAppTool` itself does not ask: call it after the consent.
454
+
455
+ - **One server's apps off**: `McpHttpServerConfig.apps: false` (over the connection's `apps`) -
456
+ that server is not told of apps, none of its apps is read, no `mcp.app` is told for it, and a
457
+ tool it marks for its app only is mounted for nobody; its other tools are plain tools. `apps:
458
+ true` turns them on for that server alone (`mcpAppsModeOf`: `'on' | 'declined' | 'off'`).
459
+ - **A file an app links to** (`ui/download-file` with a `resource_link`):
460
+ `mcp.apps.readResource(server, uri, { maxBytes })` - `resources/read` on that server only, never a
461
+ fetch of the URI; its bytes, at most `MCP_APP_MAX_DOWNLOAD_BYTES` (20 MB), not cached. It neither
462
+ asks the user nor judges the type: the UI does both before it saves anything.
463
+ - **A completion an app asks for** (`sampling/createMessage`) - `agent.sampleForApp({ server,
464
+ resourceUri, params }, { approve, signal?, onEvent?, sessionId? })`: checked (text; images only
465
+ for a model known to read them; no tools; 16 000 characters; `maxTokens` lowered to 1024), rate
466
+ limited per app (5 a minute, 30 in all), put to `approve` with exactly what the model will get,
467
+ then answered by the synthesizer's model with nothing of the agent's context. Its tokens count in
468
+ `agent.usage` (a `usage` event of phase `'app'`); the answer goes to the caller only - never into
469
+ memory, an event or a run. Caps: `config.appSampling` (`false` refuses every request).
470
+
471
+ ```ts
472
+ const answer = await agent.sampleForApp(
473
+ { server: 'demo', resourceUri: 'ui://demo/trip-board.html', params: request.params },
474
+ { approve: (view) => askTheUser(view) }, // view: { messages, systemPrompt?, maxTokens, … }
475
+ ) // { role: 'assistant', content: { type: 'text', text }, model, stopReason } - or AppSamplingError
476
+ ```
477
+
478
+ Everything else an app may ask for - opening a link, putting a message in the chat, full screen,
479
+ saving a file - is the UI's to ask the user about. The whole of it: [docs/capabilities.md](docs/capabilities.md#mcp-apps-a-servers-interface-for-a-tool)
480
+ and [docs/security.md](docs/security.md#mcp-apps-a-servers-html-with-scripts).
481
+
237
482
  ### OAuth 2.1 + Dynamic Client Registration
238
483
 
239
484
  A server behind OAuth needs more than a header: access tokens expire mid-run.
240
485
  Pass an `authProvider` and the MCP SDK discovers the authorization server
241
- (RFC 9728), registers this app dynamically (RFC 7591 — no client_id to
242
- pre-provision), runs PKCE, and **refreshes the access token on any 401 and
243
- retries the request**.
486
+ (RFC 9728), registers this app — dynamically (RFC 7591) or by its client ID
487
+ metadata document (CIMD), automatically or one of them only (`registration`):
488
+ no client_id to pre-provision — runs PKCE, and **refreshes the access token on
489
+ any 401 and retries the request**.
244
490
 
245
491
  ```ts
246
492
  import { BrowserOAuthProvider, connectMcpHttp, finishMcpOAuth, readOAuthCallback }
@@ -283,11 +529,65 @@ on `provider.authorizationUrl` and the app decides when to use it.
283
529
  before, and a registration already in storage wins over both. The URL must be
284
530
  https with a path (anything else throws in the constructor), and the document
285
531
  must list the same `redirect_uris` as `redirectUrl`.
532
+ - **`registration`: how the client is registered** — `'auto'` (the default),
533
+ `'cimd'` or `'dcr'`; the Node package has the same option.
534
+
535
+ | value | the client | an authorization server without CIMD support |
536
+ |---|---|---|
537
+ | `'auto'` | the document where the server advertises `client_id_metadata_document_supported` (and `clientMetadataUrl` is set), a dynamic registration elsewhere; a stored client is used as it is | dynamic registration |
538
+ | `'cimd'` | the document only; needs `clientMetadataUrl` (the constructor throws without one) | **refused before anything is sent to its registration endpoint**: the connect fails with `… does not support client ID metadata documents (CIMD), which this connection requires (registration: 'cimd') - nothing was sent to its registration endpoint`, and what discovery found is dropped, so the next attempt reads the server's metadata again |
539
+ | `'dcr'` | a dynamic registration only, even with a `clientMetadataUrl` (the provider's `clientMetadataUrl` is then `undefined`: the SDK never sees the URL) | dynamic registration |
540
+
541
+ `await provider.registrationKind()` says how the stored client was made —
542
+ `'cimd'`, `'dcr'` (also a client you saved yourself), or `undefined` when
543
+ there is none this provider would use; `provider.registration` is the
544
+ setting. Under `'cimd'` / `'dcr'` **a stored client of the other kind is not
545
+ reused**: it is forgotten together with the tokens issued to it (a token
546
+ belongs to its client) before either is read, and the user signs in again.
547
+ The kind is stamped on the stored record when it is saved, so a later change
548
+ of `clientMetadataUrl` does not make an old document client look like a
549
+ dynamic one; a record saved before the stamp existed is CIMD when its
550
+ `client_id` is the document configured now.
286
551
  - **Registration** describes a public PKCE client. `application_type` follows
287
552
  the redirect URL: `'web'` for an https page, `'native'` for a loopback one
288
553
  (local development). Change any field through `clientMetadata`.
289
554
  - `provider.reset()` forgets tokens, registration and discovery - use it when a
290
555
  server moved to another authorization server.
556
+ - **Discovery is stored** next to the tokens (the authorization server and its
557
+ metadata), so later calls skip it and the issuer check has something to
558
+ compare with. A code is exchanged only when that record is still there: a
559
+ flow whose discovery state is gone (started by a version that did not keep
560
+ it, or storage was cleared in between) is refused by `finishMcpOAuth` with
561
+ `Authorization cannot be completed: ... start the authorization again`.
562
+ Tokens already in storage are not touched; send the user to authorize again
563
+ and the new redirect completes.
564
+ - **Credentials belong to the authorization server that issued them.** The
565
+ registration and the tokens are stored with an `issuer` stamp and are never
566
+ presented to another authorization server: stamped for a different one, they
567
+ are read as absent and a new authorization is asked for. Storage written
568
+ before the stamp existed keeps working — its values are used as they are and
569
+ stamped on first use (the SDK says so once on the console). A custom
570
+ `McpOAuthStorage` only has to return what it was given.
571
+ - **A token endpoint must be https** (or loopback). The SDK refuses to send a
572
+ code or a refresh token to a plain-http token endpoint; the error names it,
573
+ and no new authorization is started in its place.
574
+ - **The metadata must be the server's own.** Authorization server metadata
575
+ whose `issuer` is not the URL it was fetched for is refused by the SDK
576
+ (RFC 8414 section 3.3): the connect fails with the two issuers named, and
577
+ nothing is registered. The 1.x SDK accepted such a document.
578
+ - **`403 insufficient_scope`.** When the server answers a request with `403` and
579
+ `WWW-Authenticate: Bearer error="insufficient_scope"`, the tool call fails
580
+ with `Insufficient scope: required "<scope>"` (the SDK's
581
+ `InsufficientScopeError`, with `requiredScope`; it is **not** an
582
+ `UnauthorizedError`). No authorization is started from inside a run: a new
583
+ authorization URL in the middle of a tool call would replace the state and
584
+ PKCE verifier of the one the user may have open. Ask for the scope up front
585
+ (`scope`), or authorize again with it. A provider **without** a human step
586
+ (no `redirectUrl`: the enterprise one below) asks once for the wider scope
587
+ and retries the request once.
588
+ - **A refresh whose result cannot be saved is an error**, not a new
589
+ authorization: when storage throws while saving refreshed tokens (a full
590
+ quota, a broken vault), the connect or the tool call fails with that error.
291
591
 
292
592
  ### Enterprise-managed authorization (ID-JAG)
293
593
 
@@ -379,6 +679,31 @@ Access-Control-Allow-Headers: Content-Type, Authorization, mcp-session-id,
379
679
  Access-Control-Expose-Headers: mcp-session-id, WWW-Authenticate
380
680
  ```
381
681
 
682
+ Nothing changed here with the 2.x MCP SDK: recorded on the wire against a raw
683
+ HTTP server, the old and the new client send the same requests with the same
684
+ headers (`Accept`, `Content-Type`, then `mcp-session-id` and
685
+ `MCP-Protocol-Version` after `initialize`, `Authorization` and `Last-Event-ID`
686
+ when they apply), and the browser tests run against a server with exactly this
687
+ list.
688
+
689
+ **For the 2026-07-28 revision** (a server connected with `protocol: 'auto'` or
690
+ `'modern'`) two more request headers are needed, and `MCP-Protocol-Version` is
691
+ on the very first request:
692
+
693
+ ```
694
+ Access-Control-Allow-Headers: Content-Type, Authorization, MCP-Protocol-Version,
695
+ Mcp-Method, Mcp-Name
696
+ ```
697
+
698
+ (`mcp-session-id` and `Last-Event-ID` are not sent in that revision, and no new
699
+ response header needs exposing; keep them all in one list if the server also
700
+ serves 2025 clients.) This package does **not** send `Mcp-Param-*` headers -
701
+ the mirror of tool arguments a tool may ask for with `x-mcp-header` - so the
702
+ list above is the whole requirement for it; another client may send them, and
703
+ their names come from the tools, so a server that uses the feature has to
704
+ allow them by pattern. Without `protocol`, none of these headers is sent and
705
+ the 2025 list is still enough.
706
+
382
707
  Each line earns its place:
383
708
 
384
709
  - **`MCP-Protocol-Version` in Allow-Headers** is the one that bites hardest. The
@@ -402,6 +727,16 @@ browser's silence: it re-probes the endpoint with a plain request and, if that
402
727
  gets through, says which header is being refused. `diagnoseMcpCors(url)` is
403
728
  exported so a UI can show the same sentence.
404
729
 
730
+ With `protocol: 'auto'` or `'modern'` it goes one step further, because the
731
+ browser will not say *which* header a preflight refused: it sends one request
732
+ per header (`MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name`, each alone) and
733
+ names the ones that were blocked - `… one carrying Mcp-Method / Mcp-Name was
734
+ blocked: the server's Access-Control-Allow-Headers does not list them …`. That
735
+ sentence is added to the connect error (`'modern'`, and `'auto'` against a
736
+ 2026-only server) or logged at `warn` (`'auto'` that fell back to 2025). The
737
+ same from your own code: `diagnoseMcpCors(url, fetch, { protocol: 'modern' })`.
738
+ These extra requests are made only after a connect already failed or fell back.
739
+
405
740
  ## Optional: WebMCP — a page's tools, both ways
406
741
 
407
742
  [WebMCP](https://webmachinelearning.github.io/webmcp/) lets a page register named, typed tools
@@ -448,7 +783,10 @@ const agent = await createAgent({
448
783
  skills: [defineSkill({ name: 'triage', description: 'Triage a bug report', content: '…' })],
449
784
  toolApproval: {
450
785
  mode: 'ask-writes', // autopilot | ask-writes | ask-all | read-only
451
- onRequest: async (req) => window.confirm(`Allow ${req.toolName}?`),
786
+ // `signal` aborts when the agent stops waiting (the bound, a stop): take your dialog down then
787
+ onRequest: async (req, { signal }) => askInADialog(`Allow ${req.toolName}?`, { signal }),
788
+ // no decision in 5 minutes (the default) -> deny; 0 or Infinity: wait until the run is stopped
789
+ timeoutMs: 300_000,
452
790
  },
453
791
  })
454
792
  agent.setToolApprovalMode('autopilot') // flip the switch at any time
@@ -469,7 +807,7 @@ that run's limits. Give `persistence` a store
469
807
  last checkpoint with `run('', { resumeFromRunId })` — the planner does not run again and
470
808
  no finished step is repeated. `createRunControl()` steers a run that is going: `send()`
471
809
  puts a message in front of the model at the next boundary (the replanner re-checks the plan
472
- 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:
810
+ 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 function of yours (any search API — recipes for Tavily, Brave and SearXNG are in the docs) or the built-in Google Search through Gemini grounding, which needs only a Gemini key and spends its tokens — 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:
473
811
  **[docs/capabilities.md](docs/capabilities.md)**.
474
812
 
475
813
  ## Pipelines: a graph of agents
@@ -537,14 +875,16 @@ Loading a definition someone else wrote: [docs/security.md](docs/security.md#pip
537
875
  | `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)) |
538
876
  | `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 |
539
877
  | `credentials` | — | a `CredentialStore` for `credentialRef` keys |
540
- | `tools` | `{}` | host tools (`defineTool`) |
878
+ | `tools` | `{}` | host tools (`defineTool`); mark a tool that runs code with `markCodeExecution` (always asked while a run acts on an MCP server's skill) |
541
879
  | `availableTools` / `excludedTools` | — | whitelist / blacklist of tool names mounted from `tools` |
542
880
  | `toolMode` | `'auto'` | `native` \| `prompted` \| `auto` (cloud→native, local→prompted) |
543
881
  | `toolSelectionStrategy` | `'auto'` | `all` \| `plan-narrowed` \| `search` \| `auto` (search above `toolSearchThreshold`, 40, or once the definitions take ¼ of the window) |
544
- | `toolApproval` | autopilot | consent policy: `{ mode, rules, onRequest, timeoutMs }`; `agent.setToolApprovalMode()` |
545
- | `skills` | — | SKILL.md bundles (`defineSkill` / `parseSkillMarkdown` / `loadSkillFromUrl`) |
882
+ | `appSampling` | on, with caps | the caps of `agent.sampleForApp` (an MCP App asking the model): `{ maxTokens: 1024, maxRequestsPerMinute: 5, maxRequests: 30, maxInputChars: 16000, reasoningTokens: 2048 }`, per app (`reasoningTokens`: room on top of an app's `maxTokens` for a model seen reasoning - its reasoning counts against the cap); `false` refuses every request. Nothing happens unless a host calls it, and every request goes to its `approve` first. See [An app asks the model](docs/capabilities.md#an-app-asks-the-model) |
883
+ | `toolApproval` | autopilot | consent policy: `{ mode, rules, onRequest, timeoutMs }`; `agent.setToolApprovalMode()`. A question waits `timeoutMs` for a decision, then is denied: default 300000 (`TOOL_APPROVAL_TIMEOUT_MS`), `0` or `Infinity` = until the run is stopped (as is a value above 2^31 - 1, the most a timer holds); negative or `NaN` fails `createAgent`. `onRequest(req, { signal })`: the signal aborts when the question ends without an answer (`TimeoutError` for the bound, `AbortError` for a stop). See [Tool consent](docs/capabilities.md#tool-consent-and-autopilot) |
884
+ | `skills` | — | SKILL.md bundles (`defineSkill` / `parseSkillMarkdown` / `loadSkillFromUrl`). An MCP server's skills come with its tools (`skills: true` or `{ consent }` on the server of `connectMcpHttp`, experimental) and join them as `<server>/<skill>` - see [MCP skills](#mcp-skills-experimental-a-servers-instructions-as-skills) |
885
+ | `mcpSkills` | `{ consent: 'once-per-skill' }` | experimental: when a person is asked (`toolApproval.onRequest`, a request with `skill`) before an MCP server's skill enters the model's context, for servers whose `skills: { consent }` does not say - `'once-per-skill'`, `'ask'` (every run) or `'never'` - see [MCP skills](#mcp-skills-experimental-a-servers-instructions-as-skills) |
546
886
  | `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) |
547
- | `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) |
887
+ | `search` | off | the model may **search the web** (`web_search`: a short list of title / url / snippet): `{ engine: fn }` - a search engine of yours, any API - or `{ provider: 'google', credentialRef, model, baseURL, maxResults, allowPrivateNetwork, readOnly, fetch }` - Google Search through Gemini grounding: one extra `generateContent` call per search on a Gemini key (default model `gemini-2.5-flash-lite`), which **spends model tokens** (`usage` phase `'search'`) and returns **Google redirect links**, not the pages' URLs. No key ships with the library and none is written in the config (`credentialRef` names it in `credentials`); the request reaches only that API; with `egress`, results the model could not fetch are left out. Recipes for Tavily / Brave / SearXNG as an `engine`, the free-tier models and what the redirect links mean — see [Search](docs/capabilities.md#search-finding-the-page-to-fetch) |
548
888
  | `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) |
549
889
  | `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) |
550
890
  | `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 |
@@ -564,7 +904,7 @@ Loading a definition someone else wrote: [docs/security.md](docs/security.md#pip
564
904
  | `sessionId` | — | names the stored conversation in `memory`, and the bucket `agent.sessionUsage()` counts into |
565
905
  | `persistence` | — | checkpoint runs (`IndexedDBRunStore` / `MemoryRunStore`) so `run(goal, { resumeFromRunId })` continues after a reload — see [Resuming](docs/capabilities.md#resuming-an-interrupted-run) |
566
906
  | `maxIterations` / `maxStepsPerTask` / `maxRevisions` | 8 / 4 / 2 | loop caps |
567
- | `chatTimeoutMs` | 120000 | per-call watchdog |
907
+ | `chatTimeoutMs` | 120000 | per-call watchdog; for the executor, the whole step (its tool calls included). Stopped while a tool call waits for a person (an approval, an MCP question): the step goes on with the time it had left - see [Tool consent](docs/capabilities.md#tool-consent-and-autopilot) |
568
908
  | `temperature` | provider default | sampling temperature for every stage |
569
909
  | `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) |
570
910
  | `clientName` | — | sent as the openai-compatible provider name and the MCP client name |
@@ -573,6 +913,60 @@ Loading a definition someone else wrote: [docs/security.md](docs/security.md#pip
573
913
  | `replanAfter` | `'failure'` | replan trigger: `'failure'` \| `'always'` \| `(stepResult) => boolean \| Promise<boolean>` |
574
914
  | `compressAfterChars` | 12000 | legacy: summarize old history past this size (when `compaction` is unset) |
575
915
 
916
+ ## Upgrading to the 2.x MCP SDK
917
+
918
+ The `./mcp` subpath moved from `@modelcontextprotocol/sdk` 1.x to the official
919
+ 2.x client, `@modelcontextprotocol/client`, in one step. **The optional peer
920
+ dependency is renamed — that is the breaking change.** Nothing changes on the
921
+ wire, and nothing changes if you never import `@dudko.dev/agent-web/mcp`.
922
+
923
+ If you do import it:
924
+
925
+ 1. **Install the new package, remove the old one.**
926
+ `npm uninstall @modelcontextprotocol/sdk && npm install @modelcontextprotocol/client`
927
+ (`^2.4.0`). With only the old package installed, a bundler cannot resolve
928
+ `@modelcontextprotocol/client` and the build fails. The new SDK needs
929
+ `zod ^4.2` (this package already depends on zod 4) and declares Node >= 20
930
+ for tooling.
931
+ 2. **Import SDK types from the new package.** `McpHttpServerConfig.authProvider`
932
+ is the `OAuthClientProvider` of `@modelcontextprotocol/client`, `fetch` its
933
+ `FetchLike`, `reconnection` its `StreamableHTTPReconnectionOptions`. Change
934
+ `@modelcontextprotocol/sdk/client/auth.js`, `.../shared/auth.js`,
935
+ `.../shared/transport.js` and `.../client/streamableHttp.js` to
936
+ `@modelcontextprotocol/client`; the member names are the same. A provider
937
+ that is only structurally an `OAuthClientProvider` (no import) keeps
938
+ compiling, and a plain `fetch`-shaped function is still a `FetchLike`. If you
939
+ only use `BrowserOAuthProvider` / `createEnterpriseOAuthProvider`, there is
940
+ nothing to change in code.
941
+ 3. **Errors.** `UnauthorizedError` (re-exported from `./mcp`) is the new
942
+ package's class: an `instanceof` against a class imported from the 1.x
943
+ package no longer matches. It now sets `name` to `'UnauthorizedError'`, and
944
+ `instanceof` holds across two copies of the SDK. Other classes: `ProtocolError`
945
+ (was `McpError`), `SdkError` / `SdkHttpError` (was `StreamableHTTPError`; the
946
+ HTTP status is `.status`). Messages lost the `MCP error <code>: ` prefix.
947
+ 4. **Your own `OAuthClientProvider`.** `tokens`, `saveTokens`,
948
+ `clientInformation` and `saveClientInformation` get an optional last argument
949
+ `ctx: { issuer }`; ignore it if you keep one credential set. The objects
950
+ handed to the two `save*` methods carry an `issuer` field: store and return
951
+ them **verbatim**. `invalidateCredentials` is called with `'client'` and then
952
+ `'tokens'` on an `invalid_client` (it was `'all'`). When the provider
953
+ implements `saveDiscoveryState`, `discoveryState()` must still return it when
954
+ the code comes back, or the exchange is refused. A `saveTokens` that throws
955
+ after a refresh now fails the request instead of starting a new
956
+ authorization.
957
+ 5. **Stored tokens need no migration.** What `BrowserOAuthProvider` wrote
958
+ before (no `issuer` stamp) loads as it is and is stamped on first use. One
959
+ thing does not carry over: an authorization that was *started* before the
960
+ upgrade and comes back after it, if that version stored no discovery state —
961
+ `finishMcpOAuth` refuses it and the user authorizes again.
962
+ 6. **Behaviour that is new on purpose** (each in the sections above): a
963
+ `tools/call` answered with a JSON-RPC error keeps the server's message
964
+ verbatim; an `outputSchema` that cannot be compiled fails only that tool's
965
+ calls, where it used to fail the whole server at connect; a
966
+ `403 insufficient_scope` fails the call instead of starting an
967
+ authorization; a server that speaks only 2026-07-28 is refused with a clear
968
+ error (unless you opt in: `protocol: 'auto'` or `'modern'` on that server).
969
+
576
970
  ## Docs
577
971
 
578
972
  - [docs/design.md](docs/design.md) — architecture & rationale.