Share via


@microsoft/agents-hosting package

Classes

ActivityHandler

Handles incoming activities from channels and dispatches them to the appropriate handlers.

AdaptiveCardsActions

A class to handle Adaptive Card actions such as executing actions, submitting actions, and performing searches.

AgentApplication

Main application class for handling agent conversations and routing.

Example

const app = new AgentApplication<MyState>({
  storage: new MemoryStorage(),
  adapter: myAdapter
});

app.onMessage('hello', async (context, state) => {
  await context.sendActivity('Hello there!');
});

await app.run(turnContext);
AgentApplicationBuilder

Builder class for creating and configuring AgentApplication instances.

AgentClient

Client for communicating with other agents through HTTP requests. Manages configuration, authentication, and activity exchange with target agents.

AgentExtension

Represents an extension that adds channel-specific routing functionality to an agent application. This class allows you to register routes that are only active for a specific channel.

AgentState

Manages the state of an Agent across turns in a conversation.

AgentStatePropertyAccessor

Provides typed access to an Agent state property with automatic state loading and persistence management.

Example

Basic Usage

// Create a property accessor
const userProfile = userState.createProperty<UserProfile>("userProfile");

// Get with default value
const profile = await userProfile.get(context, {
  name: "",
  preferences: { theme: "light", language: "en" }
});

// Modify the profile
profile.preferences.theme = "dark";

// Save the changes
await userProfile.set(context, profile);
await userState.saveChanges(context); // Persist to storage

Example

Working with Primitive Types

const counterProperty = userState.createProperty<number>("counter");

// Increment counter
const currentCount = await counterProperty.get(context, 0);
await counterProperty.set(context, currentCount + 1);
await userState.saveChanges(context);

Example

Conditional Logic

const settingsProperty = userState.createProperty<Settings>("settings");

// Check if property exists
const settings = await settingsProperty.get(context);
if (settings === undefined) {
  // Property doesn't exist, initialize with defaults
  await settingsProperty.set(context, getDefaultSettings());
}

Example

Custom Storage Keys

// Store state with a custom key for multi-tenant scenarios
const customKey = { key: `tenant_${tenantId}` };
const tenantData = await dataProperty.get(context, defaultData, customKey);
await dataProperty.set(context, updatedData, customKey);

Important Notes

  • Thread Safety: This class is not thread-safe. Ensure proper synchronization in concurrent scenarios.
  • Memory Usage: State objects are kept in memory until the context is disposed.
  • Persistence: Always call state.saveChanges(context) to persist changes to storage.
  • Deep Cloning: Default values are deep cloned using JSON serialization, which may not work with complex objects containing functions or circular references.

See createProperty for creating property accessors See StatePropertyAccessor for the interface definition

AttachmentDownloader

A utility class for downloading input files from activity attachments.

Authorization

Class responsible for managing authorization and OAuth flows. Handles multiple OAuth providers and manages the complete authentication lifecycle.

Example

const auth = new Authorization(storage, {
  'microsoft': {
    name: 'Microsoft',
    title: 'Sign in with Microsoft',
    text: 'Please sign in'
  }
});

auth.onSignInSuccess(async (context, state) => {
  await context.sendActivity('Welcome! You are now signed in.');
});
BaseAdapter

Abstract base class for all adapters in the Agents framework.

CardFactory

Factory class for creating various types of cards.

ClaimsIdentity

Represents an identity with a collection of claims.

CloudAdapter

Adapter for handling agent interactions with various channels through cloud-based services.

ConnectorClient

ConnectorClient is a client for interacting with the Microsoft Connector API.

ConsoleTranscriptLogger

A transcript logger that logs activities to the console.

ConversationState

Manages the state of a conversation.

FileStorage

A file-based storage implementation that persists data to the local filesystem.

Example

const storage = new FileStorage('./data');

// Write some data
await storage.write({
  'user123': { name: 'John', lastSeen: new Date().toISOString() },
  'conversation456': { turn: 5, context: 'discussing weather' }
});

// Read specific keys
const data = await storage.read(['user123']);
console.log(data.user123); // { name: 'John', lastSeen: '...' }

// Delete data
await storage.delete(['conversation456']);
HeaderPropagation

A class that implements the HeaderPropagationCollection interface. It filters the incoming request headers based on the definition provided and loads them into the outgoing headers collection.

InvokeException

Represents an exception that occurs during an invoke operation.

MemoryStorage

A simple in-memory storage provider that implements the Storage interface.

MessageFactory

A factory class for creating various types of message activities.

MiddlewareSet

Represents a set of middleware.

MsalTokenCredential

Token credential implementation that uses MSAL (Microsoft Authentication Library) to acquire access tokens. Implements the Azure Core Auth TokenCredential interface for authentication scenarios.

