@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 SDK-specific Activity-protocol delegation over HTTP.

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 AgentState.createProperty for creating property accessors See StatePropertyAccessor for the interface definition

AttachmentDownloader

A utility class for downloading input files from activity attachments.

BaseAdapter

Abstract base class for all adapters in the Agents framework.

CardFactory

Factory class for creating various types of cards.

CloudAdapter

Abstract base class for all adapters in the Agents framework.

ConnectionManager

Generic, provider-agnostic connection manager. Dispatches connections to any AuthProvider implementation produced by the supplied AuthProviderFactory, while owning the provider-independent connection routing logic (audience matching, service URL dispatch, altBlueprintConnectionName handling, default connection resolution).

ConnectorClient

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

ConsoleTranscriptLogger

A transcript logger that logs activities to the console.

Conversation

A serializable pair of a ConversationReference and the JWT claims needed to authenticate proactive calls on behalf of this agent.

Instances are stored in and retrieved from the proactive storage backend. The identity getter produces the JwtPayload shape expected by adapter.continueConversation().

ConversationBuilder

Fluent builder for the Conversation class.

Example

// Build from scratch
const conv = ConversationBuilder
  .create('my-client-id', 'msteams')
  .withUser('user-aad-id')
  .withConversationId('19:channel@thread.skype')
  .build()

// Build from a live TurnContext
const conv = ConversationBuilder.fromContext(turnContext).build()
ConversationReferenceBuilder

Fluent builder for ConversationReference.

ConversationState

Manages the state of a conversation.

CreateConversationOptionsBuilder

Fluent builder for CreateConversationOptions.

Example

const opts = CreateConversationOptionsBuilder
  .create('my-client-id', 'msteams')
  .withUser('user-aad-id')
  .withTenantId('tenant-id')
  .build()
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.

HttpClient

A lightweight HTTP client built on native fetch.

HttpError

Error thrown when an HTTP request fails.

InvokeException

Represents an exception that occurs during an invoke operation.

M365AttachmentDownloader

Downloads attachments from Teams and M365 using the bots access token.

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.

MsalConnectionManager

Connection manager backed by MSAL (and, for EntraAuthSideCar connections, the Entra sidecar provider). A thin convenience subclass of ConnectionManager that supplies the default provider factory and applies MSAL-specific connection defaults.

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.

OutboundHostValidator

Shared allowlist policy for server-side outbound requests.

A configured suffix matches both the exact host and its subdomains. The policy is disabled by default to preserve existing SDK behavior.

Proactive

Provides methods for storing, retrieving, and managing conversation references to enable proactive messaging scenarios. Supports sending activities and continuing conversations outside the standard request/response flow using stored conversation references.

RouteList
SidecarAuthProvider

Authentication provider that delegates token acquisition to the Microsoft Entra Agent ID sidecar (agent container). This replaces MSAL at the connection layer, using the sidecar's /AuthorizationHeaderUnauthenticated/{serviceName} endpoint for app-only and agentic identity flows. The sidecar performs the full Blueprint→Instance→User chain internally; no MSAL exchange is performed in-process.

StreamingResponse

A helper class for streaming responses to the client.

TaskModuleAction

Represents a task module action.

TeamsAttachmentDownloader
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 for SDK-specific Activity-protocol delegation.

AgentResponseHandlerParams

Route parameters supplied to AgentResponseHandler — typically pulled from the framework's URL path parser.

AgenticAuthorizationOptions

Options for configuring the Agentic authorization handler.

Example

# For a handler with id "myAuth":
AgentApplication__UserAuthorization__handlers__myAuth__settings__type=AgenticUserAuthorization
AgentApplication__UserAuthorization__handlers__myAuth__settings__scopes=api://scope1 api://scope2
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.

AuthProvider

Represents an authentication provider.

Authorization
AuthorizationHandlerTokenOptions

Options for token requests in authorization handlers.

AzureBotAuthorizationOptions

Interface defining an authorization handler configuration.

Example

# For a handler with id "myAuth":
AgentApplication__UserAuthorization__handlers__myAuth__settings__azureBotOAuthConnectionName=MyConnection
AgentApplication__UserAuthorization__handlers__myAuth__settings__oboScopes=api://scope1 api://scope2
AzureBotAuthorizationOptionsLegacy

