Skip to main content

Search Mailbox Tool

The Search Mailbox Tool enables AI agents to proactively search, read, and browse emails from any mailbox in your Microsoft 365 organization. Unlike monitored mailboxes that react to incoming emails, this tool lets agents reach out and find information across the organization's email landscape on demand.

Overview

The Problem

Without the Search Mailbox Tool, agents have limited email visibility:

  • Reactive only -- Agents can only process emails that arrive at monitored mailboxes. They cannot proactively look up past correspondence in other mailboxes.
  • No cross-mailbox context -- When handling a customer inquiry, agents cannot check what other departments have communicated with that customer.
  • Manual lookups required -- Research tasks that involve reviewing email history require humans to find and forward relevant messages to agents.

The Solution

The Search Mailbox Tool gives agents the ability to:

  1. Search any accessible mailbox using full-text KQL queries or structured filters (sender, date range, attachments, subject)
  2. Read full email content with automatic HTML-to-text conversion and configurable body truncation
  3. List folders in any accessible mailbox to understand its structure

All access is controlled through per-agent scoping configuration, ensuring agents only access mailboxes appropriate to their role.

Prerequisites

Before agents can use the Search Mailbox Tool, you need:

  1. Microsoft 365 Integration -- Your organization must be connected via Build > Connections > Microsoft 365 with the application registration having Mail.Read permissions
  2. Tool Assignment -- The search_mailbox tool must be assigned to the agent via Build > AI Agents > Agents
  3. Access Scope Configured -- A mailbox_access configuration must be set in the tool's ToolConfiguration on the agent's tool assignment

Configuring Mailbox Access

Understanding Access Scopes

The Search Mailbox Tool uses a fail-closed access model: if no mailbox_access configuration is set, the agent has no access to any mailbox. Access is configured per-agent through the ToolConfiguration JSON on the agent's tool assignment in the AgentTools table.

There are four scoping modes, which can be used individually or combined:

Full Access

Grant the agent access to search any mailbox in the tenant.

{
"mailbox_access": "all"
}

Use when: The agent needs unrestricted access, such as an AICOS or executive assistant agent.

Department-Based Access

Grant access to mailboxes belonging to employees in specified departments. This is validated against the Employee Directory.

{
"mailbox_access": {
"departments": ["Sales", "Customer Support"]
}
}

Use when: An agent should only access mailboxes within specific business units. Employees must be synced to the Employee Directory with department assignments.

Group-Based Access

Grant access to mailboxes of members in specified Entra ID (Azure AD) groups.

{
"mailbox_access": {
"groups": ["a1b2c3d4-e5f6-7890-abcd-ef1234567890"]
}
}

Use when: Access should follow existing Entra ID group membership. Group members are cached for 5 minutes to optimize performance.

Specific Mailboxes

Grant access to an explicit list of mailbox addresses.

{
"mailbox_access": {
"mailboxes": ["info@company.com", "support@company.com", "sales@company.com"]
}
}

Use when: The agent needs access to a known, fixed set of mailboxes.

Combined Access (Union Logic)

All three array-based scoping methods can be combined. Access is granted if the target mailbox matches any of the configured criteria (OR logic).

{
"mailbox_access": {
"departments": ["Sales"],
"groups": ["a1b2c3d4-e5f6-7890-abcd-ef1234567890"],
"mailboxes": ["info@company.com"]
}
}

In this example, the agent can search a mailbox if the mailbox owner is in the Sales department, OR is a member of the specified Entra ID group, OR the mailbox address is info@company.com.

No Configuration (Default Deny)

If mailbox_access is not set or is missing from the ToolConfiguration, the agent receives an access denied error. This fail-closed design ensures no accidental access.

Setting Up Access via the Admin Console

To configure mailbox access for a standard agent:

  1. Navigate to Build > AI Agents > Agents
  2. Edit the agent
  3. In the Tools section, find the search_mailbox tool
  4. Click the gear icon next to the tool to open the configuration modal
  5. Select Full Access (any mailbox) or Scoped Access (restricted)
  6. For Scoped Access, enter the allowed mailboxes, departments, or Entra ID groups
  7. Click Save

To configure mailbox access for AICOS:

  1. Navigate to Build > AI Chief of Staff > Tools
  2. Find the search_mailbox tool in the list
  3. Click the gear icon to open the configuration modal
  4. Select Full Access or Scoped Access
  5. For Scoped Access, add the AICOS monitored mailbox address (e.g., aicos@company.com) and the Business Owner's personal mailbox address (e.g., ceo@company.com)
  6. Click Save