MsalTokenProvider

Provides tokens using MSAL.

OAuthFlow

Manages the OAuth flow

RouteList
StreamingResponse

A helper class for streaming responses to the client.

TaskModuleAction

Represents a task module action.

TranscriptLoggerMiddleware

Middleware for logging agent conversations to a transcript logger.

TurnContext

Represents the context for a single turn in a conversation between a user and an agent.

TurnContextStateCollection

A collection for managing state within a turn context.

TurnState

Base class defining a collection of turn state scopes.

Example

class MyTurnState extends TurnState {
  protected async onComputeStorageKeys(context) {
    const keys = await super.onComputeStorageKeys(context);
    keys['myScope'] = `myScopeKey`;
    return keys;
  }

  public get myScope() {
    const scope = this.getScope('myScope');
    if (!scope) {
      throw new Error(`MyTurnState hasn't been loaded. Call load() first.`);
    }
    return scope.value;
  }

  public set myScope(value) {
    const scope = this.getScope('myScope');
    if (!scope) {
      throw new Error(`MyTurnState hasn't been loaded. Call load() first.`);
    }
    scope.replace(value);
  }
}
TurnStateEntry

Represents an entry in the turn state that can be tracked for changes and stored.

UserState

Manages the state of a user.

UserTokenClient

Client for managing user tokens.

Interfaces

AadResourceUrls

Represents a collection of Azure Active Directory (AAD) resource URLs. This interface defines the structure of a collection of resource URLs.

AdaptiveCard

Represents an Adaptive Card, which is a card framework that enables developers to exchange UI content in a common and consistent way.

See Adaptive Cards Documentation

AdaptiveCardAuthentication

Represents the authentication information for an adaptive card.

AdaptiveCardInvokeResponse

Represents the response of an adaptive card invoke request.

AdaptiveCardInvokeValue

Represents the value of an adaptive card invoke request.

AdaptiveCardSearchResult

Represents a single search result item returned from an Adaptive Card search operation.

Example

const searchResult: AdaptiveCardSearchResult = {
  title: "John Doe",
  value: "john.doe@company.com"
};
AdaptiveCardsOptions

Configuration options for Adaptive Cards.

AdaptiveCardsSearchParams

Represents the search parameters for adaptive cards.

AgentApplicationOptions

Configuration options for creating and initializing an Agent Application. This interface defines all the configurable aspects of an agent's behavior, including adapter settings, storage, authorization, and various feature flags.

AgentClientConfig

Configuration settings required to connect to an agent endpoint.

AnimationCard

Represents an Animation Card.

AppMemory

Interface for memory operations that provides a way to store and retrieve values by path. Allows components to persist state data during a conversation.

AppRoute

Represents a route configuration for handling bot activities within an application.

Example

const echoRoute: AppRoute<MyTurnState> = {
  selector: (activity) => activity.type === 'message',
  handler: async (context, state) => {
    await context.sendActivity(`You said: ${context.activity.text}`);
  }
};
AttachmentData

Represents the data of an attachment.

AttachmentInfo

Represents information about an attachment.

AttachmentView

Represents a view of an attachment.

AudioCard

Represents an Audio Card.

AuthConfiguration

Represents the authentication configuration.

AuthHandler

Interface defining an authorization handler for OAuth flows.

AuthProvider

Represents an authentication provider.

AuthorizationHandlers

Options for configuring user authorization. Contains settings to configure OAuth connections.

CachedAgentState

Represents agent state that has been cached in the turn context.

CardImage

Represents a Card Image.

Citation

Citations returned by the model.

Claim

Represents a claim with a type and value.

ConversationData

Data structure to store conversation state for agent interactions

ConversationMembers

Represents the members of a conversation.

ConversationResourceResponse

Represents the response from a conversation resource operation.

ConversationsResult

Represents the result of a conversation query.

CustomKey

Represents a custom key for storing state in a specific location.

DefaultConversationState

Default interface for conversation state. Extend this interface to define custom conversation state properties.

DefaultTempState

Default interface for temporary state that persists only during the current turn. Contains properties used for handling user input, file attachments, and OAuth flows.

DefaultUserState

Default interface for user state. Extend this interface to define custom user state properties.

Fact

Represents a Fact.

FlowState

Represents the state of the OAuth flow.

HeaderPropagationCollection

Defines the interface for managing header propagation.

HeaderPropagationDefinition
HeroCard

Represents a Hero Card.

InputFile

Represents a file input with its content, type, and optional URL.

InputFileDownloader

Interface for downloading input files in a specific turn context and state.

InvokeResponse

Represents the response of an invoke request.

MediaUrl

Represents a media URL.

Middleware

Interface for middleware.

O365ConnectorCard

Represents an O365 connector card.