Interface defining an authorization handler configuration.

Example

# For a handler with id "myAuth":
AgentApplication__UserAuthorization__handlers__myAuth__settings__azureBotOAuthConnectionName=MyConnection
AgentApplication__UserAuthorization__handlers__myAuth__settings__oboScopes=api://scope1 api://scope2
AzureBotAuthorizationOptionsMessages
AzureBotAuthorizationOptionsOBO
CachedAgentState

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

CardImage

Represents a Card Image.

Citation

Citations returned by the model.

CloudAdapterOptions

Optional configuration for CloudAdapter runtime behavior.

Defaults are conservative and match the .NET SDK's AdapterOptions defaults.

Each option can also be supplied via an environment variable using the convention CloudAdapterOptions__<propertyName> — for example CloudAdapterOptions__validateServiceUrl=true. The prefix matches the .NET SDK's IConfiguration.GetSection("CloudAdapterOptions") section name, so a shared environment can configure both SDKs from the same variables. Both the CloudAdapterOptions__ prefix and the property name are matched case-insensitively, so hosts that uppercase env-var names (some PaaS platforms) still work. Values supplied directly to the constructor always win over environment variables.

CloudAdapterResult

Result of creating a CloudAdapter from an agent.

ConnectionMapItem

A single entry in the connections map used to route an inbound activity (matched by audience and/or serviceUrl) to a named connection.

ConnectionSettings

The complete settings for a single connection, across every provider.

ConnectionSettingsBase

Connection-level settings common to every authentication provider.

Connections
ConversationClaims

