Connect your agent to external Model Context Protocol (MCP) servers to use their tools, resources, and prompts. Agents SDK v0.20.0 uses @modelcontextprotocol/client and negotiates stateless or legacy behavior automatically. The MCP client does not need @modelcontextprotocol/sdk or @modelcontextprotocol/server.
Refer to Migrate to MCP SDK v2 for package, type, OAuth provider, and rollout changes.
The MCP client capability lets your agent:
- Connect to external MCP servers - GitHub, Slack, databases, AI services
- Use their tools - Call functions exposed by MCP servers
- Access resources - Read data from MCP servers
- Use prompts - Leverage pre-built prompt templates
import { Agent } from "agents";
export class MyAgent extends Agent {
async onRequest(request) {
// Add an MCP server
const result = await this.addMcpServer(
"github",
"https://mcp.github.com/mcp",
);
if (result.state === "authenticating") {
// Server requires OAuth - redirect user to authorize
return Response.redirect(result.authUrl);
}
// Server is ready - tools are now available
const state = this.getMcpServers();
console.log(`Connected! ${state.tools.length} tools available`);
return new Response("MCP server connected");
}
}import { Agent } from "agents";
export class MyAgent extends Agent {
async onRequest(request: Request) {
// Add an MCP server
const result = await this.addMcpServer(
"github",
"https://mcp.github.com/mcp",
);
if (result.state === "authenticating") {
// Server requires OAuth - redirect user to authorize
return Response.redirect(result.authUrl);
}
// Server is ready - tools are now available
const state = this.getMcpServers();
console.log(`Connected! ${state.tools.length} tools available`);
return new Response("MCP server connected");
}
}Connections persist in the agent's SQL storage, and when an agent connects to an MCP server, all tools from that server become available automatically.
Use addMcpServer() to connect to an MCP server. For non-OAuth servers, no options are needed:
// Non-OAuth server — no options required
await this.addMcpServer("notion", "https://mcp.notion.so/mcp");
// OAuth server — callbackHost is auto-derived from the incoming request,
// but you can set it explicitly if needed (e.g. custom domains)
await this.addMcpServer("github", "https://mcp.github.com/mcp", {
callbackHost: "https://my-worker.workers.dev",
});// Non-OAuth server — no options required
await this.addMcpServer("notion", "https://mcp.notion.so/mcp");
// OAuth server — callbackHost is auto-derived from the incoming request,
// but you can set it explicitly if needed (e.g. custom domains)
await this.addMcpServer("github", "https://mcp.github.com/mcp", {
callbackHost: "https://my-worker.workers.dev",
});By default, each connection is assigned a generated nanoid(8) ID. Pass id for connector-style integrations so tools surface as readable keys instead of opaque connection IDs.
await this.addMcpServer("GitHub", env.MCP_SESSION, {
id: "github",
props: { token: "..." },
});
// tools surface as `tool_github_<name>`await this.addMcpServer("GitHub", env.MCP_SESSION, {
id: "github",
props: { token: "..." },
});
// tools surface as `tool_github_<name>`When provided, this id replaces the generated value as the server's ID in storage, restore, listServers(), listTools(), getAITools(), and OAuth state. The supplied ID is normalized via the exported normalizeServerId helper, so values like "GitHub MCP!" become "github-mcp" — guaranteeing the ID is safe to embed in AI SDK tool names and storage keys.
Stable IDs are fully additive — no existing code breaks. If you add { id: "github" } to an addMcpServer call for a server already registered under an auto-generated ID, the SDK transparently migrates the existing storage row, in-memory connection, and OAuth-related storage keys to the new stable ID. No removeMcpServer step is required. addMcpServer only throws on a genuinely ambiguous collision: the same stable ID already belongs to a different (name, url) server.
MCP supports multiple transport types:
await this.addMcpServer("server", "https://mcp.example.com/mcp", {
transport: {
type: "streamable-http",
},
});await this.addMcpServer("server", "https://mcp.example.com/mcp", {
transport: {
type: "streamable-http",
},
});| Transport | Description |
|---|---|
auto |
Auto-detect based on server response (default) |
streamable-http |
HTTP with streaming |
sse |
Server-Sent Events - legacy/compatibility transport |
addMcpServer() can also connect to an McpAgent through its Durable Object binding instead of a URL. Messages travel over Workers RPC, so the server needs no HTTP endpoint.
export class MyAgent extends Agent {
async onStart() {
// env.MyMCP is the Durable Object binding for an McpAgent class
await this.addMcpServer("my-mcp", this.env.MyMCP, {
props: { userId: "user-123", role: "admin" },
});
}
}export class MyAgent extends Agent<Env> {
async onStart() {
// env.MyMCP is the Durable Object binding for an McpAgent class
await this.addMcpServer("my-mcp", this.env.MyMCP, {
props: { userId: "user-123", role: "admin" },
});
}
}- No authentication. The RPC transport has no OAuth flow. Pass user context in
props. TheMcpAgentreads it asthis.props. - Restored after hibernation. The binding name and props are stored, so the connection comes back without extra code.
- Deduplicated by name. Calling
addMcpServer()again with a name that already has an active RPC connection returns the existing connection, so it is safe to call inonStart(). - No MCP SDK v1 on the Agent side. Connecting does not need
@modelcontextprotocol/sdk. ImportRPCClientTransportandRPC_DO_PREFIXfromagents/mcp/client, notagents/mcp, which loads the v1 SDK.
For the server side, including bindings and the tool timeout, refer to RPC transport in the McpAgent reference.
For servers behind authentication (like Cloudflare Access) or using bearer tokens:
await this.addMcpServer("internal", "https://internal-mcp.example.com/mcp", {
transport: {
headers: {
Authorization: "Bearer my-token",
"CF-Access-Client-Id": "...",
"CF-Access-Client-Secret": "...",
},
},
});await this.addMcpServer("internal", "https://internal-mcp.example.com/mcp", {
transport: {
headers: {
Authorization: "Bearer my-token",
"CF-Access-Client-Id": "...",
"CF-Access-Client-Secret": "...",
},
},
});The headers are sent with every request, including the SSE stream, and are stored with the server, so a restored connection sends them too. They are stored as plain text in the Durable Object's SQLite storage.
MCP server URLs are validated before connection to prevent Server-Side Request Forgery (SSRF). The following URL targets are blocked:
- Private/internal IP ranges (RFC 1918:
10.x,172.16-31.x,192.168.x) - Unspecified addresses (
0.0.0.0,[::]) - Link-local addresses (
169.254.x,fe80::) - IPv6 unique-local addresses (
fc00::/7) - IPv4-mapped IPv6 addresses that resolve to private ranges (for example,
[::ffff:10.0.0.1]) - Cloud metadata endpoints (
metadata.google.internal)
Loopback addresses (localhost, 127.x.x.x, [::1]) are allowed for local development.
addMcpServer() returns the connection state:
ready- Server connected and tools discoveredauthenticating- Server requires OAuth; redirect user toauthUrl. This includes servers that accept the MCP handshake without a token but require one to list tools, prompts, or resources.
Calling addMcpServer() again for a server that is already registered returns its current state, replaces a link that expired, and throws for a failed server. If the server is still connecting, for example while it is restored after the agent wakes, the call waits for that attempt and returns its result. Pass a stable id so the server keeps the same ID everywhere.
Each connection makes a few quick attempts with the server's retry options. If they all fail, because the server is down, times out, or returns an error, the server is failed with the error, and the failure is recorded with the server. Nothing retries it on a timer, and later wakes show the same failed state without contacting the server. The server stays failed until something asks to connect it again.
When a wake finds a server that was not failed, the agent connects it again in the background with the same quick attempts. If the server is unreachable at that moment, it is failed from then on.
Retrying cannot help when authorization was refused, so these failures skip the quick attempts:
- The server answered
401and the agent cannot ask the user, for example because a static token passed intransport.headerswas revoked, or no OAuth callback is configured. When the agent can ask, the server moves toauthenticatingwith a new link instead. - The server answered
403. A403witherror="insufficient_scope"still starts a step-up first. It only counts as refused when no step-up is possible. - The authorization server refused with an OAuth error such as
invalid_target,invalid_scope, oraccess_denied. An expired or revoked refresh token (invalid_grant) starts a new authorization instead.server_errorandtemporarily_unavailablecount as an outage. - The authorization server rejected dynamic client registration with a
4xxstatus other than429. - The server still answers
401right after the user completed an authorization, for example because it rejects tokens from its own authorization server. The link that was just used is never shown again.
The server is marked failed with Authorization was refused: .... A callback where the user denied access, or whose code could not be exchanged, is recorded the same way, so a later wake does not start another flow that the user just turned down.
To try a failed server again, for example from a Reconnect button, call reconnectMcpServer(id). It clears why the server failed and its pending link, then connects now. It returns the same result as addMcpServer(), including a fresh authUrl when the user needs to authorize again.
import { Agent, callable } from "agents";
export class MyAgent extends Agent {
@callable()
async reconnectServer(id) {
return this.reconnectMcpServer(id);
}
}import { Agent, callable } from "agents";
export class MyAgent extends Agent<Env> {
@callable()
async reconnectServer(id: string) {
return this.reconnectMcpServer(id);
}
}Calling addMcpServer() for a server that is already registered does not retry a failure:
ready: returns the server as it is.authenticating: returns the link the server is waiting on.failed: throws the recorded error, which namesreconnectMcpServer().
Many MCP servers require OAuth authentication. The agent handles the OAuth flow automatically.
sequenceDiagram
participant Client
participant Agent
participant MCPServer
Client->>Agent: addMcpServer(name, url)
Agent->>MCPServer: Connect
MCPServer-->>Agent: Requires OAuth
Agent-->>Client: state: authenticating, authUrl
Client->>MCPServer: User authorizes
MCPServer->>Agent: Callback with code
Agent->>MCPServer: Exchange for token
Agent-->>Client: onMcpUpdate (ready)
class MyAgent extends Agent {
async onRequest(request) {
const result = await this.addMcpServer(
"github",
"https://mcp.github.com/mcp",
);
if (result.state === "authenticating") {
// Redirect the user to the OAuth authorization page
return Response.redirect(result.authUrl);
}
return Response.json({ status: "connected", id: result.id });
}
}class MyAgent extends Agent {
async onRequest(request: Request) {
const result = await this.addMcpServer(
"github",
"https://mcp.github.com/mcp",
);
if (result.state === "authenticating") {
// Redirect the user to the OAuth authorization page
return Response.redirect(result.authUrl);
}
return Response.json({ status: "connected", id: result.id });
}
}The callback URL is automatically constructed:
https://{host}/{agentsPrefix}/{agent-name}/{instance-name}/callbackFor example: https://my-worker.workers.dev/agents/my-agent/default/callback
OAuth tokens are securely stored in SQLite, and persist across agent restarts.
A server waiting for authorization keeps its link, across wakes too, until the user completes it or you call reconnectMcpServer(id). Whether an old link still works is up to the authorization server and the OAuth provider. The default provider accepts a callback for 10 minutes. If the user completes a link that no longer works, the callback reports the error and the server keeps waiting. Call reconnectMcpServer(id) to get a fresh link. If a callback already redeemed the link and the agent restarted before it finished, the agent reconnects with the saved tokens instead.
A request can need authorization again after the server is ready: a tool call that needs a scope the grant lacks (403 insufficient_scope), or a 401 whose token refresh fails. callTool(), readResource(), and getPrompt() then throw MCPAuthorizationRequiredError. The server moves to authenticating, and its auth_url is saved, so clients see the new link through getMcpServers() as they do when it connects. Send the user to error.authUrl. The normal OAuth callback completes the flow and reconnects. Retry the request when the server is ready again. Tools from getAITools() call callTool(), so their execute throws the same error.
import { MCPAuthorizationRequiredError } from "agents/mcp/client";
try {
return await this.mcp.callTool({ serverId, name: "deploy", arguments: {} });
} catch (error) {
if (error instanceof MCPAuthorizationRequiredError) {
return { needsAuthorization: true, authUrl: error.authUrl };
}
throw error;
}import { MCPAuthorizationRequiredError } from "agents/mcp/client";
try {
return await this.mcp.callTool({ serverId, name: "deploy", arguments: {} });
} catch (error) {
if (error instanceof MCPAuthorizationRequiredError) {
return { needsAuthorization: true, authUrl: error.authUrl };
}
throw error;
}MCPAuthorizationRequiredError extends the MCP SDK's UnauthorizedError, so existing instanceof UnauthorizedError checks still match. If no usable link was produced, for example because a custom OAuth provider does not put a fresh state in each authorization URL, or a callback for this server is already being processed, the call throws a plain UnauthorizedError.
- Scope step-up. The session keeps its current grant, so requests it already covers keep working while the user decides. If the user declines, the server goes back to
readyon that grant, and the next request that needs the scope asks again. - Refused refresh. No grant is left to keep working on. The server waits for the sign-in as it does when it connects: every request throws
MCPAuthorizationRequiredErrorwith the same link, and if the user declines, the server is markedfailed. - First authorization. A request to a server that is waiting for its first authorization throws
MCPAuthorizationRequiredErrorwith the link it is waiting on. - No connection. A call for a
serverIdwith no connection, because it was never registered, was removed, or is still being restored, throwsMCPConnectionNotFoundError.
Re-authorization is limited, as the MCP authorization specification asks. If the user completes three authorizations for the same scopes within an hour and the server still asks for them, for example because the authorization server never grants a scope, the next challenge does not produce a link. The server moves to failed with an error that names the scopes, the request throws UnauthorizedError, and the server stays failed until you call reconnectMcpServer(id).
When using sendIdentityOnConnect: false to hide sensitive instance names (like session IDs or user IDs), the default OAuth callback URL would expose the instance name. To prevent this security issue, you must provide a custom callbackPath.
import { Agent, routeAgentRequest, getAgentByName } from "agents";
export class SecureAgent extends Agent {
static options = { sendIdentityOnConnect: false };
async onRequest(request) {
// callbackPath is required when sendIdentityOnConnect is false
const result = await this.addMcpServer(
"github",
"https://mcp.github.com/mcp",
{
callbackPath: "mcp-oauth-callback", // Custom path without instance name
},
);
if (result.state === "authenticating") {
return Response.redirect(result.authUrl);
}
return new Response("Connected!");
}
}
// Route the custom callback path to the agent
export default {
async fetch(request, env) {
const url = new URL(request.url);
// Route custom MCP OAuth callback to agent instance
if (url.pathname.startsWith("/mcp-oauth-callback")) {
// Implement this to extract the instance name from your session/auth mechanism
const instanceName = await getInstanceNameFromSession(request);
const agent = await getAgentByName(env.SecureAgent, instanceName);
return agent.fetch(request);
}
// Standard agent routing
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
};import { Agent, routeAgentRequest, getAgentByName } from "agents";
export class SecureAgent extends Agent {
static options = { sendIdentityOnConnect: false };
async onRequest(request: Request) {
// callbackPath is required when sendIdentityOnConnect is false
const result = await this.addMcpServer(
"github",
"https://mcp.github.com/mcp",
{
callbackPath: "mcp-oauth-callback", // Custom path without instance name
},
);
if (result.state === "authenticating") {
return Response.redirect(result.authUrl);
}
return new Response("Connected!");
}
}
// Route the custom callback path to the agent
export default {
async fetch(request: Request, env: Env) {
const url = new URL(request.url);
// Route custom MCP OAuth callback to agent instance
if (url.pathname.startsWith("/mcp-oauth-callback")) {
// Implement this to extract the instance name from your session/auth mechanism
const instanceName = await getInstanceNameFromSession(request);
const agent = await getAgentByName(env.SecureAgent, instanceName);
return agent.fetch(request);
}
// Standard agent routing
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
} satisfies ExportedHandler<Env>;Configure how OAuth completion is handled. By default, successful authentication redirects to your application origin, while failed authentication displays an HTML error page.
export class MyAgent extends Agent {
onStart() {
this.mcp.configureOAuthCallback({
// Redirect after successful auth
successRedirect: "https://myapp.com/success",
// Redirect on error with error message in query string
errorRedirect: "https://myapp.com/error",
// Or use a custom handler
customHandler: () => {
// Close popup window after auth completes
return new Response("<script>window.close();</script>", {
headers: { "content-type": "text/html" },
});
},
});
}
}export class MyAgent extends Agent {
onStart() {
this.mcp.configureOAuthCallback({
// Redirect after successful auth
successRedirect: "https://myapp.com/success",
// Redirect on error with error message in query string
errorRedirect: "https://myapp.com/error",
// Or use a custom handler
customHandler: () => {
// Close popup window after auth completes
return new Response("<script>window.close();</script>", {
headers: { "content-type": "text/html" },
});
},
});
}
}Once connected, access the server's capabilities:
Use listTools() to inspect the raw MCP catalog without preparing tools for an AI SDK model call:
const tools = this.mcp.listTools();
for (const tool of tools) {
console.log(`Tool: ${tool.name}`);
console.log(` From server: ${tool.serverId}`);
console.log(` Title: ${tool.title ?? tool.annotations?.title ?? tool.name}`);
console.log(` Description: ${tool.description}`);
}const tools = this.mcp.listTools();
for (const tool of tools) {
console.log(`Tool: ${tool.name}`);
console.log(` From server: ${tool.serverId}`);
console.log(` Title: ${tool.title ?? tool.annotations?.title ?? tool.name}`);
console.log(` Description: ${tool.description}`);
}getMcpServers().tools returns the same raw tool records as part of the full MCP client state. Neither API converts the tool schemas.
To use MCP tools with the AI SDK, use this.mcp.getAITools() which converts MCP tools to AI SDK format:
import { generateText } from "ai";
import { createAI } from "agents/models/ai-sdk";
export class MyAgent extends Agent {
async onRequest(request) {
const ai = createAI({ binding: this.env.AI });
const response = await generateText({
model: ai("@cf/zai-org/glm-4.7-flash"),
prompt: "What's the weather in San Francisco?",
tools: this.mcp.getAITools(),
});
return new Response(response.text);
}
}import { generateText } from "ai";
import { createAI } from "agents/models/ai-sdk";
export class MyAgent extends Agent<Env> {
async onRequest(request: Request) {
const ai = createAI({ binding: this.env.AI });
const response = await generateText({
model: ai("@cf/zai-org/glm-4.7-flash"),
prompt: "What's the weather in San Francisco?",
tools: this.mcp.getAITools(),
});
return new Response(response.text);
}
}const state = this.getMcpServers();
// Available resources
for (const resource of state.resources) {
console.log(`Resource: ${resource.name} (${resource.uri})`);
}
// Available prompts
for (const prompt of state.prompts) {
console.log(`Prompt: ${prompt.name}`);
}const state = this.getMcpServers();
// Available resources
for (const resource of state.resources) {
console.log(`Resource: ${resource.name} (${resource.uri})`);
}
// Available prompts
for (const prompt of state.prompts) {
console.log(`Prompt: ${prompt.name}`);
}MCP servers can request user input while handling another operation. On the stateless path, elicitation returns input_required and completes through multi-round-trip requests (MRTR). On the legacy path, the server sends pushed elicitation/create requests. Both use form and URL modes.
Register a handler for each mode your Agent supports in onStart(). The same handlers serve both lanes:
import { Agent } from "agents";
class MyAgent extends Agent {
onStart() {
this.mcp.configureElicitationHandlers({
form: (request, serverId) =>
this.forwardElicitationToBrowser(request, serverId),
url: (request, serverId) =>
this.forwardElicitationToBrowser(request, serverId),
});
}
forwardElicitationToBrowser(request, serverId) {
// Forward the request to your UI and resolve after the user responds.
// A complete implementation appears in Forward elicitation to a UI.
throw new Error(
`Implement elicitation for ${serverId}: ${request.params.message}`,
);
}
}import { Agent } from "agents";
import type { ElicitRequest, ElicitResult } from "agents/mcp/client";
class MyAgent extends Agent<Env> {
onStart() {
this.mcp.configureElicitationHandlers({
form: (request, serverId) =>
this.forwardElicitationToBrowser(request, serverId),
url: (request, serverId) =>
this.forwardElicitationToBrowser(request, serverId),
});
}
private forwardElicitationToBrowser(
request: ElicitRequest,
serverId: string,
): Promise<ElicitResult> {
// Forward the request to your UI and resolve after the user responds.
// A complete implementation appears in Forward elicitation to a UI.
throw new Error(
`Implement elicitation for ${serverId}: ${request.params.message}`,
);
}
}The serverId identifies the connection that sent the request. Use it to tell the user which server is asking for input and to apply server-specific policy.
The SDK advertises only the modes with configured handlers. Connections on the legacy path advertise them during initialize. Requests on the stateless path carry them with request capabilities. A form-only handler advertises form mode. A URL-only handler advertises URL mode. A connection without handlers advertises no elicitation capability, which lets the server use its fallback.
The SDK stores the advertised modes with each server registration. A connection restored after Durable Object hibernation can therefore advertise the same modes when it reconnects. Callback functions remain in memory and reattach when onStart() runs.
You can explicitly narrow the advertised modes when adding a server:
await this.addMcpServer("portal", "https://portal.example.com/mcp", {
client: {
capabilities: {
elicitation: { form: {} },
},
},
});await this.addMcpServer("portal", "https://portal.example.com/mcp", {
client: {
capabilities: {
elicitation: { form: {} },
},
},
});An explicit client.capabilities.elicitation value takes precedence over handler-derived modes and persists with the server registration. Do not advertise a mode without a matching handler. If the server sends that mode, the connection returns an error because it cannot handle the request.
Form mode collects structured, non-sensitive data in the client. The request includes a restricted JSON Schema in requestedSchema. If the user submits the form, return action: "accept" with matching content:
this.mcp.configureElicitationHandlers({
form: async (request) => {
const content = await showFormToUser(request.params.requestedSchema);
return content ? { action: "accept", content } : { action: "cancel" };
},
});this.mcp.configureElicitationHandlers({
form: async (request) => {
const content = await showFormToUser(request.params.requestedSchema);
return content ? { action: "accept", content } : { action: "cancel" };
},
});Allow the user to review and edit values before submission. Validate accepted content against requestedSchema. Do not use form mode to request passwords, API keys, access tokens, payment credentials, or other secrets.
URL mode asks the user to open an external page. Use it for out-of-band interactions that may collect secrets, such as third-party authorization or payment. Keep the URL in the dedicated elicitation path and out of model-visible messages and tool-result text.
A URL handler should:
- Show which MCP server sent the request.
- Show the request message, target host, and full URL.
- Ask for consent before opening the URL.
- Open the page in a browser context the Agent and model cannot inspect.
- Return
action: "accept"withoutcontentafter consent. - Offer distinct decline and cancel controls.
Do not prefetch the URL or its metadata. Treat the URL as untrusted input. Production servers should send HTTPS URLs.
For URL mode, accept means the user consented to open the URL. It does not mean the external interaction finished. A server may later send notifications/elicitation/complete with the request elicitationId.
Both modes support three actions:
| Action | Meaning |
|---|---|
accept |
The user submitted the form or consented to open the URL. |
decline |
The user explicitly rejected the request. |
cancel |
The user dismissed the request without making an explicit choice. |
Include content only for an accepted form response. Omit it for URL, decline, and cancel responses.
A handler returns a promise, but the response often comes from a browser. Broadcast the request to connected clients, then resolve the promise through a @callable method:
import { Agent, callable } from "agents";
class MyAgent extends Agent {
pendingElicitations = new Map();
onStart() {
this.mcp.configureElicitationHandlers({
form: (request, serverId) => this.forward(request, serverId),
url: (request, serverId) => this.forward(request, serverId),
});
}
forward(request, serverId) {
const id = crypto.randomUUID();
const result = new Promise((resolve) => {
const timeout = setTimeout(() => {
if (this.pendingElicitations.delete(id)) {
resolve({ action: "cancel" });
}
}, 55_000);
this.pendingElicitations.set(id, { resolve, timeout });
});
this.broadcast(
JSON.stringify({
type: "mcp-elicitation",
id,
serverId,
params: request.params,
}),
);
return result;
}
@callable()
respondToElicitation(id, result) {
const pending = this.pendingElicitations.get(id);
if (!pending) return;
this.pendingElicitations.delete(id);
clearTimeout(pending.timeout);
pending.resolve(result);
}
}import { Agent, callable } from "agents";
import type { ElicitRequest, ElicitResult } from "agents/mcp/client";
type PendingResolver = {
resolve: (result: ElicitResult) => void;
timeout: ReturnType<typeof setTimeout>;
};
class MyAgent extends Agent<Env> {
private pendingElicitations = new Map<string, PendingResolver>();
onStart() {
this.mcp.configureElicitationHandlers({
form: (request, serverId) => this.forward(request, serverId),
url: (request, serverId) => this.forward(request, serverId),
});
}
private forward(
request: ElicitRequest,
serverId: string,
): Promise<ElicitResult> {
const id = crypto.randomUUID();
const result = new Promise<ElicitResult>((resolve) => {
const timeout = setTimeout(() => {
if (this.pendingElicitations.delete(id)) {
resolve({ action: "cancel" });
}
}, 55_000);
this.pendingElicitations.set(id, { resolve, timeout });
});
this.broadcast(
JSON.stringify({
type: "mcp-elicitation",
id,
serverId,
params: request.params,
}),
);
return result;
}
@callable()
respondToElicitation(id: string, result: ElicitResult) {
const pending = this.pendingElicitations.get(id);
if (!pending) return;
this.pendingElicitations.delete(id);
clearTimeout(pending.timeout);
pending.resolve(result);
}
}The example uses a 55-second timeout because MCP SDK requests default to 60 seconds. If your client call sets a longer request timeout, adjust this timeout to finish first.
Refer to the mcp-client example ↗︎ for the browser implementation. mcp-elicitation-mrtr ↗︎ demonstrates stateless elicitation.
For the server side, refer to Elicitation with a stateless handler.
MCP server registrations persist across Agent restarts. The SDK stores server configuration in SQLite, stores OAuth tokens securely, and restores HTTP and RPC connections in the background when the Agent wakes, so startup never waits on an MCP server. Call waitForConnections() when you need the restored tools.
When you manage servers:
- Add servers with a stable
id, from a callable that the user triggers or fromonStart(). - Render each server from
getMcpServers(), oronMcpUpdateinuseAgent. Send the user toauth_urlwhile the server isauthenticating, and showerrorwith a Reconnect button that callsreconnectMcpServer(id)while it isfailed. - Catch
MCPAuthorizationRequiredErrorfromcallTool(),readResource(), andgetPrompt(), and give the usererror.authUrl.
const state = this.getMcpServers();
for (const [id, server] of Object.entries(state.servers)) {
console.log(`${id}: ${server.name} (${server.server_url})`);
}const state = this.getMcpServers();
for (const [id, server] of Object.entries(state.servers)) {
console.log(`${id}: ${server.name} (${server.server_url})`);
}Use the server ID to inspect an individual connection:
const state = this.getMcpServers();
const server = state.servers[serverId];
if (server) {
console.log(`${server.name}: ${server.state}`);
// state: "ready" | "authenticating" | "connecting" | "connected" | "discovering" | "failed"
}const state = this.getMcpServers();
const server = state.servers[serverId];
if (server) {
console.log(`${server.name}: ${server.state}`);
// state: "ready" | "authenticating" | "connecting" | "connected" | "discovering" | "failed"
}await this.removeMcpServer(serverId);await this.removeMcpServer(serverId);This disconnects from the server and removes it from storage.
Connected clients receive real-time MCP updates via WebSocket:
import { useAgent } from "agents/react";
import { useState } from "react";
function Dashboard() {
const [tools, setTools] = useState([]);
const [servers, setServers] = useState({});
// reconnectServer is a @callable() that calls this.reconnectMcpServer(id)
const agent = useAgent({
agent: "MyAgent",
onMcpUpdate: (mcpState) => {
setTools(mcpState.tools);
setServers(mcpState.servers);
},
});
return (
<div>
<h2>Connected Servers</h2>
{Object.entries(servers).map(([id, server]) => (
<div key={id}>
{server.name}: {server.state}
{server.state === "authenticating" && server.auth_url && (
<a href={server.auth_url} target="_blank">
Authorize
</a>
)}
{server.state === "failed" && (
<>
{server.error}
<button onClick={() => agent.call("reconnectServer", [id])}>
Reconnect
</button>
</>
)}
</div>
))}
<h2>Available Tools ({tools.length})</h2>
{tools.map((tool) => (
<div key={`${tool.serverId}-${tool.name}`}>{tool.name}</div>
))}
</div>
);
}import { useAgent } from "agents/react";
import { useState } from "react";
function Dashboard() {
const [tools, setTools] = useState([]);
const [servers, setServers] = useState({});
// reconnectServer is a @callable() that calls this.reconnectMcpServer(id)
const agent = useAgent({
agent: "MyAgent",
onMcpUpdate: (mcpState) => {
setTools(mcpState.tools);
setServers(mcpState.servers);
},
});
return (
<div>
<h2>Connected Servers</h2>
{Object.entries(servers).map(([id, server]) => (
<div key={id}>
{server.name}: {server.state}
{server.state === "authenticating" && server.auth_url && (
<a href={server.auth_url} target="_blank">
Authorize
</a>
)}
{server.state === "failed" && (
<>
{server.error}
<button onClick={() => agent.call("reconnectServer", [id])}>
Reconnect
</button>
</>
)}
</div>
))}
<h2>Available Tools ({tools.length})</h2>
{tools.map((tool) => (
<div key={`${tool.serverId}-${tool.name}`}>{tool.name}</div>
))}
</div>
);
}Add a connection to an MCP server and make its tools available to your agent.
Calling addMcpServer is idempotent when both the server name and URL match an existing connection — the existing connection is returned without creating a duplicate. This makes it safe to call in onStart() without worrying about duplicate connections on restart. For a server that is failed, it throws the recorded error instead of retrying. Call reconnectMcpServer() to try again.
If you call addMcpServer with the same name but a different URL, a new connection is created. Both connections remain active and their tools are merged in getAITools(). To replace a server, call removeMcpServer(oldId) first.
URLs are normalized before comparison (trailing slashes, default ports, and hostname case are handled), so https://MCP.Example.com and https://mcp.example.com/ are treated as the same URL.
// HTTP transport (Streamable HTTP, SSE)
async addMcpServer(
serverName: string,
url: string,
options?: {
id?: string;
callbackHost?: string;
callbackPath?: string;
agentsPrefix?: string;
client?: McpClientOptions;
transport?: {
headers?: HeadersInit;
type?: "sse" | "streamable-http" | "auto";
};
retry?: RetryOptions;
}
): Promise<
| { id: string; state: "authenticating"; authUrl: string }
| { id: string; state: "ready" }
>
// RPC transport (Durable Object binding for an McpAgent)
async addMcpServer(
serverName: string,
binding: DurableObjectNamespace<McpAgent>,
options?: {
id?: string;
props?: Record<string, unknown>;
}
): Promise<{ id: string; state: "ready" }>serverName(string, required) — Display name for the MCP serverurl(string, required) — URL of the MCP server endpointoptions(object, optional) — Connection configuration:id— Optional stable, caller-supplied server ID for connector-style integrations. When provided, it replaces the generatednanoid(8)across storage,listServers(),listTools(),getAITools()(so tool keys become readable, for exampletool_github_create_pull_request), and OAuth state. Refer to Stable server IDscallbackHost— Host for OAuth callback URL. Only needed for OAuth-authenticated servers. If omitted, automatically derived from the incoming request or WebSocket connection URI — you typically do not need to set this unless you are using a custom domain that differs from the Worker's hostnamecallbackPath— Custom callback URL path that bypasses the default/agents/{class}/{name}/callbackconstruction. Required whensendIdentityOnConnectisfalseto prevent leaking the instance name. When set, the callback URL becomes{callbackHost}/{callbackPath}. You must route this path to the agent instance viagetAgentByNameagentsPrefix— URL prefix for OAuth callback path. Default:"agents". Ignored whencallbackPathis providedclient— The Agents-supportedMcpClientOptionssubset from@modelcontextprotocol/client. The default validator supports JSON Schema 2020-12 and legacy draft-07 schemas in Workerstransport— Transport layer configuration:headers— Custom HTTP headers for authenticationtype— Transport type:"auto"(default),"streamable-http", or"sse"
retry— How many quick attempts a connection makes before the server counts as failed. Persisted and used for every connection attempt: when the server is added, when it is restored after hibernation, after OAuth completes, and onreconnectMcpServer(). Default: 3 attempts, 500ms base delay, 5s max delay. Refer to Retries for details onRetryOptions.
serverName(string, required) — Display name for the MCP serverbinding(DurableObjectNamespace, required) — Durable Object binding for anMcpAgentclassoptions(object, optional):id— Optional stable, caller-supplied server ID. Refer to Stable server IDsprops— Data passed to theMcpAgentand available asthis.props, such as user context
The RPC transport only connects to the deprecated McpAgent. Prefer the HTTP transport with a createMcpHandler server. Refer to RPC transport.
A Promise that resolves to a discriminated union based on connection state:
- When
stateis"authenticating":id(string) — Unique identifier for this server connectionstate("authenticating") — Server is waiting for OAuth authorizationauthUrl(string) — OAuth authorization URL for user authentication
- When
stateis"ready":id(string) — Unique identifier for this server connectionstate("ready") — Server is fully connected and operational
Connect a registered server again now, for example after it failed. It clears the recorded failure and any pending authorization link before it connects. Refer to Failures and reconnecting.
async reconnectMcpServer(id: string): Promise<
| { id: string; state: "authenticating"; authUrl: string }
| { id: string; state: "ready" }
>id(string, required) — Server connection ID returned fromaddMcpServer()
The same result as addMcpServer(), including a fresh authUrl when the user needs to authorize again. Throws when the server is not registered, or when the attempt fails.
Disconnect from an MCP server and clean up its resources.
async removeMcpServer(id: string): Promise<void>id(string, required) — Server connection ID returned fromaddMcpServer()
Get the current state of all MCP server connections.
getMcpServers(): MCPServersStatetype MCPServersState = {
servers: Record<
string,
{
name: string;
server_url: string;
auth_url: string | null;
state:
| "authenticating"
| "connecting"
| "connected"
| "discovering"
| "ready"
| "failed";
capabilities: ServerCapabilities | null;
instructions: string | null;
error: string | null;
}
>;
tools: Array<Tool & { serverId: string }>;
prompts: Array<Prompt & { serverId: string }>;
resources: Array<Resource & { serverId: string }>;
resourceTemplates: Array<ResourceTemplate & { serverId: string }>;
};The state field indicates the connection lifecycle:
authenticating— Waiting for OAuth authorization to completeconnecting— Establishing transport connectionconnected— Transport connection establisheddiscovering— Discovering server capabilities (tools, resources, prompts)ready— Fully connected and operationalfailed— Connection failed (seeerrorfield for details)
The error field contains an error message when state is "failed". Error messages from external OAuth providers are automatically escaped to prevent XSS attacks, making them safe to display directly in your UI.
Configure OAuth callback behavior for MCP servers requiring authentication. This method allows you to customize what happens after a user completes OAuth authorization.
this.mcp.configureOAuthCallback(options: {
successRedirect?: string;
errorRedirect?: string;
customHandler?: () => Response | Promise<Response>;
}): voidoptions(object, required) — OAuth callback configuration:successRedirect(string, optional) — URL to redirect to after successful authenticationerrorRedirect(string, optional) — URL to redirect to after failed authentication. Error message is appended as?error=<message>query parametercustomHandler(function, optional) — Custom handler for complete control over the callback response. Must return a Response
When no configuration is provided:
- Success: Redirects to your application origin
- Failure: Displays an HTML error page with the error message
If OAuth fails, the connection state becomes "failed" and the error message is stored in the server.error field for display in your UI.
Configure in onStart() before any OAuth flows begin:
export class MyAgent extends Agent {
onStart() {
// Option 1: Simple redirects
this.mcp.configureOAuthCallback({
successRedirect: "/dashboard",
errorRedirect: "/auth-error",
});
// Option 2: Custom handler (e.g., for popup windows)
this.mcp.configureOAuthCallback({
customHandler: () => {
return new Response("<script>window.close();</script>", {
headers: { "content-type": "text/html" },
});
},
});
}
}export class MyAgent extends Agent {
onStart() {
// Option 1: Simple redirects
this.mcp.configureOAuthCallback({
successRedirect: "/dashboard",
errorRedirect: "/auth-error",
});
// Option 2: Custom handler (e.g., for popup windows)
this.mcp.configureOAuthCallback({
customHandler: () => {
return new Response("<script>window.close();</script>", {
headers: { "content-type": "text/html" },
});
},
});
}
}Configure handlers for stateless elicitation and legacy elicitation/create requests. Add a handler for each elicitation mode your Agent supports.
this.mcp.configureElicitationHandlers(handlers?: {
form?: (
request: ElicitRequest,
serverId: string,
signal?: AbortSignal,
) => Promise<ElicitResult>;
url?: (
request: ElicitRequest,
serverId: string,
signal?: AbortSignal,
) => Promise<ElicitResult>;
}): voidhandlers(object, optional) — Elicitation handlers keyed by mode:form(function, optional) — Handles form-mode requests for structured, non-sensitive input.url(function, optional) — Handles URL-mode requests for out-of-band interactions.
request(ElicitRequest) — The MCP elicitation request. Inspectrequest.params.modefor the mode-specific fields.serverId(string) — The ID of the MCP server connection that sent the request.signal(AbortSignal, optional) — Aborts when the originating MCP operation is cancelled.
Each handler returns a promise containing an ElicitResult. Return accept, decline, or cancel. Accepted form responses include content that matches requestedSchema. URL responses omit content.
Passing undefined clears all configured handlers.
The client advertises only modes with configured handlers during legacy negotiation and on stateless requests. Handler changes apply immediately to live connections, but servers receive updated advertised modes after those connections reconnect.
The SDK stores the handler-derived modes with each MCP server registration. Restored connections advertise those modes after Durable Object hibernation, and callbacks reattach when onStart() runs.
Configure handlers in onStart():
import { Agent } from "agents";
export class MyAgent extends Agent {
onStart() {
this.mcp.configureElicitationHandlers({
form: (request, serverId) =>
this.forwardElicitationToBrowser(request, serverId),
url: (request, serverId) =>
this.forwardElicitationToBrowser(request, serverId),
});
}
forwardElicitationToBrowser(request, serverId) {
// Forward the request to your UI and resolve after the user responds.
throw new Error(
`Implement elicitation for ${serverId}: ${request.params.message}`,
);
}
}import { Agent } from "agents";
import type { ElicitRequest, ElicitResult } from "agents/mcp/client";
export class MyAgent extends Agent<Env> {
onStart() {
this.mcp.configureElicitationHandlers({
form: (request, serverId) =>
this.forwardElicitationToBrowser(request, serverId),
url: (request, serverId) =>
this.forwardElicitationToBrowser(request, serverId),
});
}
private forwardElicitationToBrowser(
request: ElicitRequest,
serverId: string,
): Promise<ElicitResult> {
// Forward the request to your UI and resolve after the user responds.
throw new Error(
`Implement elicitation for ${serverId}: ${request.params.message}`,
);
}
}For the complete browser forwarding pattern and mode-specific requirements, refer to Elicitation.
Override the default OAuth provider used when connecting to MCP servers by implementing createMcpOAuthProvider() on your Agent class. This enables custom authentication strategies such as pre-registered client credentials or mTLS, beyond the built-in dynamic client registration.
The override is used for both new connections (addMcpServer) and restored connections after a Durable Object restart.
import { Agent } from "agents";
export class MyAgent extends Agent {
createMcpOAuthProvider(callbackUrl) {
const env = this.env;
return {
get redirectUrl() {
return callbackUrl;
},
get clientMetadata() {
return {
client_id: env.MCP_CLIENT_ID,
client_secret: env.MCP_CLIENT_SECRET,
redirect_uris: [callbackUrl],
};
},
clientInformation() {
return {
client_id: env.MCP_CLIENT_ID,
client_secret: env.MCP_CLIENT_SECRET,
};
},
};
}
}import { Agent } from "agents";
import type { AgentMcpOAuthProvider } from "agents";
export class MyAgent extends Agent<Env> {
createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {
const env = this.env;
return {
get redirectUrl() {
return callbackUrl;
},
get clientMetadata() {
return {
client_id: env.MCP_CLIENT_ID,
client_secret: env.MCP_CLIENT_SECRET,
redirect_uris: [callbackUrl],
};
},
clientInformation() {
return {
client_id: env.MCP_CLIENT_ID,
client_secret: env.MCP_CLIENT_SECRET,
};
},
};
}
}If you do not override this method, the agent uses the default provider which performs OAuth 2.0 Dynamic Client Registration ↗︎ with the MCP server.
To keep the built-in OAuth logic (CSRF state, PKCE, nonce generation, token management) but route token storage to a different backend, import DurableObjectOAuthClientProvider and pass your own storage adapter:
import { Agent, DurableObjectOAuthClientProvider } from "agents";
export class MyAgent extends Agent {
createMcpOAuthProvider(callbackUrl) {
return new DurableObjectOAuthClientProvider(
myCustomStorage, // any DurableObjectStorage-compatible adapter
this.name,
callbackUrl,
);
}
}import { Agent, DurableObjectOAuthClientProvider } from "agents";
import type { AgentMcpOAuthProvider } from "agents";
export class MyAgent extends Agent {
createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {
return new DurableObjectOAuthClientProvider(
myCustomStorage, // any DurableObjectStorage-compatible adapter
this.name,
callbackUrl,
);
}
}For fine-grained control, use this.mcp directly:
// 1. Register the server (saves to storage and creates in-memory connection)
const id = "my-server";
await this.mcp.registerServer(id, {
url: "https://mcp.example.com/mcp",
name: "My Server",
callbackUrl: "https://my-worker.workers.dev/agents/my-agent/default/callback",
transport: { type: "auto" },
});
// 2. Connect (initializes transport, handles OAuth if needed)
const connectResult = await this.mcp.connectToServer(id);
if (connectResult.state === "failed") {
console.error("Connection failed:", connectResult.error);
return;
}
if (connectResult.state === "authenticating") {
console.log("OAuth required:", connectResult.authUrl);
return;
}
// 3. Discover capabilities (transitions from "connected" to "ready")
if (connectResult.state === "connected") {
const discoverResult = await this.mcp.discoverIfConnected(id);
if (!discoverResult?.success) {
console.error("Discovery failed:", discoverResult?.error);
}
}// 1. Register the server (saves to storage and creates in-memory connection)
const id = "my-server";
await this.mcp.registerServer(id, {
url: "https://mcp.example.com/mcp",
name: "My Server",
callbackUrl: "https://my-worker.workers.dev/agents/my-agent/default/callback",
transport: { type: "auto" },
});
// 2. Connect (initializes transport, handles OAuth if needed)
const connectResult = await this.mcp.connectToServer(id);
if (connectResult.state === "failed") {
console.error("Connection failed:", connectResult.error);
return;
}
if (connectResult.state === "authenticating") {
console.log("OAuth required:", connectResult.authUrl);
return;
}
// 3. Discover capabilities (transitions from "connected" to "ready")
if (connectResult.state === "connected") {
const discoverResult = await this.mcp.discoverIfConnected(id);
if (!discoverResult?.success) {
console.error("Discovery failed:", discoverResult?.error);
}
}// Listen for state changes (onServerStateChanged is an Event<void>)
const disposable = this.mcp.onServerStateChanged(() => {
console.log("MCP server state changed");
this.broadcastMcpServers(); // Notify connected clients
});
// Clean up the subscription when no longer needed
// disposable.dispose();// Listen for state changes (onServerStateChanged is an Event<void>)
const disposable = this.mcp.onServerStateChanged(() => {
console.log("MCP server state changed");
this.broadcastMcpServers(); // Notify connected clients
});
// Clean up the subscription when no longer needed
// disposable.dispose();Register a server without immediately connecting.
async registerServer(
id: string,
options: {
url: string;
name: string;
callbackUrl: string;
clientOptions?: ClientOptions;
transportOptions?: TransportOptions;
}
): Promise<string>Establish a connection to a previously registered server. On a standalone MCPClientManager, this is the explicit retry: it clears a recorded failure and the step-up budget before it connects. On an Agent, use reconnectMcpServer(id).
async connectToServer(id: string): Promise<MCPConnectionResult>
type MCPConnectionResult =
| { state: "failed"; error: string }
| { state: "authenticating"; authUrl: string }
| { state: "connected" }Check server capabilities if a connection is active.
async discoverIfConnected(
serverId: string,
options?: { timeoutMs?: number }
): Promise<MCPDiscoverResult | undefined>
type MCPDiscoverResult = {
success: boolean;
state: MCPConnectionState;
error?: string;
}Wait for all in-flight MCP connection and discovery operations to settle. This applies to HTTP and RPC servers alike. This is useful when you need this.mcp.getAITools() to return the full set of tools immediately after the agent wakes from hibernation.
// Wait indefinitely
await this.mcp.waitForConnections();
// Wait with a timeout (milliseconds)
await this.mcp.waitForConnections({ timeout: 10_000 });Close the connection to a specific server while keeping it registered.
async closeConnection(id: string): Promise<void>Close all active server connections while preserving registrations.
async closeAllConnections(): Promise<void>Get raw MCP tool records without converting their schemas to Zod.
listTools(filter?: MCPServerFilter): Array<Tool & { serverId: string }>Use this method for catalog discovery and inspection. Pass an MCPServerFilter to limit the returned tools to specific connections.
Get all discovered MCP tools in a format compatible with the AI SDK.
getAITools(filter?: MCPServerFilter): ToolSetTools are automatically namespaced by server ID to prevent conflicts when multiple MCP servers expose tools with the same name.
getAITools() reuses converted schemas for the current catalog on each live connection. It converts schemas again after discovery replaces the catalog or the live connection changes. Each call returns fresh tool records and execute functions. Use this.mcp.listTools() when you only need the raw catalog.
Pass an MCPServerFilter to scope the returned tools to a subset of connected servers:
// Tools from a specific server only
const githubTools = this.mcp.getAITools({ serverId: "github" });
// Tools from multiple servers
const tools = this.mcp.getAITools({ serverId: ["github", "notion"] });
// Tools from servers matching a name
const tools = this.mcp.getAITools({ serverName: "GitHub" });
// Only tools from servers that are ready
const tools = this.mcp.getAITools({ state: "ready" });// Tools from a specific server only
const githubTools = this.mcp.getAITools({ serverId: "github" });
// Tools from multiple servers
const tools = this.mcp.getAITools({ serverId: ["github", "notion"] });
// Tools from servers matching a name
const tools = this.mcp.getAITools({ serverName: "GitHub" });
// Only tools from servers that are ready
const tools = this.mcp.getAITools({ state: "ready" });The filter type is available from agents/mcp/client:
import type { MCPServerFilter } from "agents/mcp/client";
type MCPServerFilter = {
serverId?: string | string[];
serverName?: string | string[];
state?: MCPConnectionState | MCPConnectionState[];
};All specified filter criteria are AND'd together. The same filter parameter is accepted by listTools(), listPrompts(), listResources(), and listResourceTemplates().
Use error detection utilities to handle connection errors:
import { isUnauthorized, isTransportNotImplemented } from "agents";
export class MyAgent extends Agent {
async onRequest(request) {
try {
await this.addMcpServer("Server", "https://mcp.example.com/mcp");
} catch (error) {
if (isUnauthorized(error)) {
return new Response("Authentication required", { status: 401 });
} else if (isTransportNotImplemented(error)) {
return new Response("Transport not supported", { status: 400 });
}
throw error;
}
}
}import { isUnauthorized, isTransportNotImplemented } from "agents";
export class MyAgent extends Agent {
async onRequest(request: Request) {
try {
await this.addMcpServer("Server", "https://mcp.example.com/mcp");
} catch (error) {
if (isUnauthorized(error)) {
return new Response("Authentication required", { status: 401 });
} else if (isTransportNotImplemented(error)) {
return new Response("Transport not supported", { status: 400 });
}
throw error;
}
}
}| Error | When it is thrown |
|---|---|
MCPAuthorizationRequiredError |
A request needs the user to authorize, or authorize again. Send the user to error.authUrl. Refer to Re-authorization during a session |
MCPConnectionNotFoundError |
A call names a serverId with no connection: never registered, removed, or still being restored |
| The recorded error | addMcpServer() for a server that is failed. Call reconnectMcpServer(id) to try again |
Import MCPAuthorizationRequiredError and MCPConnectionNotFoundError from agents/mcp/client.