O365ConnectorCardActionBase

Represents a base action in an O365 connector card.

O365ConnectorCardFact

Represents a fact in an O365 connector card.

O365ConnectorCardImage

Represents an image in an O365 connector card.

O365ConnectorCardSection

Represents a section in an O365 connector card.

OAuthCard

Represents an OAuth card. This interface defines the structure of an OAuth card, including its buttons, connection name, text, and associated resources.

PagedResult

Paged result of items.

Query

Represents a query with pagination and parameters.

ReceiptCard

Represents a receipt card.

ReceiptItem

Represents an item in a receipt card.

Request

Represents a Node.js HTTP Request, including the minimal set of use properties. Compatible with Restify, Express, and Node.js core http.

ResourceResponse

Represents a response containing a resource ID.

SearchInvokeOptions

Represents the options for a search invoke request.

SearchInvokeResponse

Represents the response of a search invoke request.

SearchInvokeValue

Represents the value of a search invoke request.

SignInResource

Represents a resource for signing in. This interface defines the structure of a sign-in resource, including the sign-in link, token exchange resource, and token post resource.

SignInState

Represents the state of a sign-in process.

StatePropertyAccessor

Interface for accessing a property in state storage with type safety.

Storage

Defines the interface for storage operations in the Agents platform.

StoreItem

Represents an item to be stored in a storage provider.

StoreItems

Represents a collection of store items indexed by key.

ThumbnailCard

Represents a thumbnail card.

ThumbnailUrl

Represents a thumbnail URL.

TokenExchangeInvokeRequest

Represents a token exchange invoke request.

TokenExchangeRequest

Represents a request for exchanging tokens. This interface defines the structure of a token exchange request, including the URI, token, and ID.

TokenExchangeResource

Represents a resource for exchanging tokens. This interface defines the structure of a token exchange resource, including its ID, URI, and provider ID.

TokenOrSinginResourceResponse

Represents a response containing either a token or a sign-in resource. This interface defines the structure of a response that includes a token response and a sign-in resource.

TokenPostResource

Represents a resource for posting tokens. This interface defines the structure of a token post resource, including its SAS URL.

TokenResponse

Represents the response containing OAuth token information. This interface encapsulates all data related to an OAuth token response.

TokenStatus

Represents the status of a token. This interface defines the structure of a token status, including channel ID, connection name, and other metadata.

TranscriptInfo

Information about a transcript.

TranscriptLogger

Interface for logging activities to a transcript.

TranscriptStore

Interface for storing and managing transcripts.

VideoCard

Represents a video card.

Type Aliases

ActivityImageType

Defines the type of activity image to display in an O365 connector card section.

  • 'avatar': Displays the image as a profile avatar (typically circular or small)
  • 'article': Displays the image as an article thumbnail (typically rectangular or larger)
AgentHandler

Type definition for agent handler function

ApplicationEventHandler

Event handler function type for application events.

ConversationUpdateEvents

Represents the types of conversation update events that can occur.

  • membersAdded: Triggered when new members are added to the conversation.
  • membersRemoved: Triggered when members are removed from the conversation.
DeleteActivityHandler

Defines a handler for deleting an activity. Used for middleware that needs to intercept or handle activity deletions.

MiddlewareHandler

Type for middleware handler.

O365ConnectorCardActionType

Defines the possible types of actions in an O365 connector card.

  • ViewAction: Represents an action to view content.
  • OpenUri: Represents an action to open a URI.
  • HttpPOST: Represents an action to make an HTTP POST request.
  • ActionCard: Represents an action that opens a card with additional actions or inputs.
RouteHandler

A handler function for routing operations in a specific turn context and state.

RouteSelector

A specialized selector for routing operations.

Selector

A function that determines whether a specific condition is met in the given turn context.

SendActivitiesHandler

Defines a handler for processing and sending activities. Used for middleware that needs to intercept or modify activities being sent.

StorageKeyFactory

A factory function to generate storage keys based on the conversation context.

TurnEvents

Represents the types of events that can occur during a turn in the application.

  • beforeTurn: Triggered before the turn starts.
  • afterTurn: Triggered after the turn ends.
UpdateActivityHandler

Defines a handler for updating an activity. Used for middleware that needs to intercept or modify activity updates.

Enums

AdaptiveCardActionExecuteResponseType

Defines the types of responses that can be returned after executing an Adaptive Card action.

RouteRank

Defines the priority ranking for route evaluation in the agent hosting framework.

Example

// High priority route that should be evaluated first
this.onMessage('urgent', handler, undefined, RouteRank.First);

// Normal priority route with default ranking
this.onMessage('data', handler, undefined, RouteRank.Unspecified);

// Fallback route that should be evaluated last
this.onActivity('message', fallbackHandler, undefined, RouteRank.Last);

