@dudko.dev/agent-web

agent.dudko.dev · live demo · source
Headless, universal, configurable in-browser LLM agent built on the
Vercel AI SDK. One package drives any model from the
browser:
- ☁️ Cloud providers, bring-your-own-key — OpenAI, Anthropic, Google, xAI,
DeepSeek, any OpenAI-compatible server, and the Vercel AI Gateway.
- 🖥️ Local WebGPU models — via WebLLM
(
@browser-ai/web-llm); no server, no key, data never leaves the device.
- 🔌 Any AI SDK
LanguageModel — e.g. Chrome/Edge built-in AI.
It gives you simple text generation, streaming, native tool-calling, and
structured output, plus a high-level plan → execute → replan → synthesize
agent — with host-defined tools, optional MCP, system prompts,
IndexedDB storage, and an encrypted token vault. UI-agnostic: it streams
typed events; you render them however you like.
The agent loop also has thinking (portable reasoning levels or exact
budgets), token limits (input / output / thinking / total per run),
context compaction (automatic and agent.compact()), prompt caching,
skills (SKILL.md bundles), tool consent modes with an autopilot switch,
tool search for catalogues of hundreds of MCP tools, subagents in
Web Workers, image / PDF / file / URL input (with a clear error for models
that can't take them),
a virtual file system in IndexedDB with fs_* tools, usage counted live
across a session (agent.usage), steering a run while it goes (RunControl),
resuming an interrupted run, egress you switch on and bound (the model's
web_fetch), and learning — the agent writes its own lessons down as skills
— see docs/capabilities.md.
Browser sibling of the Node package
@dudko.dev/agent.
Using React? @dudko.dev/agent-web-react
wraps this core in a useAgent hook, an <AgentProvider> context and drop-in
UI components — try the live demo
(source).
Install
npm install @dudko.dev/agent-web ai zod
Then add only the providers you use (all optional peers, dynamically
imported):
# cloud, pick what you need
npm install @ai-sdk/openai # or @ai-sdk/anthropic, @ai-sdk/google, @ai-sdk/xai, @ai-sdk/deepseek, @ai-sdk/openai-compatible
# local WebGPU models
npm install @browser-ai/web-llm @mlc-ai/web-llm
# optional: HTTP MCP (the official 2.x client SDK; see "Upgrading to the 2.x MCP SDK")
npm install @modelcontextprotocol/client
CDN / standalone bundle (no build step)
dist/agent-web.js is a self-contained ESM bundle of the core — ai,
zod and idb are baked in. It ships in the npm package (so it's on every
CDN) and is attached to each
GitHub release as
agent-web-<version>.min.js:
<script type="module">
import { createAgent, defineTool } from 'https://cdn.jsdelivr.net/npm/@dudko.dev/agent-web/dist/agent-web.js'
// or: https://unpkg.com/@dudko.dev/agent-web/dist/agent-web.js
</script>
Bundler users can also opt into it via the @dudko.dev/agent-web/bundle
subpath. Optional provider peers stay external even in the bundle; in a
bundler-less page, map the ones you use with an import map (the runtime
import() respects it) — direct LanguageModels and gateway specs need no
import map at all:
<script type="importmap">
{
"imports": {
"@ai-sdk/openai": "https://cdn.jsdelivr.net/npm/@ai-sdk/openai/+esm"
}
}
</script>
Quick start — cloud model, bring-your-own-key
Keys are stored encrypted at rest (WebCrypto, IndexedDB) and referenced by
id — never inlined into config. See security.
import {
createAgent,
defineTool,
VaultCredentialStore,
} from '@dudko.dev/agent-web'
import { z } from 'zod'
// 1. Store the user's key once (e.g. from a settings form). Encrypted at rest.
const credentials = new VaultCredentialStore()
await credentials.setApiKey('openai', userProvidedKey)
// 2. Tools = your app's actions.
const tools = {
add_text: defineTool({
description: 'Add a text block to the page.',
inputSchema: z.object({ text: z.string(), x: z.number().optional() }),
execute: async ({ text, x }) => addTextBlock(text, x), // your code
}),
}
// 3. Create the agent. The key is fetched from the vault at build time.
const agent = await createAgent({
model: { providerType: 'openai', model: 'gpt-4o-mini', credentialRef: 'openai' },
credentials,
tools,
describeState: () => serializeMyCanvas(), // optional grounding
})
// 4. Run. Every step is a typed event.
const result = await agent.run('Add a centered title and a totals line', {
onEvent: (e) => {
if (e.type === 'plan.created') console.log('plan:', e.plan.steps)
if (e.type === 'step.tool-call') console.log('tool:', e.name, e.input)
if (e.type === 'final') console.log('done:', e.text)
},
})
console.log(result.final, `— ${result.applied} changes`)
Direct browser calls & CORS: as of October 2026 Google, OpenAI, xAI and
DeepSeek send CORS headers, so a user's own key works straight from the page;
Anthropic works too (a required header is injected for you). Kimi, Groq,
Mistral and OpenRouter do as well (build their AI SDK models yourself and pass
them as model). See docs/providers.md.
Quick start — local WebGPU model (no key, offline)
import { createAgent, createWebLLMModel, isWebGPUAvailable } from '@dudko.dev/agent-web'
if (!isWebGPUAvailable()) throw new Error('WebGPU required for local models')
const model = await createWebLLMModel('Llama-3.2-3B-Instruct-q4f16_1-MLC', {
initProgressCallback: (r) => console.log('loading', Math.round(r.progress * 100), '%'),
contextWindowTokens: 8192, // WebLLM loads with 4096 unless told otherwise
})
// Local models default to the robust "prompted" tool-mode automatically, and
// the agent sizes compaction and tool lists from the model's own window.
const agent = await createAgent({ model, tools /* ...same as above */ })
await agent.run('Summarize the current page and add a heading')
A local vision model (Phi-3.5-vision-instruct-q4f16_1-MLC) takes images
like a cloud one. See docs/capabilities.md
for the window: WebLLM's default is 4096 tokens, raised per model at load.
You can also pass a model by spec: { providerType: 'web-llm', model: '…' }.
Simple generation & tool-calling (no agent loop)
import { generate, stream, generateStructured, runToolLoop } from '@dudko.dev/agent-web'
import { z } from 'zod'
const { text } = await generate(model, { prompt: 'Write a haiku about WebGPU' })
const { textStream } = stream(model, { prompt: 'Explain IndexedDB' })
for await (const chunk of textStream) process.stdout.write(chunk)
const { object } = await generateStructured(
model,
z.object({ title: z.string(), tags: z.array(z.string()) }),
{ prompt: 'Suggest a title and tags for this article: …' },
)
// Tool-calling with feedback (native or prompted), normalized result. In both
// modes the model sees its tool results and can keep going, up to `maxSteps`
// rounds (default 4; prompted models get the results as a TOOL RESULTS turn):
const { text: reply, toolCalls } = await runToolLoop(model, {
mode: 'native',
prompt: 'Add a title',
tools,
})
Optional: MCP tools over HTTP
import { connectMcpHttp } from '@dudko.dev/agent-web/mcp'
const mcp = await connectMcpHttp({
docs: { url: 'https://my-mcp-server.example/mcp', headers: { Authorization: `Bearer ${t}` } },
})
const agent = await createAgent({ model, tools: { ...tools, ...mcp.tools } })
// ... later: await mcp.close()
Browsers can only speak the HTTP (StreamableHTTP) transport — stdio MCP is
Node-only. The connector lives in the ./mcp subpath so the MCP SDK never
enters your core bundle.
The MCP client is the official 2.x SDK, @modelcontextprotocol/client (an
optional peer: install it when you import ./mcp; @modelcontextprotocol/sdk
1.x is no longer used — what to change). By
default it negotiates the 2025 protocol revisions with the unchanged
initialize handshake, so servers see the same requests and the same headers
as before; a server that speaks only the 2026-07-28 revision then fails to
connect, at once, with Unsupported protocol version: 2025-11-25 in
results[].error.
The 2026-07-28 revision is a per-server opt-in, protocol:
const mcp = await connectMcpHttp({
docs: { url: 'https://docs.example.com/mcp' }, // 'legacy', the default
crm: { url: 'https://crm.example.com/mcp', protocol: 'auto' },
files: { url: 'https://files.example.com/mcp', protocol: 'modern' },
})
mcp.protocols // [{ server: 'docs', version: '2025-11-25', era: 'legacy' }, { server: 'crm', version: '2026-07-28', era: 'modern' }, …]
protocol |
What is spoken |
Against a server of the other kind |
'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. |
'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". |
'modern' |
2026-07-28 only. |
A 2025 server: the server did not offer pinned protocol version 2026-07-28 …, at once. |
The revision is decided once, at connect; no tool call is ever sent again in
another revision. protocols says what each connected server negotiated, and
for a server with protocol set an info line goes to onLog
([mcp] crm: protocol 2026-07-28 (modern: …; configured 'auto')).
On 2026-07-28: there is no session (mcp-session-id), no GET stream and no
initialize; instructions, isError, structuredContent and the
outputSchema note work as before; OAuth is unchanged. Three things differ:
- CORS. Every request carries
Mcp-Method and Mcp-Name, and
MCP-Protocol-Version from the first one on: the server must allow them
(below). A server that does not cannot be
reached that way from a page. 'modern' then fails, and the error names the
missing headers. 'auto' cannot tell a blocked probe from an old server (the
browser says nothing), so it falls back to the 2025 revisions and logs a
warn line that names the headers - or, when the server speaks only
2026-07-28, fails with that same explanation.
- Tool list changes arrive over a
subscriptions/listen stream, which the
connector opens at connect when you pass onToolsChanged and the server
advertises tools.listChanged. When that stream ends while the connection is
open - dropped, or closed by the server with its result - it is opened
again, with backoff (at most 1 s, 2 s, 4 s, ... up to 60 s, less a random
share of up to half; the count starts over after a stream that stayed up a
minute), and once it is back onToolsChanged(name) fires once, exactly as
for a notice: a change made in the gap was announced to nobody. After 10
attempts in a row it gives up; a 401 / 403 / 404 / 405 (or -32601) stops
it at once. One warn per loss with the attempt and the delay, one info
when it is back, one warn on giving up. close() takes down a pending
retry and an attempt in flight. refreshServer(name) always works. No
setting: see docs/design.md.
input_required needs onElicitation. Without it, a tool that asks the
user something (elicitation), or asks for the call to be sent again with a
state, fails with MCP tool "x" did not finish: the server asked for more input …; the call is not repeated. With it, see Elicitation.
Pass several servers at once — they connect concurrently, each with its own
deadline (connectTimeoutMs, default 30 s), every page of a paginated
tools/list is read, and tools a server marks readOnlyHint are treated as
read-only by the consent gate. A failing server is reported in results; the
others still mount. With hundreds of tools the agent switches to tool search
automatically (see docs/capabilities.md).
A server's instructions (from its initialize result) reach the planner's and
the executor's system prompts, marked as third-party text and capped; a tool's
structuredContent reaches the model once, as JSON, and a result that breaks
its outputSchema is passed on with a note instead of failing the call. See
docs/capabilities.md;
the instructions are a prompt-injection surface
(docs/security.md) —
mcpInstructions: false switches them off.
A tool the server refuses with a JSON-RPC error (what a 2.x server answers for
an unknown tool, -32602) is a failed call like an isError result; its
message is the server's own, without the MCP error <code>: prefix the 1.x
SDK added — read error.code for the number. A paginated tools/list is
followed for up to 100 pages (a repeated cursor ends the walk; past the cap a
warn line says the rest is not mounted).
connectMcpHttp returns { tools, catalog, results, instructions, protocols, refreshServer, close }.
tools and catalog are mutated in place by refreshServer(name), so an
agent built from them picks up a server's new tool list (react to it via the
onToolsChanged option) without being rebuilt. Filtering is plain object work:
delete the keys you don't want before merging.
MCP skills (experimental): a server's instructions as skills
A server may serve skills (the Skills extension,
io.modelcontextprotocol/skills, Beta, written against 2026-07-28): SKILL.md instruction files
and the files they bundle. Opt in per server - they come with its tools: