LazaUK/AIFoundry-Agents-LogicApps
Practical implementation of Azure AI Foundry agent with Logic Apps as its tool, using function calling or OpenAPI schema (with both SAS token and Managed Identity's OAuth options).
Azure AI Foundry Agent Service: Using Logic Apps as Tools
This repository demonstrates how to integrate Azure Logic Apps as custom tools for an Azure AI Foundry agent.
Note
For more in-depth information about the Azure AI Foundry Agent Service, refer to the official Azure AI Foundry documentation.
📑 Table of Contents:
- Configuring the Environment
- Option A: Logic App as a Tool using Function Calling
- Option B: Logic App as a Tool using OpenAPI Schema with SAS Token auth
- Option C: Logic App as a Tool using OpenAPI Schema with Managed Identity auth
- Option D: Logic App (STANDARD) as a Tool using OpenAPI Schema with SAS Token auth
- Appendix: Sample Logic App
Configuring the Environment
To run the provided Jupyter notebooks, you'll need to set up your Azure AI Foundry environment and install the required Python packages.
1.1 Prerequisites
You need an Azure AI Foundry project with a model deployment that supports function calling (e.g., GPT-4.1-mini). You also need a pre-existing Azure Logic App with an HTTP Trigger configured to accept incoming requests.
1.2 Initial Setup Authentication
The demo uses Microsoft Entra ID authentication via DefaultAzureCredential from the azure.identity package. To enable this, ensure you are authenticated through the Azure CLI (az login), by setting up environment variables for a service principal, or by using a managed identity in an Azure environment.
1.3 Environment Variables
Configure the following environment variables with your Azure credentials and project details:
| Environment Variable | Description |
|---|---|
AZURE_FOUNDRY_PROJECT_ENDPOINT |
The endpoint URL for your Azure AI Foundry project. |
AZURE_FOUNDRY_GPT_MODEL |
The name of your model deployment. |
AZURE_SUBSCRIPTION_ID |
Your Azure subscription ID. |
RESOURCE_GROUP_NAME |
The name of the resource group containing your Logic App. |
LOGIC_APP_NAME |
The name of the Azure Logic App resource |
TRIGGER_NAME |
The name of the HTTP trigger within your Logic App |
WORKFLOW_NAME |
The name of the workflow within your Logic App (for Standard only) |
1.4 Required Libraries
Install the necessary Python packages using pip:
pip install -r requirements.txtOption A: Logic App as a Tool using Function Calling
This section details how to wrap a Logic App's functionality within a Python function and expose it to the AI agent as a tool.
2.1 The AzureLogicAppTool Class
A dedicated class, AzureLogicAppTool, is used to manage the Logic App. It performs two key tasks:
register_logic_app: This method retrieves the unique callback URL for the Logic App's HTTP-Trigger. It uses theLogicManagementClientto securely obtain this URL, which is required to invoke the Logic App.invoke_logic_app: This method sends aPOSTrequest to the registered callback URL with a JSON payload, effectively triggering the Logic App workflow.
class AzureLogicAppTool:
"""
A service that manages Logic Apps by retrieving their callback URLs and invoking them.
"""
def __init__(self, subscription_id: str, resource_group: str, credential=None):
if credential is None:
credential = DefaultAzureCredential()
self.subscription_id = subscription_id
self.resource_group = resource_group
self.logic_client = LogicManagementClient(credential, subscription_id)
self.callback_urls: Dict[str, str] = {}
def register_logic_app(self, logic_app_name: str, trigger_name: str) -> None:
"""
Retrieves and stores a callback URL for a specific Logic App + trigger.
"""
<...>
def invoke_logic_app(self, logic_app_name: str, payload: Dict[str, Any]) -> Dict[str, Any]:
"""
Invokes the registered Logic App with the given JSON payload.
"""
<...>2.2 Python Wrapper Function
A helper function, create_weather_forecast_function, acts as a bridge between the AI agent and the AzureLogicAppTool:
- Accepting a
locationparameter from the agent. - Constructing the necessary JSON
payload. - Calling the
invoke_logic_appmethod from theAzureLogicAppToolclass. - Formating the result into a standardised JSON response that the agent can easily parse.
def create_weather_forecast_function(logic_app_tool: AzureLogicAppTool, logic_app_name: str) -> Callable[[str], str]:
"""
Creates a weather forecast function that can be used by the AI agent.
"""
def get_weather_forecast(location: str) -> str:
"""
Gets weather forecast for a specific location using the Logic App.
:param location: The location to get weather forecast for (e.g., "London", "New York", "Tokyo")
:return: A JSON string containing the weather forecast information
"""
payload = {"Location": location}
try:
result = logic_app_tool.invoke_logic_app(logic_app_name, payload)
if result.get("result") == "success":
weather_info = result.get("weather_data", result.get("data", "Weather data received"))
return json.dumps({
"status": "success",
"location": location,
"forecast": weather_info
})
else:
return json.dumps({
"status": "error",
"location": location,
"error": result.get("error", "Unknown error occurred")
})
except Exception as e:
return json.dumps({
"status": "error",
"location": location,
"error": str(e)
})
return get_weather_forecast2.3 Agent Configuration
With the Python wrapper function defined, you can now configure the AI agent:
- Define Agent Tools: The
get_weather_forecastfunction is added to aFunctionToolinstance. A separateget_current_datetimefunction is also included to demonstrate the agent's ability to use multiple tools. - Enable Function Calling: The
agents_client.enable_auto_function_calls()method is used to instruct the agent's model to automatically call the defined tools when appropriate. - Create the Agent: An agent is created with a clear instruction set that guides it to use the
get_weather_forecasttool when asked about the weather.
The output of AI agent's setup may look like this:
Setting up agent tools...
Creating weather agent...
Created weather agent with ID: asst_P24uYTY3zZhH2VFnP6on62lt
Creating conversation thread...
Created thread with ID: thread_au3fmRys3MadIZTnCppkDHmf
Agent is ready! You can now interact with it.Option B: Logic App as a Tool using OpenAPI Schema with SAS Token auth
This section demonstrates how to integrate Azure Logic Apps with Azure AI Foundry agents using OpenAPI schema. Option B utilises a Shared Access Signature (SAS) token for authentication process.
3.1 The LogicAppsIntegration Class
The LogicAppsIntegration class manages the integration between Logic Apps and the AI agent through OpenAPI spec. It handles:
- Callback URL Retrieval
- OpenAPI Spec Generation
- Agentic Tool Creation
class LogicAppsIntegration:
"""
This class uses Logic Apps callback URL as-is and creates OpenAPI tools.
"""
def __init__(self, subscription_id: str, resource_group: str, credential=None):
if credential is None:
credential = DefaultAzureCredential()
self.subscription_id = subscription_id
self.resource_group = resource_group
self.credential = credential
self.logic_client = LogicManagementClient(credential, subscription_id)
def get_callback_url(self, logic_app_name: str, trigger_name: str) -> str:
"""Get the actual callback URL from Logic App."""
# Implementation retrieves secure callback URL
def create_direct_openapi_spec(self, callback_url: str) -> Dict[str, Any]:
"""Create a minimal OpenAPI 3.0 spec that uses the callback URL directly."""
# Implementation creates OpenAPI specification
def create_openapi_tool(self, logic_app_name: str, trigger_name: str) -> OpenApiTool:
"""Create OpenAPI tool using direct callback URL approach."""
# Implementation returns configured OpenApiTool3.2 OpenAPI Specification Generation
The class automatically generates a minimal OpenAPI 3.0 spec that includes:
- Logic App Backend Configuration
- SAS Token Authentication
- JSON payload structure
openapi_spec = {
"openapi": "3.0.0",
"info": {
"title": "Logic App Weather API",
"version": "1.0.0",
"description": "Direct access to Logic App via callback URL"
},
"servers": [{"url": callback_url.split('?')[0]}],
"paths": {
"/": {
"post": {
"operationId": "get_weather",
"summary": "Get weather information",
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"Location": {
"type": "string",
"description": "The location to get weather for"
}
},
"required": ["Location"]
}
}
}
}
}
}
}
}3.3 Agent Setup with OpenAPI Tools
The OpenAPI approach simplifies agent configuration by providing a standardised tool definition:
# Initialize Logic App integration
logic_integration = LogicAppsIntegration(
subscription_id=SUBSCRIPTION_ID,
resource_group=RESOURCE_GROUP
)
# Create OpenAPI tool
openapi_tool, tool_name = logic_integration.create_openapi_tool(
logic_app_name=LOGIC_APP_NAME,
trigger_name=TRIGGER_NAME,
tool_name="get_weather",
tool_description="Get weather forecast for any location"
)
# Create AI Agent with OpenAPI tool
agent = agents_client.create_agent(
model=MODEL_DEPLOYMENT,
name="weather-agent",
instructions="You are a helpful weather assistant. When asked about weather, use the get_weather tool with the location provided by the user.",
tools=openapi_tool.definitions,
)3.4 Usage Example
Once configured, the agent can seamlessly use the Logic App tool:
# Create a conversation thread
thread = agents_client.threads.create()
# Send a message requesting weather information
message = agents_client.messages.create(
thread_id=thread.id,
role="user",
content="What's the weather in London?",
)
# Process the request (agent will automatically call the Logic App)
run = agents_client.runs.create_and_process(
thread_id=thread.id,
agent_id=agent.id
)The agent will use the OpenAPI tool to call the Logic App and provide a formatted response to the user, similar to this:
Displaying conversation results...
Found 2 messages
--------------------------------------------------
User: What's the weather in London?
--------------------------------------------------
Assistant: The weather in London is currently cloudy. During the day, the high temperature will be 19°C with wind speeds around 22 km/h coming from the southwest (217°). At night, it will remain cloudy with a low temperature of 17°C and winds around 20 km/h from the south-southwest (202°). The skies are overcast, and there is a chance of light rain. Ultraviolet (UV) levels are low.
--------------------------------------------------Note
The OpenAPI approach offers improved standardisation, automatic schema validation and reduced maintenance compared to the Function Calling method, while still enabling the full functionality of Logic App integration
Option C: Logic App as a Tool using OpenAPI Schema with Managed Identity auth
This section details the most secure and robust method for integrating a Logic App by using an OpenAPI schema with Managed Identity authentication.
Important
This approach enhances security by eliminating the need to manage secrets or SAS tokens. The Azure AI Foundry agent leverages the resource's managed identity to securely acquire an authentication token, which is then used to call the Logic App. This is the recommended approach for production environments as it follows best practices for cloud security and credential management.
4.1 Code Changes
The notebook for Option C is nearly identical to the one for Option B. The critical changes are within the LogicAppsIntegration class to enable managed identity authentication:
- OpenAPI Specification: The spec is modified to use an Authorization header for the managed identity's OAuth token.
"components": {
"securitySchemes": {
"managedIdentity": {
"type": "apiKey",
"in": "header",
"name": "Authorization"
}
}
}- URL Parameter Filtering: The code filters out SAS token parameters (e.g., sig, sv) from the Logic App's callback URL, as they are replaced by the managed identity token.
parsed = urlparse(callback_url)
query_params = parse_qs(parsed.query)
parameters = []
sas_params_to_exclude = {'sv', 'sig', 'sr', 'se', 'sp'}
for param_name, param_values in query_params.items():
if param_values and param_name not in sas_params_to_exclude:
parameters.append({
"name": param_name,
"in": "query",
"required": True,
"schema": {
"type": "string",
"default": param_values[0]
}
})4.2 Managed Identity for the Azure AI Foundry resource
In the Azure Portal, navigate to your Azure AI Foundry resource, select the Identity blade and enable the system-assigned identity. Note down the Object (principal) ID, as you will need it in a later step.
4.3 Secure Logic App HTTP Trigger
Next, configure your Logic App's HTTP trigger to require a valid OAuth token from the agent.
- In the Logic App Code view, find your HTTP trigger definition and add the following line to process the Authorization header:
"operationOptions": "IncludeAuthorizationHeadersInOutputs"- Switch to the Logic App Designer view, open the trigger's Settings and add the following Trigger Condition. This enforces the use of a Bearer token:
@startsWith(triggerOutputs()?['headers']?['Authorization'], 'Bearer')4.4 Authorisation Policy
Create a policy to grant access exclusively to your AI Foundry's Managed Identity.
In your Logic App, navigate to the Authorization blade and click Add policy. Configure the policy by adding the following three claims to validate the incoming token:
- Issuer Claim (iss): Verifies the token is from your Microsoft Entra ID tenant.
Value: https://sts.windows.net/<YOUR_TENANT_ID>/- Audience Claim (aud): Verifies the token is intended for Azure management APIs.
Value: https://management.azure.com/- Object ID Claim (oid): Verifies the token belongs to your AI Project's identity.
Value: Use the Object (principal) ID you noted in step 4.2.Note
Big shout out to Robbe Van den Daele from @HybridBrothers on the original post about the use of managed identities in Logic App HTTP triggers: https://hybridbrothers.com/posts/using-managed-identities-in-logic-app-http-triggers/.
Option D: Logic App (STANDARD) as a Tool using OpenAPI Schema with SAS Token auth
This section demonstrates integration of Azure Standard Logic Apps with Azure AI Foundry agents using OpenAPI schema and SAS token authentication.
5.1 Key Differences from Consumption Logic Apps
Standard Logic Apps are built on the Azure Functions runtime, which provides enhanced performance, scalability and networking capabilities. Due to this architectural difference, Standard Logic Apps are managed through the Azure App Service infrastructure rather than the Logic Apps Management API.
5.2 Implementation Approach
The StandardLogicAppsIntegration class uses the azure-mgmt-web package (Azure App Service Management SDK) instead of azure-mgmt-logic, as Standard Logic Apps are hosted as App Service resources.
pythonclass StandardLogicAppsIntegration:
def __init__(self, subscription_id: str, resource_group: str, credential=None):
self.web_client = WebSiteManagementClient(credential, subscription_id)
def get_callback_url(self, logic_app_name: str, workflow_name: str, trigger_name: str) -> str:
"""Get callback URL for a Standard Logic App workflow trigger."""
callback = self.web_client.workflow_triggers.list_callback_url(
resource_group_name=self.resource_group,
name=logic_app_name,
workflow_name=workflow_name,
trigger_name=trigger_name
)
return callback.value5.3 Configuration Requirements
When using Standard Logic Apps, you'll need to specify an additional environment variable: WORKFLOW_NAME with the name of the specific Logic App workflow. Standard Logic Apps can contain multiple workflows, so this parameter identifies which workflow to invoke.
5.4 Authentication Method
This implementation uses SAS token authentication (included in the callback URL) with anonymous OpenAPI authentication. The SAS parameters (sp, sv, sig) are automatically included in the OpenAPI specification as query parameters.
Appendix: Sample Logic App
To demonstrate the integration, you'll need a Logic App with an HTTP trigger that accepts a location parameter and returns weather information.

