Skip to main content

SQL Query Tools

Connect your AI agents directly to SQL Server databases, enabling them to retrieve, update, and manage data through secure, parameterized queries.

Overview

SQL Query Tools allow your agents to execute custom SQL queries against Azure SQL Server databases. Instead of complex API integrations, administrators can create database query tools through a guided wizard that the AI can use to answer questions, look up records, and update data in real-time.

Use Cases

  • Customer Lookup - Retrieve customer details by ID, email, or name from your CRM database
  • Order Status - Check order status, shipping information, and delivery tracking
  • Inventory Queries - Look up product availability, stock levels, and warehouse locations
  • Data Updates - Update customer contact information or order status (with confirmation)
  • Financial Reporting - Query sales figures, outstanding balances, and payment history
  • System Monitoring - Check active users, error logs, or system statistics

How It Works

Connection          SQL Query              Agent Tool
Configuration Definition Execution
| | |
v v v
+-----------+ +-----------+ +-----------+
| Database | --> | Query + | --> | Paramete- |
| Server + | | Parameters| | rized |
| Credentials| | + Tool | | Execution |
+-----------+ | Description| +-----------+
+-----------+ |
| v
v +-----------+
+-----------+ | Formatted |
| Auto- | | Results |
| generated | | for AI |
| Tool | +-----------+
+-----------+

Prerequisites

Before creating SQL Query Tools:

  1. Database Access - Have your SQL Server connection details ready (server, database, credentials)
  2. Network Connectivity - Ensure your database is accessible from Azure (firewall rules configured)
  3. Query Knowledge - Know the tables and columns you want to query
  4. Permissions - Have appropriate database permissions for the queries you want to run

Managing Connections

  1. Navigate to Build > Connections > SQL Tools
  2. The page displays two tabs: Connections and Queries
  3. Click the Connections tab to manage database connections

Creating a Connection

  1. Click Add Connection
  2. Fill in the connection details:
FieldDescription
Connection NameUnique identifier (lowercase, hyphens, numbers only)
Display NameFriendly name shown in the UI
DescriptionOptional description of this database
Server NameSQL Server hostname (e.g., mydb.database.windows.net)
Database NameTarget database name
Authentication TypeSQL Authentication, Azure AD, or Managed Identity
UsernameDatabase username (for SQL auth)
PasswordDatabase password (encrypted at rest)
Connection TimeoutMax seconds to establish connection (default: 30)
Command TimeoutMax seconds for query execution (default: 60)
Allow Write OperationsEnable INSERT, UPDATE, DELETE queries
Max Rows (Default)Default row limit for results (default: 100)
Max Rows (Absolute)Hard maximum row limit (default: 1000)
  1. Click Test Connection to verify connectivity
  2. Click Save to create the connection

Authentication Types

TypeWhen to Use
SQL AuthenticationStandard username/password authentication
Azure Active DirectoryUse Azure AD credentials
Managed IdentityAzure Functions managed identity (no credentials stored)

Write Operation Protection

The Allow Write Operations setting controls what types of queries can be created:

  • Disabled (default): Only SELECT queries are allowed. This is the safest option for read-only integrations.
  • Enabled: INSERT, UPDATE, DELETE, and stored procedure execution are permitted.
Write Operations

Enable write operations only when necessary. All write operations are logged for auditing, and you can optionally require confirmation for sensitive updates.

Editing and Deleting Connections

  • Edit: Click the edit button on a connection card to modify settings
  • Delete: Click the delete button. This also deletes all queries using that connection.
Cascade Deletion

Deleting a connection also removes all SQL queries that use it and their tool assignments to agents.

Creating SQL Query Tools

  1. Navigate to Build > Connections > SQL Tools
  2. Click the Queries tab
  3. Click Add Query to start the wizard

Step 1: Basic Information

Fill in the query identification details:

FieldDescription
ConnectionSelect the database connection to use
Query NameUnique identifier for this query
Display NameFriendly name shown in the UI
DescriptionWhat this query does
Tool NameFunction name the AI will call (lowercase, underscores)
Tool DescriptionDetailed description for the AI to understand when to use this tool
Tool Description

