import { n as AgentEmail } from "./context-_sPQqJWv.js";
import {
h as TransportType,
t as MCPClientManager,
u as MCPConnectionState
} from "./client-BZVYeBmf.js";
import { t as Observability } from "./index-CyDpAVHZ.js";
import { n as MessageType } from "./ai-types-U8lYA0o8.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";
import { env } from "cloudflare:workers";
//#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;
};
/**
* 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) => void;
type QueueItem<T = string> = {
id: string;
payload: T;
callback: keyof Agent<unknown>;
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;
}
);
/**
* 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;
instructions: string | null;
capabilities: ServerCapabilities | null;
};
declare function getCurrentAgent<
T extends Agent<unknown, unknown> = Agent<unknown, unknown>
>(): {
agent: T | undefined;
connection: Connection | undefined;
request: Request | undefined;
email: AgentEmail | undefined;
};
/**
* 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 = typeof 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
*/
static options: {
/** Whether the Agent should hibernate when inactive */
hibernate: boolean;
};
/**
* 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);
private _setStateInternal;
/**
* Update the Agent's state
* @param state New state to set
*/
setState(state: State): 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 | "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
* @returns void
*/
replyToEmail(
email: AgentEmail,
options: {
fromName: string;
subject?: string | undefined;
body: string;
contentType?: string;
headers?: Record<string, string>;
}
): 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, 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>>;
/**
* 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";
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>;
/**
* Get all methods marked as callable on this Agent
* @returns A map of method names to their metadata
*/
private _isCallable;
/**
* Connect to a new MCP Server
*
* @param serverName Name of the MCP server
* @param url MCP Server SSE URL
* @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
* @param agentsPrefix agents routing prefix if not using `agents`
* @param options MCP client and transport options
* @returns Server id and state - either "authenticating" with authUrl, or "ready"
* @throws If connection or discovery fails
*/
addMcpServer(
serverName: string,
url: string,
callbackHost?: string,
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
*/
type AgentNamespace<Agentic extends Agent<unknown>> =
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 EmailResolver<Env> = (
email: ForwardableEmailMessage,
env: Env
) => Promise<{
agentName: string;
agentId: string;
} | null>;
/**
* Create a resolver that uses the message-id header to determine the agent to route the email to
* @returns A function that resolves the agent to route the email to
*/
declare function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env>;
/**
* Create a resolver that uses the email address to determine the agent to route the email to
* @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
* @returns A function that resolves the agent to route the email to
*/
declare function createAddressBasedEmailResolver<Env>(
defaultAgentName: string
): EmailResolver<Env>;
/**
* Create a resolver that uses the agentName and agentId to determine the agent to route the email to
* @param agentName The name of the agent to route the email to
* @param agentId The id of the agent to route the email to
* @returns A function that resolves the agent to route the email to
*/
declare function createCatchAllEmailResolver<Env>(
agentName: string,
agentId: string
): EmailResolver<Env>;
type EmailRoutingOptions<Env> = AgentOptions<Env> & {
resolver: EmailResolver<Env>;
};
/**
* 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>(
email: ForwardableEmailMessage,
env: Env,
options: EmailRoutingOptions<Env>
): Promise<void>;
type EmailSendOptions = {
to: string;
subject: string;
body: string;
contentType?: string;
headers?: Record<string, string>;
includeRoutingHeaders?: boolean;
agentName?: string;
agentId?: string;
domain?: string;
};
/**
* 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,
T extends Agent<Env>,
Props extends Record<string, unknown> = Record<string, unknown>
>(
namespace: AgentNamespace<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, id: string);
/**
* Send a chunk of data to the client
* @param chunk The data to send
*/
send(chunk: unknown): void;
/**
* End the stream and send the final chunk (if any)
* @param finalChunk Optional final chunk of data to send
*/
end(finalChunk?: unknown): void;
}
//#endregion
export {
createCatchAllEmailResolver as C,
routeAgentEmail as D,
getCurrentAgent as E,
routeAgentRequest as O,
createAddressBasedEmailResolver as S,
getAgentByName as T,
Schedule as _,
CallableMetadata as a,
WSMessage as b,
EmailResolver as c,
MCPServer as d,
MCPServerMessage as f,
RPCResponse as g,
RPCRequest as h,
AgentOptions as i,
unstable_callable as k,
EmailRoutingOptions as l,
QueueItem as m,
AgentContext as n,
Connection$1 as o,
MCPServersState as p,
AgentNamespace as r,
ConnectionContext as s,
Agent as t,
EmailSendOptions as u,
StateUpdateMessage as v,
createHeaderBasedEmailResolver as w,
callable as x,
StreamingResponse as y
};
//# sourceMappingURL=index-B6XHf8p0.d.ts.map