Important: The search_mailbox tool uses a fail-closed access model. If you assign the tool to an agent without configuring mailbox access, the agent will receive "Access denied" errors when attempting to search any mailbox. You must configure access after assigning the tool.

How Agents Use the Tool

Operations

OperationDescriptionRequired Parameters
searchFind emails using KQL keywords or structured filtersmailbox_address
read_messageRead the full content of 1-5 messagesmailbox_address, message_ids
list_foldersList all mail folders in a mailboxmailbox_address

Search Operation

The search operation finds emails in a mailbox using full-text search, structured filters, or both.

Parameters

ParameterTypeRequiredDescription
mailbox_addressstringYesEmail address of the mailbox to search
keywordsstringNoKQL full-text search query (searches subject, body, sender, recipients)
from_addressstringNoFilter by sender email address
subject_containsstringNoFilter by subject text
date_afterstringNoOnly include emails after this ISO date
date_beforestringNoOnly include emails before this ISO date
has_attachmentsbooleanNoFilter for emails with attachments
folder_idstringNoScope search to a folder ID or well-known name (inbox, sentitems, drafts, etc.)
max_resultsintegerNoMaximum results to return, 1-50 (default: 10)
skipintegerNoNumber of results to skip for pagination
order_bystringNoSort order: newest or oldest (default: newest). Only works without keywords.

KQL vs Structured Filters

You can use KQL keywords, structured filters, or both together:

  • KQL only -- keywords: "invoice Acme Corp" performs a full-text search across subject, body, sender, and recipients.
  • Structured only -- Use from_address, date_after, subject_contains, etc. for precise field-level filtering.
  • Combined -- Use both for maximum precision. For example, keywords: "budget" combined with from_address: "cfo@company.com" and date_after: "2026-01-01".

Search Results

Each result includes:

FieldDescription
idMessage ID (use with read_message to get full content)
subjectEmail subject line
fromSender email address
from_nameSender display name
received_atWhen the email was received
previewShort body preview text
has_attachmentsWhether the email has attachments
importanceEmail importance level
is_readWhether the email has been read

Results also include total_estimated (approximate total matches) and has_more (whether additional results are available via pagination).

When you need to find relevant emails from another mailbox:
1. Use search_mailbox with operation "search" and the target mailbox address
2. Start with specific keywords and filters to narrow results
3. Use the message IDs from search results with "read_message" to get full content
4. If you need to explore the mailbox structure first, use "list_folders"

Read Message Operation

The read_message operation retrieves the full content of up to 5 messages at once.

Parameters

ParameterTypeRequiredDescription
mailbox_addressstringYesEmail address of the mailbox
message_idsarrayYesArray of message IDs to read (1-5 messages)
max_body_lengthintegerNoMaximum body length per message, 500-50,000 characters (default: 8,000)
include_headersbooleanNoInclude To and CC recipients (default: true)

Read Results

Each message includes:

FieldDescription
idMessage ID
subjectEmail subject line
from / from_nameSender email and display name
received_atWhen the email was received
bodyFull email body converted to plain text
body_lengthOriginal body length before truncation
truncatedWhether the body was truncated
has_attachmentsWhether the email has attachments
toList of To recipients (when include_headers is true)
ccList of CC recipients (when include_headers is true)

HTML email bodies are automatically converted to plain text for readability.

List Folders Operation

The list_folders operation returns all mail folders in a mailbox.

Parameters

ParameterTypeRequiredDescription
mailbox_addressstringYesEmail address of the mailbox

Folder Results

Each folder includes:

FieldDescription
idFolder ID (use with folder_id parameter in search)
nameFolder display name
total_countTotal number of items in the folder
unread_countNumber of unread items

Token Budget and Truncation

Email bodies can be large, consuming significant context window tokens. The max_body_length parameter on the read_message operation controls how much of each email body is returned:

SettingValueTypical Use
Minimum500 charsQuick subject/summary scanning
Default8,000 charsBalanced detail for most emails
Maximum50,000 charsFull content for long documents or threads

When a body exceeds the limit, it is truncated and marked with [TRUNCATED]. The body_length field shows the original full length, and truncated is set to true.

Recommendation: Start with the default 8,000 characters. Increase only when the agent specifically needs full email bodies (e.g., for document review or legal analysis).

Security Considerations

MeasureDescription
Fail-Closed AccessNo mailbox_access configuration means no access. Agents must be explicitly granted scope.
Tenant IsolationAll Graph API calls are scoped to the agent's tenant. Cross-tenant access is not possible.
Read-OnlyThe tool can only search, read, and list. It cannot send, delete, move, or modify any emails.
Per-Agent ScopingEach agent has its own access configuration. Different agents can have different levels of access.
Graph API PermissionsAccess is bounded by the application's Microsoft Graph permissions (Mail.Read).
Audit TrailAll tool calls are logged in execution details, showing which mailboxes and messages were accessed.
Group Member CachingGroup membership is cached for 5 minutes. Changes to group membership may take up to 5 minutes to take effect.