// Multiple routes with same pattern - first ranked executes first
this.onMessage('dupText', handler1, undefined, RouteRank.Last);
this.onMessage('dupText', handler2, undefined, RouteRank.First); // This executes first
StatusCodes

HTTP status codes enumeration for agent hosting responses.

This enum provides a comprehensive set of HTTP status codes commonly used in agent hosting scenarios, including success, redirection, client error, and server error status codes.

Functions

authorizeJWT(AuthConfiguration)

Middleware to authorize JWT tokens.

configureResponseController(Application, CloudAdapter, ActivityHandler, ConversationState)

To enable Agent to Agent communication, configures the agent response controller endpoint for handling incoming activities from external services.

Example

const app = express();
const adapter = new CloudAdapter();
const agent = new MyActivityHandler();
const conversationState = new ConversationState(memoryStorage);

configureResponseController(app, adapter, agent, conversationState);
getProductInfo()

Generates a string containing information about the SDK version and runtime environment. This is used for telemetry and User-Agent headers in HTTP requests.

loadAuthConfigFromEnv(string)

Loads the authentication configuration from environment variables.

Example

tenantId=your-tenant-id
clientId=your-client-id
clientSecret=your-client-secret

certPemFile=your-cert-pem-file
certKeyFile=your-cert-key-file

FICClientId=your-FIC-client-id

connectionName=your-connection-name
authority=your-authority-endpoint
loadPrevAuthConfigFromEnv()

Loads the agent authentication configuration from previous version environment variables.

Example

MicrosoftAppId=your-client-id
MicrosoftAppPassword=your-client-secret
MicrosoftAppTenantId=your-tenant-id

Function Details

authorizeJWT(AuthConfiguration)

Middleware to authorize JWT tokens.

function authorizeJWT(authConfig: AuthConfiguration): (req: Request<Record<string, unknown>, Record<string, undefined | string | string[]>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<void>

Parameters

authConfig
AuthConfiguration

The authentication configuration.

Returns

(req: Request<Record<string, unknown>, Record<string, undefined | string | string[]>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<void>

An Express middleware function.

configureResponseController(Application, CloudAdapter, ActivityHandler, ConversationState)

To enable Agent to Agent communication, configures the agent response controller endpoint for handling incoming activities from external services.

Example

const app = express();
const adapter = new CloudAdapter();
const agent = new MyActivityHandler();
const conversationState = new ConversationState(memoryStorage);

configureResponseController(app, adapter, agent, conversationState);
function configureResponseController(app: Application, adapter: CloudAdapter, agent: ActivityHandler, conversationState: ConversationState)

Parameters

app

Application

The Express application instance to configure the route on

adapter
CloudAdapter

The CloudAdapter instance used for processing bot framework activities and managing conversations

agent
ActivityHandler

The ActivityHandler instance that contains the bot's logic for processing different types of activities

conversationState
ConversationState

The ConversationState instance used for managing conversation-specific state and conversation references

Remarks

This function sets up a POST endpoint that receives activities (messages, events, etc.) from external services and processes them through the bot framework's activity handling pipeline. It's typically used when the agent needs to receive and respond to activities from channels or services that send activities to a specific webhook endpoint.

The endpoint expects activities to be sent to: POST /api/agentresponse/v3/conversations/{conversationId}/activities/{activityId}

The function handles:

  • Normalizing incoming activity data from the request body
  • Retrieving conversation references from conversation state
  • Continuing conversations using the stored conversation reference
  • Processing EndOfConversation activities by cleaning up conversation state
  • Sending activities through the turn context and returning responses

getProductInfo()

Generates a string containing information about the SDK version and runtime environment. This is used for telemetry and User-Agent headers in HTTP requests.

function getProductInfo(): string

Returns

string

A formatted string containing the SDK version, Node.js version, and OS details

loadAuthConfigFromEnv(string)

Loads the authentication configuration from environment variables.

Example

tenantId=your-tenant-id
clientId=your-client-id
clientSecret=your-client-secret

certPemFile=your-cert-pem-file
certKeyFile=your-cert-key-file

FICClientId=your-FIC-client-id

connectionName=your-connection-name
authority=your-authority-endpoint
function loadAuthConfigFromEnv(cnxName?: string): AuthConfiguration

Parameters

cnxName

string

Returns

The authentication configuration.

Remarks

  • clientId is required

loadPrevAuthConfigFromEnv()

Loads the agent authentication configuration from previous version environment variables.

Example

MicrosoftAppId=your-client-id
MicrosoftAppPassword=your-client-secret
MicrosoftAppTenantId=your-tenant-id
function loadPrevAuthConfigFromEnv(): AuthConfiguration

Returns

The agent authentication configuration.