agents
Version:
A home for your AI agents
1,049 lines (1,047 loc) • 32.5 kB
TypeScript
import { n as AgentEmail } from "./internal_context-CEu5ji80.js";
import {
l as createHeaderBasedEmailResolver,
r as EmailResolver
} from "./email-8ljcpvwV.js";
import {
d as MCPConnectionState,
g as TransportType,
t as MCPClientManager
} from "./client-DV1CZKqa.js";
import {
_ as WorkflowPage,
g as WorkflowInfo,
h as WorkflowEventPayload,
l as WorkflowCallback,
s as RunWorkflowOptions,
y as WorkflowQueryCriteria
} from "./workflow-types-Z_Oem1FJ.js";
import { t as Observability } from "./index-N6791tVt.js";
import { t as MessageType } from "./types-DSSHBW6w.js";
import {
Connection,
Connection as Connection$1,
ConnectionContext,
PartyServerOptions,
Server,
WSMessage
} from "partyserver";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import {
Prompt,
Resource,
ServerCapabilities,
Tool
} from "@modelcontextprotocol/sdk/types.js";
//#region src/index.d.ts
/**
* RPC request message from client
*/
type RPCRequest = {
type: "rpc";
id: string;
method: string;
args: unknown[];
};
/**
* State update message from client
*/
type StateUpdateMessage = {
type: MessageType.CF_AGENT_STATE;
state: unknown;
};
/**
* RPC response message to client
*/
type RPCResponse = {
type: MessageType.RPC;
id: string;
} & (
| {
success: true;
result: unknown;
done?: false;
}
| {
success: true;
result: unknown;
done: true;
}
| {
success: false;
error: string;
}
);
/**
* Metadata for a callable method
*/
type CallableMetadata = {
/** Optional description of what the method does */ description?: string; /** Whether the method supports streaming responses */
streaming?: boolean;
};
/**
* Error class for SQL execution failures, containing the query that failed
*/
declare class SqlError extends Error {
/** The SQL query that failed */
readonly query: string;
constructor(query: string, cause: unknown);
}
/**
* Decorator that marks a method as callable by clients
* @param metadata Optional metadata about the callable method
*/
declare function callable(
metadata?: CallableMetadata
): <This, Args extends unknown[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext
) => (this: This, ...args: Args) => Return;
/**
* Decorator that marks a method as callable by clients
* @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
* @param metadata Optional metadata about the callable method
*/
declare const unstable_callable: (
metadata?: CallableMetadata
) => <This, Args extends unknown[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext
) => (this: This, ...args: Args) => Return;
type QueueItem<T = string> = {
id: string;
payload: T;
callback: keyof Agent<Cloudflare.Env>;
created_at: number;
};
/**
* Represents a scheduled task within an Agent
* @template T Type of the payload data
*/
type Schedule<T = string> = {
/** Unique identifier for the schedule */ id: string; /** Name of the method to be called */
callback: string; /** Data to be passed to the callback */
payload: T;
} & (
| {
/** Type of schedule for one-time execution at a specific time */ type: "scheduled"; /** Timestamp when the task should execute */
time: number;
}
| {
/** Type of schedule for delayed execution */ type: "delayed"; /** Timestamp when the task should execute */
time: number; /** Number of seconds to delay execution */
delayInSeconds: number;
}
| {
/** Type of schedule for recurring execution based on cron expression */ type: "cron"; /** Timestamp for the next execution */
time: number; /** Cron expression defining the schedule */
cron: string;
}
| {
/** Type of schedule for recurring execution at fixed intervals */ type: "interval"; /** Timestamp for the next execution */
time: number; /** Number of seconds between executions */
intervalSeconds: number;
}
);
/**
* MCP Server state update message from server -> Client
*/
type MCPServerMessage = {
type: MessageType.CF_AGENT_MCP_SERVERS;
mcp: MCPServersState;
};
type MCPServersState = {
servers: {
[id: string]: MCPServer;
};
tools: (Tool & {
serverId: string;
})[];
prompts: (Prompt & {
serverId: string;
})[];
resources: (Resource & {
serverId: string;
})[];
};
type MCPServer = {
name: string;
server_url: string;
auth_url: string | null;
state: MCPConnectionState;
error: string | null;
instructions: string | null;
capabilities: ServerCapabilities | null;
};
/**
* Options for adding an MCP server
*/
type AddMcpServerOptions = {
/** OAuth callback host (auto-derived from request if omitted) */ callbackHost?: string; /** Agents routing prefix (default: "agents") */
agentsPrefix?: string; /** MCP client options */
client?: ConstructorParameters<typeof Client>[1]; /** Transport options */
transport?: {
/** Custom headers for authentication (e.g., bearer tokens, CF Access) */ headers?: HeadersInit; /** Transport type: "sse", "streamable-http", or "auto" (default) */
type?: TransportType;
};
};
/**
* Default options for Agent configuration.
* Child classes can override specific options without spreading.
*/
declare const DEFAULT_AGENT_STATIC_OPTIONS: {
/** Whether the Agent should hibernate when inactive */ hibernate: boolean; /** Whether to send identity (name, agent) to clients on connect */
sendIdentityOnConnect: boolean;
/**
* Timeout in seconds before a running interval schedule is considered "hung"
* and force-reset. Increase this if you have callbacks that legitimately
* take longer than 30 seconds.
*/
hungScheduleTimeoutSeconds: number;
};
type ResolvedAgentOptions = typeof DEFAULT_AGENT_STATIC_OPTIONS;
/**
* Configuration options for the Agent.
* Override in subclasses via `static options`.
* All fields are optional - defaults are applied at runtime.
* Note: `hibernate` defaults to `true` if not specified.
*/
type AgentStaticOptions = Partial<ResolvedAgentOptions>;
declare function getCurrentAgent<
T extends Agent<Cloudflare.Env> = Agent<Cloudflare.Env>
>(): {
agent: T | undefined;
connection: Connection$1 | undefined;
request: Request | undefined;
email: AgentEmail | undefined;
};
/**
* Extract string keys from Env where the value is a Workflow binding.
*/
type WorkflowBinding<E> = {
[K in keyof E & string]: E[K] extends Workflow ? K : never;
}[keyof E & string];
/**
* Type for workflow name parameter.
* When Env has typed Workflow bindings, provides autocomplete for those keys.
* Also accepts any string for dynamic use cases and compatibility.
* The `string & {}` trick preserves autocomplete while allowing any string.
*/
type WorkflowName<E> = WorkflowBinding<E> | (string & {});
/**
* Base class for creating Agent implementations
* @template Env Environment type containing bindings
* @template State State type to store within the Agent
*/
declare class Agent<
Env extends Cloudflare.Env = Cloudflare.Env,
State = unknown,
Props extends Record<string, unknown> = Record<string, unknown>
> extends Server<Env, Props> {
private _state;
private _disposables;
private _destroyed;
private _ParentClass;
readonly mcp: MCPClientManager;
/**
* Initial state for the Agent
* Override to provide default state values
*/
initialState: State;
/**
* Current state of the Agent
*/
get state(): State;
/**
* Agent configuration options.
* Override in subclasses - only specify what you want to change.
* @example
* class SecureAgent extends Agent {
* static options = { sendIdentityOnConnect: false };
* }
*/
static options: AgentStaticOptions;
/**
* Resolved options (merges defaults with subclass overrides)
*/
private get _resolvedOptions();
/**
* The observability implementation to use for the Agent
*/
observability?: Observability;
/**
* Execute SQL queries against the Agent's database
* @template T Type of the returned rows
* @param strings SQL query template strings
* @param values Values to be inserted into the query
* @returns Array of query results
*/
sql<T = Record<string, string | number | boolean | null>>(
strings: TemplateStringsArray,
...values: (string | number | boolean | null)[]
): T[];
constructor(ctx: AgentContext, env: Env);
/**
* Check for workflows referencing unknown bindings and warn with migration suggestion.
*/
private _checkOrphanedWorkflows;
private _setStateInternal;
/**
* Update the Agent's state
* @param state New state to set
*/
setState(state: State): void;
/**
* Called before the Agent's state is persisted and broadcast.
* Override to validate or reject an update by throwing an error.
*
* IMPORTANT: This hook must be synchronous.
*/
validateStateChange(nextState: State, source: Connection$1 | "server"): void;
/**
* Called when the Agent's state is updated
* @param state Updated state
* @param source Source of the state update ("server" or a client connection)
*/
onStateUpdate(
state: State | undefined,
source: Connection$1 | "server"
): void;
/**
* Called when the Agent receives an email via routeAgentEmail()
* Override this method to handle incoming emails
* @param email Email message to process
*/
_onEmail(email: AgentEmail): Promise<void>;
/**
* Reply to an email
* @param email The email to reply to
* @param options Options for the reply
* @param options.secret Secret for signing agent headers (enables secure reply routing).
* Required if the email was routed via createSecureReplyEmailResolver.
* Pass explicit `null` to opt-out of signing (not recommended for secure routing).
* @returns void
*/
replyToEmail(
email: AgentEmail,
options: {
fromName: string;
subject?: string | undefined;
body: string;
contentType?: string;
headers?: Record<string, string>;
secret?: string | null;
}
): Promise<void>;
private _tryCatch;
/**
* Automatically wrap custom methods with agent context
* This ensures getCurrentAgent() works in all custom methods without decorators
*/
private _autoWrapCustomMethods;
onError(connection: Connection$1, error: unknown): void | Promise<void>;
onError(error: unknown): void | Promise<void>;
/**
* Render content (not implemented in base class)
*/
render(): void;
/**
* Queue a task to be executed in the future
* @param payload Payload to pass to the callback
* @param callback Name of the method to call
* @returns The ID of the queued task
*/
queue<T = unknown>(callback: keyof this, payload: T): Promise<string>;
private _flushingQueue;
private _flushQueue;
/**
* Dequeue a task by ID
* @param id ID of the task to dequeue
*/
dequeue(id: string): Promise<void>;
/**
* Dequeue all tasks
*/
dequeueAll(): Promise<void>;
/**
* Dequeue all tasks by callback
* @param callback Name of the callback to dequeue
*/
dequeueAllByCallback(callback: string): Promise<void>;
/**
* Get a queued task by ID
* @param id ID of the task to get
* @returns The task or undefined if not found
*/
getQueue(id: string): Promise<QueueItem<string> | undefined>;
/**
* Get all queues by key and value
* @param key Key to filter by
* @param value Value to filter by
* @returns Array of matching QueueItem objects
*/
getQueues(key: string, value: string): Promise<QueueItem<string>[]>;
/**
* Schedule a task to be executed in the future
* @template T Type of the payload data
* @param when When to execute the task (Date, seconds delay, or cron expression)
* @param callback Name of the method to call
* @param payload Data to pass to the callback
* @returns Schedule object representing the scheduled task
*/
schedule<T = string>(
when: Date | string | number,
callback: keyof this,
payload?: T
): Promise<Schedule<T>>;
/**
* Schedule a task to run repeatedly at a fixed interval
* @template T Type of the payload data
* @param intervalSeconds Number of seconds between executions
* @param callback Name of the method to call
* @param payload Data to pass to the callback
* @returns Schedule object representing the scheduled task
*/
scheduleEvery<T = string>(
intervalSeconds: number,
callback: keyof this,
payload?: T
): Promise<Schedule<T>>;
/**
* Get a scheduled task by ID
* @template T Type of the payload data
* @param id ID of the scheduled task
* @returns The Schedule object or undefined if not found
*/
getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined>;
/**
* Get scheduled tasks matching the given criteria
* @template T Type of the payload data
* @param criteria Criteria to filter schedules
* @returns Array of matching Schedule objects
*/
getSchedules<T = string>(criteria?: {
id?: string;
type?: "scheduled" | "delayed" | "cron" | "interval";
timeRange?: {
start?: Date;
end?: Date;
};
}): Schedule<T>[];
/**
* Cancel a scheduled task
* @param id ID of the task to cancel
* @returns true if the task was cancelled, false if the task was not found
*/
cancelSchedule(id: string): Promise<boolean>;
private _scheduleNextAlarm;
/**
* Method called when an alarm fires.
* Executes any scheduled tasks that are due.
*
* @remarks
* To schedule a task, please use the `this.schedule` method instead.
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
*/
readonly alarm: () => Promise<void>;
/**
* Destroy the Agent, removing all state and scheduled tasks
*/
destroy(): Promise<void>;
/**
* Check if a method is callable
* @param method The method name to check
* @returns True if the method is marked as callable
*/
private _isCallable;
/**
* Get all methods marked as callable on this Agent
* @returns A map of method names to their metadata
*/
getCallableMethods(): Map<string, CallableMetadata>;
/**
* Start a workflow and track it in this Agent's database.
* Automatically injects agent identity into the workflow params.
*
* @template P - Type of params to pass to the workflow
* @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
* @param params - Params to pass to the workflow
* @param options - Optional workflow options
* @returns The workflow instance ID
*
* @example
* ```typescript
* const workflowId = await this.runWorkflow(
* 'MY_WORKFLOW',
* { taskId: '123', data: 'process this' }
* );
* ```
*/
runWorkflow<P = unknown>(
workflowName: WorkflowName<Env>,
params: P,
options?: RunWorkflowOptions
): Promise<string>;
/**
* Send an event to a running workflow.
* The workflow can wait for this event using step.waitForEvent().
*
* @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
* @param workflowId - ID of the workflow instance
* @param event - Event to send
*
* @example
* ```typescript
* await this.sendWorkflowEvent(
* 'MY_WORKFLOW',
* workflowId,
* { type: 'approval', payload: { approved: true } }
* );
* ```
*/
sendWorkflowEvent(
workflowName: WorkflowName<Env>,
workflowId: string,
event: WorkflowEventPayload
): Promise<void>;
/**
* Approve a waiting workflow.
* Sends an approval event to the workflow that can be received by waitForApproval().
*
* @param workflowId - ID of the workflow to approve
* @param data - Optional approval data (reason, metadata)
*
* @example
* ```typescript
* await this.approveWorkflow(workflowId, {
* reason: 'Approved by admin',
* metadata: { approvedBy: userId }
* });
* ```
*/
approveWorkflow(
workflowId: string,
data?: {
reason?: string;
metadata?: Record<string, unknown>;
}
): Promise<void>;
/**
* Reject a waiting workflow.
* Sends a rejection event to the workflow that will cause waitForApproval() to throw.
*
* @param workflowId - ID of the workflow to reject
* @param data - Optional rejection data (reason)
*
* @example
* ```typescript
* await this.rejectWorkflow(workflowId, {
* reason: 'Request denied by admin'
* });
* ```
*/
rejectWorkflow(
workflowId: string,
data?: {
reason?: string;
}
): Promise<void>;
/**
* Terminate a running workflow.
* This immediately stops the workflow and sets its status to "terminated".
*
* @param workflowId - ID of the workflow to terminate (must be tracked via runWorkflow)
* @throws Error if workflow not found in tracking table
* @throws Error if workflow binding not found in environment
* @throws Error if workflow is already completed/errored/terminated (from Cloudflare)
*
* @note `terminate()` is not yet supported in local development (wrangler dev).
* It will throw an error locally but works when deployed to Cloudflare.
*
* @example
* ```typescript
* await this.terminateWorkflow(workflowId);
* ```
*/
terminateWorkflow(workflowId: string): Promise<void>;
/**
* Pause a running workflow.
* The workflow can be resumed later with resumeWorkflow().
*
* @param workflowId - ID of the workflow to pause (must be tracked via runWorkflow)
* @throws Error if workflow not found in tracking table
* @throws Error if workflow binding not found in environment
* @throws Error if workflow is not running (from Cloudflare)
*
* @note `pause()` is not yet supported in local development (wrangler dev).
* It will throw an error locally but works when deployed to Cloudflare.
*
* @example
* ```typescript
* await this.pauseWorkflow(workflowId);
* ```
*/
pauseWorkflow(workflowId: string): Promise<void>;
/**
* Resume a paused workflow.
*
* @param workflowId - ID of the workflow to resume (must be tracked via runWorkflow)
* @throws Error if workflow not found in tracking table
* @throws Error if workflow binding not found in environment
* @throws Error if workflow is not paused (from Cloudflare)
*
* @note `resume()` is not yet supported in local development (wrangler dev).
* It will throw an error locally but works when deployed to Cloudflare.
*
* @example
* ```typescript
* await this.resumeWorkflow(workflowId);
* ```
*/
resumeWorkflow(workflowId: string): Promise<void>;
/**
* Restart a workflow instance.
* This re-runs the workflow from the beginning with the same ID.
*
* @param workflowId - ID of the workflow to restart (must be tracked via runWorkflow)
* @param options - Optional settings
* @param options.resetTracking - If true (default), resets created_at and clears error fields.
* If false, preserves original timestamps.
* @throws Error if workflow not found in tracking table
* @throws Error if workflow binding not found in environment
*
* @note `restart()` is not yet supported in local development (wrangler dev).
* It will throw an error locally but works when deployed to Cloudflare.
*
* @example
* ```typescript
* // Reset tracking (default)
* await this.restartWorkflow(workflowId);
*
* // Preserve original timestamps
* await this.restartWorkflow(workflowId, { resetTracking: false });
* ```
*/
restartWorkflow(
workflowId: string,
options?: {
resetTracking?: boolean;
}
): Promise<void>;
/**
* Find a workflow binding by its name.
*/
private _findWorkflowBindingByName;
/**
* Get all workflow binding names from the environment.
*/
private _getWorkflowBindingNames;
/**
* Get the status of a workflow and update the tracking record.
*
* @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
* @param workflowId - ID of the workflow instance
* @returns The workflow status
*/
getWorkflowStatus(
workflowName: WorkflowName<Env>,
workflowId: string
): Promise<InstanceStatus>;
/**
* Get a tracked workflow by ID.
*
* @param workflowId - Workflow instance ID
* @returns Workflow info or undefined if not found
*/
getWorkflow(workflowId: string): WorkflowInfo | undefined;
/**
* Query tracked workflows with cursor-based pagination.
*
* @param criteria - Query criteria including optional cursor for pagination
* @returns WorkflowPage with workflows, total count, and next cursor
*
* @example
* ```typescript
* // First page
* const page1 = this.getWorkflows({ status: 'running', limit: 20 });
*
* // Next page
* if (page1.nextCursor) {
* const page2 = this.getWorkflows({
* status: 'running',
* limit: 20,
* cursor: page1.nextCursor
* });
* }
* ```
*/
getWorkflows(criteria?: WorkflowQueryCriteria): WorkflowPage;
/**
* Count workflows matching criteria (for pagination total).
*/
private _countWorkflows;
/**
* Encode a cursor from workflow info for pagination.
* Stores createdAt as Unix timestamp in seconds (matching DB storage).
*/
private _encodeCursor;
/**
* Decode a pagination cursor.
* Returns createdAt as Unix timestamp in seconds (matching DB storage).
*/
private _decodeCursor;
/**
* Delete a workflow tracking record.
*
* @param workflowId - ID of the workflow to delete
* @returns true if a record was deleted, false if not found
*/
deleteWorkflow(workflowId: string): boolean;
/**
* Delete workflow tracking records matching criteria.
* Useful for cleaning up old completed/errored workflows.
*
* @param criteria - Criteria for which workflows to delete
* @returns Number of records matching criteria (expected deleted count)
*
* @example
* ```typescript
* // Delete all completed workflows created more than 7 days ago
* const deleted = this.deleteWorkflows({
* status: 'complete',
* createdBefore: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
* });
*
* // Delete all errored and terminated workflows
* const deleted = this.deleteWorkflows({
* status: ['errored', 'terminated']
* });
* ```
*/
deleteWorkflows(
criteria?: Omit<WorkflowQueryCriteria, "limit" | "orderBy"> & {
createdBefore?: Date;
}
): number;
/**
* Migrate workflow tracking records from an old binding name to a new one.
* Use this after renaming a workflow binding in wrangler.toml.
*
* @param oldName - Previous workflow binding name
* @param newName - New workflow binding name
* @returns Number of records migrated
*
* @example
* ```typescript
* // After renaming OLD_WORKFLOW to NEW_WORKFLOW in wrangler.toml
* async onStart() {
* const migrated = this.migrateWorkflowBinding('OLD_WORKFLOW', 'NEW_WORKFLOW');
* }
* ```
*/
migrateWorkflowBinding(oldName: string, newName: string): number;
/**
* Update workflow tracking record from InstanceStatus
*/
private _updateWorkflowTracking;
/**
* Convert a database row to WorkflowInfo
*/
private _rowToWorkflowInfo;
/**
* Find the binding name for this Agent's namespace by matching class name.
* Returns undefined if no match found - use options.agentBinding as fallback.
*/
private _findAgentBindingName;
/**
* Handle a callback from a workflow.
* Called when the Agent receives a callback at /_workflow/callback.
* Override this to handle all callback types in one place.
*
* @param callback - The callback payload
*/
onWorkflowCallback(callback: WorkflowCallback): Promise<void>;
/**
* Called when a workflow reports progress.
* Override to handle progress updates.
*
* @param workflowName - Workflow binding name
* @param workflowId - ID of the workflow
* @param progress - Typed progress data (default: DefaultProgress)
*/
onWorkflowProgress(
_workflowName: string,
_workflowId: string,
_progress: unknown
): Promise<void>;
/**
* Called when a workflow completes successfully.
* Override to handle completion.
*
* @param workflowName - Workflow binding name
* @param workflowId - ID of the workflow
* @param result - Optional result data
*/
onWorkflowComplete(
_workflowName: string,
_workflowId: string,
_result?: unknown
): Promise<void>;
/**
* Called when a workflow encounters an error.
* Override to handle errors.
*
* @param workflowName - Workflow binding name
* @param workflowId - ID of the workflow
* @param error - Error message
*/
onWorkflowError(
_workflowName: string,
_workflowId: string,
_error: string
): Promise<void>;
/**
* Called when a workflow sends a custom event.
* Override to handle custom events.
*
* @param workflowName - Workflow binding name
* @param workflowId - ID of the workflow
* @param event - Custom event payload
*/
onWorkflowEvent(
_workflowName: string,
_workflowId: string,
_event: unknown
): Promise<void>;
/**
* Handle a workflow callback via RPC.
* @internal - Called by AgentWorkflow, do not call directly
*/
_workflow_handleCallback(callback: WorkflowCallback): Promise<void>;
/**
* Broadcast a message to all connected clients via RPC.
* @internal - Called by AgentWorkflow, do not call directly
*/
_workflow_broadcast(message: unknown): void;
/**
* Update agent state via RPC.
* @internal - Called by AgentWorkflow, do not call directly
*/
_workflow_updateState(
action: "set" | "merge" | "reset",
state?: unknown
): void;
/**
* Connect to a new MCP Server
*
* @example
* // Simple usage
* await this.addMcpServer("github", "https://mcp.github.com");
*
* @example
* // With options (preferred for custom headers, transport, etc.)
* await this.addMcpServer("github", "https://mcp.github.com", {
* transport: { headers: { "Authorization": "Bearer ..." } }
* });
*
* @example
* // Legacy 5-parameter signature (still supported)
* await this.addMcpServer("github", url, callbackHost, agentsPrefix, options);
*
* @param serverName Name of the MCP server
* @param url MCP Server URL
* @param callbackHostOrOptions Options object, or callback host string (legacy)
* @param agentsPrefix agents routing prefix if not using `agents` (legacy)
* @param options MCP client and transport options (legacy)
* @returns Server id and state - either "authenticating" with authUrl, or "ready"
* @throws If connection or discovery fails
*/
addMcpServer(
serverName: string,
url: string,
callbackHostOrOptions?: string | AddMcpServerOptions,
agentsPrefix?: string,
options?: {
client?: ConstructorParameters<typeof Client>[1];
transport?: {
headers?: HeadersInit;
type?: TransportType;
};
}
): Promise<
| {
id: string;
state: typeof MCPConnectionState.AUTHENTICATING;
authUrl: string;
}
| {
id: string;
state: typeof MCPConnectionState.READY;
authUrl?: undefined;
}
>;
removeMcpServer(id: string): Promise<void>;
getMcpServers(): MCPServersState;
private broadcastMcpServers;
/**
* Handle MCP OAuth callback request if it's an OAuth callback.
*
* This method encapsulates the entire OAuth callback flow:
* 1. Checks if the request is an MCP OAuth callback
* 2. Processes the OAuth code exchange
* 3. Establishes the connection if successful
* 4. Broadcasts MCP server state updates
* 5. Returns the appropriate HTTP response
*
* @param request The incoming HTTP request
* @returns Response if this was an OAuth callback, null otherwise
*/
private handleMcpOAuthCallback;
/**
* Handle OAuth callback response using MCPClientManager configuration
* @param result OAuth callback result
* @param request The original request (needed for base URL)
* @returns Response for the OAuth callback
*/
private handleOAuthCallbackResponse;
}
/**
* Namespace for creating Agent instances
* @template Agentic Type of the Agent class
* @deprecated Use DurableObjectNamespace instead
*/
type AgentNamespace<Agentic extends Agent<Cloudflare.Env>> =
DurableObjectNamespace<Agentic>;
/**
* Agent's durable context
*/
type AgentContext = DurableObjectState;
/**
* Configuration options for Agent routing
*/
type AgentOptions<Env> = PartyServerOptions<Env> & {
/**
* Whether to enable CORS for the Agent
*/
cors?: boolean | HeadersInit | undefined;
};
/**
* Route a request to the appropriate Agent
* @param request Request to route
* @param env Environment containing Agent bindings
* @param options Routing options
* @returns Response from the Agent or undefined if no route matched
*/
declare function routeAgentRequest<Env>(
request: Request,
env: Env,
options?: AgentOptions<Env>
): Promise<Response | null>;
type EmailRoutingOptions<Env> = AgentOptions<Env> & {
resolver: EmailResolver<Env>;
/**
* Callback invoked when no routing information is found for an email.
* Use this to reject the email or perform custom handling.
* If not provided, a warning is logged and the email is dropped.
*/
onNoRoute?: (email: ForwardableEmailMessage) => void | Promise<void>;
};
/**
* Route an email to the appropriate Agent
* @param email The email to route
* @param env The environment containing the Agent bindings
* @param options The options for routing the email
* @returns A promise that resolves when the email has been routed
*/
declare function routeAgentEmail<Env extends Cloudflare.Env = Cloudflare.Env>(
email: ForwardableEmailMessage,
env: Env,
options: EmailRoutingOptions<Env>
): Promise<void>;
/**
* Get or create an Agent by name
* @template Env Environment type containing bindings
* @template T Type of the Agent class
* @param namespace Agent namespace
* @param name Name of the Agent instance
* @param options Options for Agent creation
* @returns Promise resolving to an Agent instance stub
*/
declare function getAgentByName<
Env extends Cloudflare.Env = Cloudflare.Env,
T extends Agent<Env> = Agent<Env>,
Props extends Record<string, unknown> = Record<string, unknown>
>(
namespace: DurableObjectNamespace<T>,
name: string,
options?: {
jurisdiction?: DurableObjectJurisdiction;
locationHint?: DurableObjectLocationHint;
props?: Props;
}
): Promise<DurableObjectStub<T>>;
/**
* A wrapper for streaming responses in callable methods
*/
declare class StreamingResponse {
private _connection;
private _id;
private _closed;
constructor(connection: Connection$1, id: string);
/**
* Whether the stream has been closed (via end() or error())
*/
get isClosed(): boolean;
/**
* Send a chunk of data to the client
* @param chunk The data to send
* @returns false if stream is already closed (no-op), true if sent
*/
send(chunk: unknown): boolean;
/**
* End the stream and send the final chunk (if any)
* @param finalChunk Optional final chunk of data to send
* @returns false if stream is already closed (no-op), true if sent
*/
end(finalChunk?: unknown): boolean;
/**
* Send an error to the client and close the stream
* @param message Error message to send
* @returns false if stream is already closed (no-op), true if sent
*/
error(message: string): boolean;
}
//#endregion
export {
AddMcpServerOptions,
Agent,
AgentContext,
AgentNamespace,
AgentOptions,
AgentStaticOptions,
CallableMetadata,
type Connection,
type ConnectionContext,
DEFAULT_AGENT_STATIC_OPTIONS,
EmailRoutingOptions,
MCPServer,
MCPServerMessage,
MCPServersState,
QueueItem,
RPCRequest,
RPCResponse,
Schedule,
SqlError,
StateUpdateMessage,
StreamingResponse,
type TransportType,
type WSMessage,
callable,
createHeaderBasedEmailResolver,
getAgentByName,
getCurrentAgent,
routeAgentEmail,
routeAgentRequest,
unstable_callable
};
//# sourceMappingURL=index.d.ts.map