@agentdeploy/edge-sdk Guide
Complete API reference for the AgentDeploy Edge SDK — a wrapper around the Cloudflare Agents SDK (agents + @cloudflare/ai-chat) with platform billing, telemetry, and gateway integration.
Installation
npm install @agentdeploy/edge-sdk
Peer dependencies (installed automatically by ad init):
{
"agents": "^0.18.0",
"@cloudflare/ai-chat": "^0.9.0",
"ai": "^6.0.0",
"zod": "^3.0.0"
}
createChatAgent()
Creates a chat agent with streaming responses, tool calling, and message persistence. Extends AIChatAgent from @cloudflare/ai-chat.
import { createChatAgent, createHandler } from "@agentdeploy/edge-sdk";
export const MyAgent = createChatAgent({
name: "my-agent", // Agent name (used in URL routing)
systemPrompt: "You are a helpful assistant.", // String or function
model: "openai/gpt-4o-mini", // Model hint (platform may override)
tools: { /* defineTool() results */ }, // Optional
mcpServers: [ /* McpServerConfig */ ], // Optional
maxSteps: 10, // Max tool-call round trips (default: 10)
temperature: 0.7, // Optional
maxTokens: 1000, // Optional
onBeforeChat: async (ctx) => { /* ... */ }, // Optional
onAfterChat: async (ctx, usage) => { /* ... */ }, // Optional
});
export default createHandler(MyAgent);
Dynamic system prompts
export const SupportAgent = createChatAgent({
name: "support",
systemPrompt: async (ctx) => {
const userTime = new Date().toLocaleTimeString("en-US", { timeZone: ctx.region });
return `You are a support agent. Current time: ${userTime}. Deployment: ${ctx.deploymentId}`;
},
});
createAgent()
Creates a general-purpose agent for scheduled tasks, HTTP handlers, and stateful logic. Extends Agent from agents.
import { createAgent, createHandler } from "@agentdeploy/edge-sdk";
export const MonitorAgent = createAgent({
name: "monitor",
// Called once when the agent first starts
onStart() {
this.sql`CREATE TABLE IF NOT EXISTS events (id TEXT, data TEXT)`;
this.scheduleEvery("*/5 * * * *", "healthCheck");
},
// HTTP request handler (non-WebSocket requests)
onRequest(request) {
const url = new URL(request.url);
if (url.pathname === "/status") {
return Response.json({ state: this.state });
}
return new Response("Monitor Agent");
},
// Scheduled task handler
async onSchedule(task) {
if (task.name === "healthCheck") {
// Do work...
this.setState({ lastCheck: new Date().toISOString() });
}
},
// WebSocket handlers
onConnect(connection) { /* ... */ },
onMessage(connection, message) { /* ... */ },
onClose(connection) { /* ... */ },
// Tools callable via this.callTool()
tools: { /* ... */ },
});
export default createHandler(MonitorAgent);
Available this methods inside agent lifecycle
| Method | Description |
|---|---|
this.state | Agent state object (syncs to connected clients) |
this.setState(state) | Update state |
this.env | Environment bindings (secrets) |
this.ctx | DurableObjectState |
this.sql\...`` | SQLite query (embedded in Durable Object) |
this.schedule(when, name, ...args) | Schedule one-time task |
this.scheduleEvery(cron, name, ...args) | Schedule recurring task |
this.getSchedules() | List scheduled tasks |
this.cancelSchedule(id) | Cancel a scheduled task |
this.mcp.connect(server) | Connect MCP server |
this.mcp.getAITools() | Get MCP tools as AI SDK tools |
this.callTool(name, input) | Call a defined tool |
defineTool()
Typed tool factory with Zod input validation and telemetry.
import { defineTool } from "@agentdeploy/edge-sdk";
import { z } from "zod";
const lookupUser = defineTool({
description: "Look up a user by email",
inputSchema: z.object({
email: z.string().email(),
includeOrders: z.boolean().default(false),
}),
needsApproval: false, // Set true to require buyer approval before executing
execute: async ({ email, includeOrders }, ctx) => {
// ctx.agent — the calling agent instance
// ctx.env — environment bindings
// ctx.deploymentId — deployment ID
// ctx.model — model string
// ctx.gatewayBaseUrl — gateway URL
const res = await fetch(`https://api.example.com/users?email=${email}`);
const user = await res.json();
if (includeOrders) {
const orders = await fetch(`https://api.example.com/users/${user.id}/orders`);
user.orders = await orders.json();
}
return user;
},
});
useGateway()
Returns an AI SDK model instance that routes through the AgentDeploy gateway for billing and token metering.
import { useGateway } from "@agentdeploy/edge-sdk";
import { generateText, streamText } from "ai";
// One-shot generation
const model = useGateway();
const result = await generateText({
model,
system: "You are a helpful assistant.",
prompt: "Explain quantum computing in one sentence.",
});
console.log(result.text);
// Specify a model preference (platform may override based on deployment config)
const model2 = useGateway("anthropic/claude-3-sonnet");
// Streaming
const model3 = useGateway();
const result3 = streamText({
model: model3,
prompt: "Write a haiku about edge computing.",
});
for await (const chunk of result3.textStream) {
process.stdout.write(chunk);
}
The gateway:
- Uses
AD_GATEWAY_BASE_URL(injected by platform) - Sends
X-AD-Deploymentheader for authentication - Meters all token usage automatically
- Enforces buyer plan limits
Note: createChatAgent() calls useGateway() internally — you only need it for direct LLM access in scheduled agents or custom tools.
useSecrets()
Typed access to deployment secrets with descriptive error messages.
import { useSecrets, hasSecret, getSecret } from "@agentdeploy/edge-sdk";
interface MySecrets {
STRIPE_API_KEY: string;
DATABASE_URL: string;
OPTIONAL_WEBHOOK?: string;
}
// Proxy-based typed access
const secrets = useSecrets<MySecrets>(ctx.env);
console.log(secrets.STRIPE_API_KEY); // Throws if not configured
// Check if secret exists
if (hasSecret(ctx.env, "OPTIONAL_WEBHOOK")) {
// Use optional secret
}
// Get secret with fallback
const webhook = getSecret(ctx.env, "OPTIONAL_WEBHOOK", "https://default.com/webhook");
MCP integration
Connect external MCP servers for additional tools:
import { createChatAgent, createHandler } from "@agentdeploy/edge-sdk";
export const ResearchAgent = createChatAgent({
name: "research",
systemPrompt: "You are a research assistant.",
mcpServers: [
{
name: "web-search",
transport: {
type: "sse",
url: "https://mcp.serper.dev/sse",
headers: { "X-API-KEY": "${SERPER_API_KEY}" },
},
},
{
name: "github",
transport: {
type: "stdio",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
},
},
],
maxSteps: 15,
});
MCP tools are merged with your locally-defined tools and passed to the LLM. All tool calls (MCP and local) are logged via telemetry.
createHandler()
Generates the Worker entry point with agent routing.
import { createHandler } from "@agentdeploy/edge-sdk";
// Single agent
export default createHandler(SupportAgent);
// Multiple agents
export default createHandler(SupportAgent, SalesAgent, BillingAgent);
The handler:
- Routes WebSocket requests via
routeAgentRequest()to the correct agent Durable Object - Serves
GET /health— returns{"status":"ok","deploymentId":"...","agents":[...]} - Serves
GET /info— returns agent URLs - Returns 404 for unknown routes
Type exports
import type {
AgentConfig,
ChatAgentConfig,
AgentDeployTool,
ToolContext,
AgentContext,
AgentDeployAgent,
AgentDeployChatAgent,
AgentSchedule,
AgentHandler,
McpServerConfig,
} from "@agentdeploy/edge-sdk";
Ambient constants
The platform injects these as global constants at deploy time:
declare global {
const AD_DEPLOYMENT_ID: string;
const AD_USER_ID: string;
const AD_TEMPLATE_ID: number;
const AD_MODEL: string;
const AD_REGION: string;
const AD_GATEWAY_BASE_URL: string;
}
The SDK uses these internally — you typically don't reference them directly.
Example agents
See the agent-deploy-edge-starter repo for complete, real-world examples:
- Customer Support — Chat agent with KB search, ticket escalation, order lookup
- Commerce Agent — Inventory, pricing tiers, order creation
- DevOps Monitor — Scheduled health checks, SQLite storage, dashboard
- Scheduled Reports — Cron tasks, LLM summarization, email delivery
- MCP Research — External MCP servers, content analysis
- Multi-Agent Router — Support/Sales/Billing routing in one worker