JWT-like claims identifying the agent for proactive authentication. aud (the agent's client ID) is required; all other fields are optional.

ConversationData

Conversation state for an SDK-specific delegated Activity exchange.

ConversationMembers

Represents the members of a conversation.

ConversationResourceResponse

Represents the response from a conversation resource operation.

ConversationsResult

Represents the result of a conversation query.

CreateConversationOptions

Options passed to Proactive.createConversation(). Flattened — no nested Conversation wrapper.

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.

DefaultUserState

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

Fact

Represents a Fact.

HeaderPropagationCollection

Defines the interface for managing header propagation.

HeaderPropagationDefinition

A function type that defines how headers should be propagated.

HeroCard

Represents a Hero Card.

HttpClientOptions

Options for creating an HttpClient instance.

HttpRequestConfig

Configuration for an HTTP request.

HttpResponse

Represents an HTTP response.

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.

MsalConnectionSettings

Connection settings for the MSAL-backed authentication providers (the default providers used for every AuthType except EntraAuthSideCar).

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.

OutboundHostValidatorOptions

Configuration for the shared outbound-host allowlist.

OutboundUrlPolicy

A policy that decides whether an outbound URL is safe to request.

PagedResult

Paged result of items.

ProactiveOptions

Configuration for the proactive messaging subsystem.

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.

SidecarConnectionSettings

Connection settings for the Entra Agent ID sidecar (agent container) authentication provider, used when a connection's authType is 'EntraAuthSideCar'.

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.

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.

TokenExchangeInvokeResponse

Represents the response for a token exchange invoke operation.

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.

TypingOptions

Configuration options for automatic typing indicators.

TypingTimingOptions

Typing timer settings for a specific channel or the global default.

VideoCard

Represents a video card.

WebApp

Minimal application surface needed by configureResponseController to register the SDK-specific Activity callback POST route. Express's Application structurally satisfies this. Framework integrations that do not satisfy it should wrap createAgentResponseHandler; Fastify users should use configureResponseController from @microsoft/agents-hosting-fastify.

WebApp is a minimal structural shape rather than a richer, named route-registrar contract. It is exported so it has a stable name in the generated type declarations and API report (it appears in the exported configureResponseController signature). Any framework app whose post(path, handler) method structurally matches satisfies it.

WebRequestParamsCarrier

Minimal HTTP request shape used by framework-agnostic route handlers.

WebResponse

Framework-agnostic response surface used by the hosting layer.

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

AgentResponseHandler

Framework-agnostic handler signature for the SDK-specific Activity callback endpoint.

ApplicationEventHandler

Event handler function type for application events.

AuthProviderFactory

Factory function that creates an AuthProvider instance from a connection's AuthConfiguration.

AuthorizationOptions

Authorization configuration options.

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.

NextFunction

Framework-agnostic next callback used by middleware-style functions in the hosting layer (notably authorizeJWT). Mirrors the shape of Express's NextFunction so existing Express middleware continues to work unchanged.

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.

AuthType

Supported authentication types for agent connections.

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.

StreamingResponseResult

Results for streaming response operations.

Functions

buildJwksUri(string, AuthConfiguration)

Builds the JWKS URI for the given token issuer and auth configuration.

clearJwksClients()

Clears process-wide JWKS clients.

createOutboundHostValidator(OutboundHostValidatorOptions)

Creates the default validator, with explicit settings overriding the environment.

getAuthConfigWithDefaults(AuthConfiguration)

Loads the authentication configuration from the provided config or from the environment variables providing default values for authority and issuers.

Example

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

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

FICClientId=your-FIC-client-id

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

Loads validator options from environment variables compatible with the .NET OutboundHostValidator configuration section.

Hosts can be supplied either as a comma-separated Hosts value or as indexed values such as Hosts__0, Hosts__1, and so on.

resolveAuthority(string, string)

Resolves the full authority URL including the tenant ID. Supports both patterns:

  • Tenant embedded in authority: https://login.microsoftonline.com/my-tenant
  • Authority + separate tenantId: https://login.microsoftonline.com + tenantId Also handles trailing slashes on authority.
resolveAuthType(AuthConfiguration)

Resolves the authentication type for a given authentication configuration.

Variables

ACTION_INVOKE_NAME
AGENT_RESPONSE_ROUTE_PATH

Canonical route path for the agent response controller endpoint. Both Express and Fastify wrappers should register on this path.

AgentCallbackHandlerKey

Key for the agent callback handler in TurnState collection.

ApxDevScope
ApxDoDScope
ApxGallatinScope
ApxGCCHScope
ApxGCCScope
ApxLocalScope

Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.

ApxProductionScope
AzureBotScope

Default OAuth scope for Azure Bot Service authentication.

HostingErrors
INVOKE_RESPONSE_KEY

Symbol key for invoke response

TeamsServiceEndpoints

Well-known Teams service URLs for proactive messaging.

Use only when the incoming serviceUrl from a real conversation is unavailable. Once you have received a serviceUrl from a real turn, cache and prefer that value.

authorizeJWT

Middleware to authorize JWT tokens.

configureResponseController

Registers the authenticated Activity callback endpoint used by SDK-specific Activity-protocol delegation.

Example

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

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

Creates a framework-agnostic handler for the authenticated Activity callback endpoint.

This is the core, Express-free implementation used by:

  • configureResponseController in @microsoft/agents-hosting-express
  • configureResponseController in @microsoft/agents-hosting-fastify

Both wrappers register the canonical route POST /api/agentresponse/v3/conversations/:conversationId/activities/:activityId and forward the parsed body + path parameters to the handler returned here. The handler returns 401 for failed JWT authentication and 403 when the authenticated caller does not match the delegated agent stored for the conversation, or when that delegated state is missing or malformed.

This callback contract is SDK-specific and is not the open A2A protocol.

createCloudAdapter

Creates a CloudAdapter for the given agent.

If the agent is an AgentApplication with a pre-configured adapter, that adapter is reused. Otherwise, a new CloudAdapter is created.

Example

import { AgentApplication, TurnState, createCloudAdapter } from '@microsoft/agents-hosting';

const app = new AgentApplication<TurnState>();
const { adapter, headerPropagation } = createCloudAdapter(app, { clientId: process.env.CLIENT_ID });

// Use the adapter directly with request/response objects compatible with CloudAdapter.process
adapter.process(req, res, (context) => app.run(context), headerPropagation);
defaultAuthProviderFactory

Default AuthProviderFactory that dispatches per-connection by authType: connections with authType set to EntraAuthSideCar use SidecarAuthProvider; all others use MsalTokenProvider.

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

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
sendX5C=false

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

buildJwksUri(string, AuthConfiguration)

Builds the JWKS URI for the given token issuer and auth configuration.

function buildJwksUri(iss: string, authConfig: AuthConfiguration): string

Parameters

iss

string

The token issuer claim.

authConfig
AuthConfiguration

The authentication configuration for the matched audience.

Returns

string

The JWKS URI string.

clearJwksClients()

Clears process-wide JWKS clients.

function clearJwksClients()

createOutboundHostValidator(OutboundHostValidatorOptions)

Creates the default validator, with explicit settings overriding the environment.

function createOutboundHostValidator(options?: OutboundHostValidatorOptions): OutboundHostValidator

Parameters

Returns

getAuthConfigWithDefaults(AuthConfiguration)

Loads the authentication configuration from the provided config or from the environment variables providing default values for authority and issuers.

Example

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

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

FICClientId=your-FIC-client-id

connectionName=your-connection-name
authority=your-authority-endpoint
function getAuthConfigWithDefaults(config?: AuthConfiguration): AuthConfiguration

Parameters

Returns

The authentication configuration.

loadOutboundHostValidatorOptionsFromEnv()

Loads validator options from environment variables compatible with the .NET OutboundHostValidator configuration section.

Hosts can be supplied either as a comma-separated Hosts value or as indexed values such as Hosts__0, Hosts__1, and so on.

function loadOutboundHostValidatorOptionsFromEnv(): OutboundHostValidatorOptions

Returns

resolveAuthority(string, string)

Resolves the full authority URL including the tenant ID. Supports both patterns:

  • Tenant embedded in authority: https://login.microsoftonline.com/my-tenant
  • Authority + separate tenantId: https://login.microsoftonline.com + tenantId Also handles trailing slashes on authority.
function resolveAuthority(authority?: string, tenantId?: string): string

Parameters

authority

string

tenantId

string

Returns

string

resolveAuthType(AuthConfiguration)

Resolves the authentication type for a given authentication configuration.

function resolveAuthType(authConfig?: AuthConfiguration): string

Parameters

authConfig
AuthConfiguration

The authentication configuration object.

Returns

string

The resolved authentication type as a string or 'unknown' if it cannot be determined.

Remarks

The function checks various properties of the authConfig object to determine the appropriate authentication type. It returns a string representing the resolved authentication type or 'unknown' if it cannot be determined.

Variable Details

ACTION_INVOKE_NAME

ACTION_INVOKE_NAME: "adaptiveCard/action"

Type

"adaptiveCard/action"

AGENT_RESPONSE_ROUTE_PATH

Canonical route path for the agent response controller endpoint. Both Express and Fastify wrappers should register on this path.

AGENT_RESPONSE_ROUTE_PATH: "/api/agentresponse/v3/conversations/:conversationId/activities/:activityId"

Type

"/api/agentresponse/v3/conversations/:conversationId/activities/:activityId"

AgentCallbackHandlerKey

Key for the agent callback handler in TurnState collection.

AgentCallbackHandlerKey: "agentCallbackHandler"

Type

"agentCallbackHandler"

ApxDevScope

ApxDevScope: string

Type

string

ApxDoDScope

ApxDoDScope: string

Type

string

ApxGallatinScope

ApxGallatinScope: string

Type

string

ApxGCCHScope

ApxGCCHScope: string

Type

string

ApxGCCScope

ApxGCCScope: string

Type

string

ApxLocalScope

Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.

ApxLocalScope: string

Type

string

ApxProductionScope

ApxProductionScope: string

Type

string

AzureBotScope

Default OAuth scope for Azure Bot Service authentication.

AzureBotScope: "https://api.botframework.com"

Type

"https://api.botframework.com"

HostingErrors

HostingErrors: {[key: string]: AgentErrorDefinition}

Type

{[key: string]: AgentErrorDefinition}

INVOKE_RESPONSE_KEY

Symbol key for invoke response

INVOKE_RESPONSE_KEY: unique symbol

Type

unique symbol

TeamsServiceEndpoints

Well-known Teams service URLs for proactive messaging.

Use only when the incoming serviceUrl from a real conversation is unavailable. Once you have received a serviceUrl from a real turn, cache and prefer that value.

TeamsServiceEndpoints: { dod: "https://smba.infra.dod.teams.microsoft.us/teams", gcc: "https://smba.infra.gcc.teams.microsoft.com/teams", gccHigh: "https://smba.infra.gov.teams.microsoft.us/teams", publicGlobal: "https://smba.trafficmanager.net/teams/" }

Type

{ dod: "https://smba.infra.dod.teams.microsoft.us/teams", gcc: "https://smba.infra.gcc.teams.microsoft.com/teams", gccHigh: "https://smba.infra.gov.teams.microsoft.us/teams", publicGlobal: "https://smba.trafficmanager.net/teams/" }

authorizeJWT

Middleware to authorize JWT tokens.

authorizeJWT: (authConfig: AuthConfiguration) => (req: Request, res: WebResponse, next: NextFunction) => Promise<void>

Type

(authConfig: AuthConfiguration) => (req: Request, res: WebResponse, next: NextFunction) => Promise<void>

configureResponseController

Registers the authenticated Activity callback endpoint used by SDK-specific Activity-protocol delegation.

Example

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

configureResponseController(app, adapter, agent, conversationState);
configureResponseController: (app: WebApp, adapter: CloudAdapter, agent: ActivityHandler, conversationState: ConversationState) => void

Type

(app: WebApp, adapter: CloudAdapter, agent: ActivityHandler, conversationState: ConversationState) => void

Remarks

This endpoint is part of the Microsoft Agents SDK delegated-agent callback flow

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

The function handles:

  • Returning 401 when JWT authentication fails
  • Returning 403 when delegated state is invalid or the authenticated caller does not own the delegated conversation
  • 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

Anonymous callbacks are supported only for unconfigured development hosts outside production and cannot cryptographically prove callback ownership.

createAgentResponseHandler

Creates a framework-agnostic handler for the authenticated Activity callback endpoint.

This is the core, Express-free implementation used by:

  • configureResponseController in @microsoft/agents-hosting-express
  • configureResponseController in @microsoft/agents-hosting-fastify

Both wrappers register the canonical route POST /api/agentresponse/v3/conversations/:conversationId/activities/:activityId and forward the parsed body + path parameters to the handler returned here. The handler returns 401 for failed JWT authentication and 403 when the authenticated caller does not match the delegated agent stored for the conversation, or when that delegated state is missing or malformed.

This callback contract is SDK-specific and is not the open A2A protocol.

createAgentResponseHandler: (adapter: CloudAdapter, agent: ActivityHandler, conversationState: ConversationState) => AgentResponseHandler

Type

(adapter: CloudAdapter, agent: ActivityHandler, conversationState: ConversationState) => AgentResponseHandler

createCloudAdapter

Creates a CloudAdapter for the given agent.

If the agent is an AgentApplication with a pre-configured adapter, that adapter is reused. Otherwise, a new CloudAdapter is created.

Example

import { AgentApplication, TurnState, createCloudAdapter } from '@microsoft/agents-hosting';

const app = new AgentApplication<TurnState>();
const { adapter, headerPropagation } = createCloudAdapter(app, { clientId: process.env.CLIENT_ID });

// Use the adapter directly with request/response objects compatible with CloudAdapter.process
adapter.process(req, res, (context) => app.run(context), headerPropagation);
createCloudAdapter: (agent: AgentApplication<TurnState<any, any>> | ActivityHandler, authConfig?: AuthConfiguration) => CloudAdapterResult

Type

(agent: AgentApplication<TurnState<any, any>> | ActivityHandler, authConfig?: AuthConfiguration) => CloudAdapterResult

defaultAuthProviderFactory

Default AuthProviderFactory that dispatches per-connection by authType: connections with authType set to EntraAuthSideCar use SidecarAuthProvider; all others use MsalTokenProvider.

defaultAuthProviderFactory: AuthProviderFactory

Type

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.

getProductInfo: () => string

Type

() => string

loadAuthConfigFromEnv

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
sendX5C=false

FICClientId=your-FIC-client-id

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

Type

(cnxName?: string) => AuthConfiguration

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
loadPrevAuthConfigFromEnv: () => AuthConfiguration

Type

() => AuthConfiguration