Documentation Index Fetch the complete documentation index at: https://mintlify.com/cloudflare/agents/llms.txt
Use this file to discover all available pages before exploring further.
Overview
MCPClientManager allows Agents to connect to external MCP servers and access their tools, prompts, and resources. It’s automatically available via this.mcp in all Agents.
class MyAgent extends Agent {
async onStart () {
// Register an MCP server
const serverId = await this . mcp . registerServer ( "weather-server" , {
url: "https://weather-mcp.example.com" ,
name: "Weather Server"
});
// Connect to the server
await this . mcp . connectToServer ( serverId );
// Discover capabilities
await this . mcp . discoverIfConnected ( serverId );
}
@ callable ()
async getWeather ( location : string ) {
const result = await this . mcp . callTool ({
serverId: "weather-server" ,
name: "get_weather" ,
arguments: { location }
});
return result ;
}
}
Registration & Connection
registerServer()
Register an MCP server without connecting. Creates the connection object, sets up observability, and saves to storage.
Unique identifier for the server
options
RegisterServerOptions
required
Server URL (http/https for remote, rpc:// for Durable Object)
Human-readable server name
OAuth callback URL (auto-derived from request if omitted)
client
ConstructorParameters<typeof Client>[1]
MCP client options
Transport configuration (headers, type)
Retry options for connection attempts
const serverId = await this . mcp . registerServer ( "my-server" , {
url: "https://mcp-server.example.com" ,
name: "My MCP Server" ,
transport: {
headers: {
"Authorization" : "Bearer token"
},
type: "streamable-http"
},
retry: {
maxAttempts: 5 ,
baseDelayMs: 200
}
});
Returns: Promise<string> - Server ID
connectToServer()
Connect to a registered MCP server and initialize the connection.
Server ID (from registerServer)
const result = await this . mcp . connectToServer ( "my-server" );
if ( result . state === "authenticating" ) {
console . log ( "OAuth required:" , result . authUrl );
} else if ( result . state === "connected" ) {
console . log ( "Connected!" );
} else if ( result . state === "failed" ) {
console . error ( "Connection failed:" , result . error );
}
Returns: Promise<MCPConnectionResult>
Show MCPConnectionResult variants
Connected: Authenticating (OAuth required): {
state : "authenticating" ,
authUrl : string ,
clientId ?: string
}
Failed: {
state : "failed" ,
error : string
}
discoverIfConnected()
Discover server capabilities if connection is in CONNECTED or READY state.
const result = await this . mcp . discoverIfConnected ( "my-server" );
if ( result . success ) {
console . log ( "Discovery complete!" );
const tools = this . mcp . listTools ();
console . log ( "Available tools:" , tools );
} else {
console . error ( "Discovery failed:" , result . error );
}
Returns: Promise<MCPDiscoverResult | undefined>
removeServer()
Remove an MCP server - closes connection if active and removes from storage.
await this . mcp . removeServer ( "my-server" );
Returns: Promise<void>
Listing Resources
Get all available tools from connected MCP servers.
const tools = this . mcp . listTools ();
tools . forEach ( tool => {
console . log ( `[ ${ tool . serverId } ] ${ tool . name } : ${ tool . description } ` );
});
Returns: (Tool & { serverId: string })[]
listPrompts()
Get all available prompts from connected MCP servers.
const prompts = this . mcp . listPrompts ();
for ( const prompt of prompts ) {
console . log ( ` ${ prompt . name } : ${ prompt . description } ` );
}
Returns: (Prompt & { serverId: string })[]
listResources()
Get all available resources from connected MCP servers.
const resources = this . mcp . listResources ();
for ( const resource of resources ) {
console . log ( ` ${ resource . uri } : ${ resource . name } ` );
}
Returns: (Resource & { serverId: string })[]
listResourceTemplates()
Get all available resource templates from connected MCP servers.
const templates = this . mcp . listResourceTemplates ();
Returns: (ResourceTemplate & { serverId: string })[]
listServers()
List all registered MCP servers from storage.
const servers = this . mcp . listServers ();
for ( const server of servers ) {
console . log ( ` ${ server . name } : ${ server . server_url } ` );
}
Returns: MCPServerRow[]
Call a tool on an MCP server.
arguments
Record<string, unknown>
required
Tool arguments
const result = await this . mcp . callTool ({
serverId: "weather-server" ,
name: "get_weather" ,
arguments: { location: "San Francisco" }
});
console . log ( "Result:" , result );
Returns: Promise<CallToolResult>
getPrompt()
Get a prompt from an MCP server.
const prompt = await this . mcp . getPrompt ({
serverId: "my-server" ,
name: "summarize" ,
arguments: { text: "Long text to summarize..." }
});
Returns: Promise<GetPromptResult>
readResource()
Read a resource from an MCP server.
params
ReadResourceParams
required
const resource = await this . mcp . readResource ({
serverId: "my-server" ,
uri: "file:///data.json"
});
Returns: Promise<ReadResourceResult>
AI SDK Integration
Get all MCP tools as AI SDK tool definitions. Use with generateText() or streamText().
import { generateText } from "ai" ;
const tools = this . mcp . getAITools ();
const result = await generateText ({
model: this . env . AI . run ( "@cf/meta/llama-3.3-70b-instruct-fp8-fast" ),
messages: [
{ role: "user" , content: "What's the weather in SF?" }
],
tools
});
Returns: ToolSet
Call await this.mcp.ensureJsonSchema() before using getAITools() if you’re not using await this.mcp.waitForConnections().
Connection Management
waitForConnections()
Wait for all in-flight connection and discovery operations to settle.
Maximum time to wait in milliseconds. 0 returns immediately, undefined waits indefinitely.
// Wait for all connections to complete
await this . mcp . waitForConnections ({ timeout: 10000 });
// Now safe to use getAITools()
const tools = this . mcp . getAITools ();
Returns: Promise<void>
closeConnection()
Close a connection to an MCP server (but keep it in storage).
await this . mcp . closeConnection ( "my-server" );
Returns: Promise<void>
closeAllConnections()
Close all active connections to MCP servers (but keep them in storage).
await this . mcp . closeAllConnections ();
Returns: Promise<void>
OAuth Flow
Configure OAuth callback handling for MCP servers.
config
MCPClientOAuthCallbackConfig
required
URL to redirect to on successful OAuth
URL to redirect to on failed OAuth
customHandler
(result: MCPClientOAuthResult) => Response
Custom handler for OAuth callback
this . mcp . configureOAuthCallback ({
successRedirect: "/dashboard" ,
errorRedirect: "/error"
});
isCallbackRequest()
Check if a request is an OAuth callback request.
async onRequest ( request : Request ) {
if ( this . mcp . isCallbackRequest ( request )) {
const result = await this . mcp . handleCallbackRequest ( request );
if ( result . authSuccess ) {
// OAuth complete, establish connection
await this . mcp . establishConnection ( result . serverId );
return new Response ( "Connected!" );
}
return new Response ( result . authError , { status: 400 });
}
}
Returns: boolean
handleCallbackRequest()
Handle an OAuth callback request.
The OAuth callback request
const result = await this . mcp . handleCallbackRequest ( request );
if ( result . authSuccess ) {
await this . mcp . establishConnection ( result . serverId );
return new Response ( "Success!" );
} else {
return new Response ( result . authError , { status: 400 });
}
Returns: Promise<MCPClientOAuthResult>
establishConnection()
Establish connection in the background after OAuth completion.
await this . mcp . establishConnection ( "my-server" );
Returns: Promise<void>
RPC Servers (Durable Objects)
addRpcMcpServer()
Connect to an MCP server running as a Durable Object.
// In your Agent
await this . mcp . addRpcMcpServer (
"internal-server" ,
this . env . INTERNAL_MCP_SERVER ,
{ props: { config: "value" } }
);
const tools = this . mcp . listTools ();
See Agent class reference for full signature.
Full Example
import { Agent , callable } from "agents" ;
import { generateText } from "ai" ;
class WeatherAgent extends Agent {
async onStart () {
// Register weather MCP server
await this . mcp . registerServer ( "weather" , {
url: "https://weather-mcp.example.com" ,
name: "Weather Server"
});
// Connect and discover
const connected = await this . mcp . connectToServer ( "weather" );
if ( connected . state === "connected" ) {
await this . mcp . discoverIfConnected ( "weather" );
}
// Wait for all connections
await this . mcp . waitForConnections ({ timeout: 5000 });
// List available tools
const tools = this . mcp . listTools ();
console . log ( "Available tools:" , tools . map ( t => t . name ));
}
@ callable ()
async chat ( message : string ) {
const tools = this . mcp . getAITools ();
const result = await generateText ({
model: this . env . AI . run ( "@cf/meta/llama-3.3-70b-instruct-fp8-fast" ),
messages: [
{ role: "user" , content: message }
],
tools ,
maxSteps: 5
});
return result . text ;
}
}
Events
onServerStateChanged
Subscribe to server state changes (registered, connected, removed, etc.).
const unsubscribe = this . mcp . onServerStateChanged (() => {
console . log ( "MCP server state changed!" );
this . broadcastMcpServers ();
});
// Clean up
unsubscribe ();
onObservabilityEvent
Subscribe to observability events from MCP connections.
const unsubscribe = this . mcp . onObservabilityEvent (( event ) => {
console . log ( "MCP event:" , event . type , event . payload );
});