Write the tool description as if explaining to a person when they should use this query. Include what information it returns and when it's appropriate to call.

Good example: "Look up customer information by their email address. Returns customer name, company, account status, and contact details. Use when you need to identify who sent an email or verify customer information."

Step 2: SQL Query Editor

Enter your SQL query:

SELECT
CustomerId,
CustomerName,
Email,
Phone,
Status,
CreatedAt
FROM Customers
WHERE Email = @email

Configure query options:

OptionDescription
Query TypeSELECT, INSERT, UPDATE, DELETE, or EXEC (auto-detected)
Is Stored ProcedureCheck if calling a stored procedure
Max RowsOverride connection default (optional)
Return Formattable (markdown), json, or summary

Return Formats:

FormatBest For
tableHuman-readable markdown tables, good for small result sets
jsonStructured data, good for AI processing
summaryLarge result sets, returns count and sample row

Click Parse Parameters to extract @parameter placeholders from your query.

Step 3: Parameter Configuration

For each parameter detected in your query, configure:

SettingDescription
Parameter NameThe @param name from your query (read-only)
TypeSQL data type (INT, NVARCHAR, DATETIME, etc.)
LengthCharacter length for VARCHAR/NVARCHAR types
RequiredWhether this parameter must be provided
Default ValueValue to use if not provided (optional)
DescriptionExplanation for the AI about what value to provide
Validation RulesJSON constraints (min, max, pattern, enum)

Example Parameter Configuration:

ParameterTypeRequiredDescription
@emailNVARCHAR(255)YesCustomer's email address
@statusNVARCHAR(50)No (default: Active)Filter by customer status

Validation Rules:

// For integers with range
{"minimum": 1, "maximum": 9999}

// For strings with pattern
{"pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"}

// For strings with allowed values
{"enum": ["Active", "Inactive", "Pending"]}

Step 4: Test Execution

Before saving, test your query:

  1. Enter test values for each parameter
  2. Click Execute Test
  3. Review the results

Successful test shows:

  • Row count and execution time
  • Sample results in your chosen format
  • Column names and data types

Failed test shows:

  • Error message from the database
  • SQL state code for troubleshooting
Test Values

Use realistic test values that you know exist in your database. This validates both the query syntax and your parameter types.

Step 5: Grant Tool Access

After saving, choose which agents can use this tool:

  1. Select agents from the list of available agents and SMEs
  2. Check the boxes next to agents that should have access
  3. Click Grant Access

You can also assign tools later from the agent configuration page.

Sample Query Configurations

Customer Lookup by Email

SELECT CustomerId, CustomerName, Email, Phone, Status
FROM Customers
WHERE Email = @email

Parameters:

  • @email (NVARCHAR 255, required): Customer email to search

Tool Description: "Look up customer information by email address. Returns customer ID, name, contact details, and account status."

Order Status Check

SELECT
o.OrderId,
o.OrderNumber,
o.OrderDate,
o.Status,
o.TotalAmount,
o.TrackingNumber,
c.CustomerName
FROM Orders o
INNER JOIN Customers c ON o.CustomerId = c.CustomerId
WHERE o.OrderNumber = @orderNumber

Parameters:

  • @orderNumber (NVARCHAR 50, required): Order number to look up

Tool Description: "Check the status of an order by order number. Returns order details including status, total amount, and shipping tracking number."

Update Customer Email

UPDATE Customers
SET Email = @newEmail, UpdatedAt = GETUTCDATE()
WHERE CustomerId = @customerId

Parameters:

  • @customerId (INT, required): Customer ID to update
  • @newEmail (NVARCHAR 255, required): New email address

Tool Description: "Update a customer's email address. Requires customer ID and new email. Use only when the customer explicitly requests an email change."

Ticket Statistics by Status

SELECT
Status,
COUNT(*) AS TicketCount,
AVG(DATEDIFF(hour, CreatedAt, COALESCE(ResolvedAt, GETUTCDATE()))) AS AvgResolutionHours
FROM SupportTickets
WHERE CreatedAt >= @startDate
GROUP BY Status
ORDER BY TicketCount DESC