Error Handling

Error CodeMeaningResolution
MISSING_CONTEXTAgent or tenant context not availableEnsure the tool is called within an agent execution context
INVALID_PARAMSInvalid parameters (e.g., bad email format, max_results out of range)Check parameter values against the schema
ACCESS_DENIEDAgent does not have access to the target mailboxReview and update the mailbox_access configuration
CONFIG_ERRORFailed to load the ToolConfiguration from the databaseCheck database connectivity and AgentTools configuration
GRAPH_ERRORMicrosoft Graph API returned an errorCheck Graph API permissions and mailbox existence

Graph API Error Mapping

HTTP StatusFriendly Message
403Application may not have permission to access this mailbox
404Mailbox not found -- verify the email address is correct
429Rate limit exceeded -- wait before retrying

Troubleshooting

Access Denied Errors

Symptoms: Agent receives "Access denied" or "No mailbox access configuration found" errors.

Solutions:

  1. Verify the search_mailbox tool is assigned to the agent
  2. Check that the ToolConfiguration includes a valid mailbox_access configuration
  3. For department-based access, confirm the target mailbox owner is in the Employee Directory with the correct department
  4. For group-based access, verify the target user is a member of the specified Entra ID group
  5. For specific mailboxes, check that the email address matches exactly (case-insensitive)

No Search Results

Symptoms: Search returns empty results when emails should exist.

Solutions:

  1. Verify the mailbox address is correct
  2. Try broader search terms or remove filters
  3. Check date range filters -- date_after and date_before must use ISO date format
  4. If using folder_id, verify the folder exists using list_folders first
  5. KQL search may not find very recent emails due to indexing delay

Rate Limiting

Symptoms: Agent receives "Rate limit exceeded" errors.

Solutions:

  1. Reduce the frequency of search_mailbox calls in the agent's instructions
  2. Use more specific filters to reduce the number of API calls needed
  3. Batch message reading (up to 5 per call) instead of reading one at a time
  4. Wait and retry -- Microsoft Graph rate limits reset within minutes

Tool Not Available

Symptoms: Agent does not have access to the search_mailbox tool.

Solutions:

  1. Navigate to Build > AI Agents > Agents and verify the tool is assigned
  2. Check that the tool assignment is enabled (IsEnabled = true)
  3. Ensure the Microsoft 365 integration is connected and healthy

Best Practices

Agent Instructions

Include clear guidance in your agent's instructions for when and how to use the tool:

When you need to find emails from another person's mailbox:
1. First use list_folders to understand the mailbox structure if needed
2. Use search with specific keywords and filters to find relevant messages
3. Review the previews from search results before reading full messages
4. Use read_message with specific message_ids to get full content
5. Respect privacy -- only search mailboxes relevant to your current task
6. Use date filters to limit results to relevant time periods

Access Configuration

  • Start restrictive -- Begin with specific mailboxes or departments, and expand as needed
  • Match scope to role -- A customer support agent only needs access to the support team's mailboxes, not the entire organization
  • Use groups for dynamic access -- Entra ID groups automatically update membership, reducing maintenance
  • Document your decisions -- Record why each agent has the access scope it does for compliance audits
  • Combine methods thoughtfully -- Use combined access (departments + specific mailboxes) to cover both team-based and cross-functional needs

Performance

  • Use filters -- Narrow searches with date ranges, sender addresses, and folder IDs to reduce API calls and token usage
  • Batch reads -- Read up to 5 messages per call instead of making separate calls
  • Paginate wisely -- Start with max_results: 10 and paginate only if needed
  • Limit body size -- Use the default 8,000 character body limit unless full content is essential

Comparison with Mine Mailbox Tool

FeatureSearch MailboxMine Mailbox
PurposeSearch and read emails on demandBuild searchable knowledge bases from email archives
OperationReal-time query against live mailboxBatch processing with LLM value assessment
OutputDirect email content returned to agentIndexed documents in Azure AI Search
Access ModelPer-agent mailbox scoping (ToolConfiguration)Feature-level enablement with rate limits
Read/WriteRead-only (search, read, list)Creates knowledge sources and triggers scans
LatencyImmediate resultsAsynchronous (minutes to hours)
CostGraph API calls onlyGraph API + LLM evaluation costs
Best ForFinding specific emails during a taskBuilding reusable knowledge from email history