Parameters:

  • @startDate (DATETIME, required): Start date for statistics

Tool Description: "Get support ticket statistics grouped by status. Returns ticket counts and average resolution times. Use for reporting on support workload."

Security and Best Practices

Credential Protection

  • All database passwords are encrypted at rest using AES-256-CBC encryption
  • Credentials are never returned in API responses
  • Connection test uses encrypted credentials directly

SQL Injection Prevention

SQL Query Tools use parameterized queries exclusively:

  • All queries must use @parameter syntax
  • Parameter values are escaped automatically
  • Dynamic SQL is not allowed
  • Suspicious patterns are blocked (DROP TABLE, xp_cmdshell, etc.)

Write Operation Safeguards

For queries that modify data:

  1. Connection-level control: Enable "Allow Write Operations" only when needed
  2. Query-level confirmation: Enable "Require Confirmation" for sensitive updates
  3. Audit logging: All write operations are logged with parameters and results

Result Size Limits

Three-tier limit system prevents excessive data retrieval:

  1. Connection Default: Applied to all queries using this connection
  2. Connection Absolute: Maximum rows that can ever be returned
  3. Query Override: Per-query limit (cannot exceed connection absolute)
  1. Least Privilege: Create dedicated database users with minimal permissions
  2. Read-Only by Default: Keep write operations disabled unless required
  3. Row Limits: Set appropriate limits to prevent accidental large result sets
  4. Audit Review: Regularly review query execution logs
  5. Parameter Validation: Use validation rules to constrain input values

Managing SQL Query Tools

View All Queries

Navigate to Build > Connections > SQL Tools > Queries to see all configured queries:

  • Filter by connection
  • Filter by query type (SELECT, UPDATE, etc.)
  • Search by name or description
  • View assigned agent count

Edit a Query

  1. Click the edit button on a query card
  2. Modify settings through the wizard steps
  3. Re-test the query before saving (required after changes)
  4. Save to update the tool

Delete a Query

  1. Click the delete button on a query card
  2. Confirm deletion
Tool Removal

Deleting a query removes it from all agents that use it. Consider deactivating the query instead if you might need it later.

Toggle Active/Inactive

Use the status toggle to enable or disable a query without deleting it. Inactive queries are not available to agents.

Execution Logging

Viewing Query Executions

All SQL query executions are logged in the agent execution details:

  1. Navigate to Monitor > Activity > Agent Activity
  2. Click on an execution
  3. Expand the tool calls section
  4. Find the SQL query tool call

What Gets Logged

CategoryDetails
Tool CallTool name, parameters passed
ExecutionStart time, duration, success/failure
ResultsRow count, sample data (truncated)
ErrorsError messages, SQL state codes

Write Operation Audit

Write operations include additional audit data:

  • Full parameter values
  • Rows affected count
  • Connection and database names
  • User/agent that triggered the operation

Troubleshooting

Connection Errors

Problem: Cannot connect to database

Solutions:

  1. Verify server name and port are correct
  2. Check firewall rules allow Azure Functions access
  3. Verify credentials are correct
  4. For Azure SQL, ensure Azure AD login is configured if using AD auth

Query Timeout

Problem: Query exceeds command timeout

Solutions:

  1. Increase command timeout in connection settings
  2. Optimize the query (add indexes, reduce result set)
  3. Add more specific WHERE clauses to limit data

Parameter Type Mismatch

Problem: Query fails with type conversion error

Solutions:

  1. Verify parameter type matches column type
  2. Check parameter length for VARCHAR/NVARCHAR
  3. Ensure date formats are valid for DATETIME parameters

Tool Not Appearing

Problem: Query tool not available to agent

Solutions:

  1. Verify the query is Active (not disabled)
  2. Check the query is assigned to the agent
  3. Verify the connection is Active
  4. Refresh the agent's tool list

Empty Results

Problem: Query returns no results

Solutions:

  1. Verify test data exists in the database
  2. Check parameter values match expected format
  3. Test the query directly in SQL Server Management Studio