Agentic Retrieval with Azure AI Search and MCP: Setup Guide
>Learn how to connect Azure AI Search to AI agent runtimes using the Model Context Protocol (MCP) for dynamic querying, schema routing, and hybrid retrieval.
🎧 Listen — ~9 min
Audio summary not available yet

Dynamic retrieval pipelines for autonomous agents
Traditional Retrieval-Augmented Generation (RAG) relies on static query expansion: incoming prompts are converted into vector embeddings, matched against an index via cosine similarity, and dumped directly into the context window of a Large Language Model (LLM). While this pattern handles straightforward question-answering over narrow corpora, it breaks down when agents must navigate relational data schemas, perform multi-step document investigations, or decide dynamically whether search is even warranted.
Agentic retrieval shifts the index from a passive lookup store to an active tool runtime. By exposing search backends like Azure AI Search over the open Model Context Protocol (MCP), autonomous systems running inside frameworks like Microsoft Foundry Agent Service or open-source ReAct loops can introspect index schemas, reformulate hybrid filter queries, and chain sequential lookups dynamically.
Key takeaways
- Protocol abstraction over proprietary SDKs: Exposing search indices through an MCP server lets agents inspect tools and execute semantic or keyword filters without embedding custom SDK logic directly into the model context.
- Dynamic query reformulation: Rather than executing a single nearest-neighbor vector search, agentic retrieval allows the model to inspect initial search snippets, adjust filter facets, and run targeted follow-up queries.
- Hybrid search exploitation: Azure AI Search's support for dense vectors, sparse BM25 text scoring, and semantic reranking gives agents higher-quality grounding material than vector-only vector databases.
- Enterprise operational overhead: Running agentic search over MCP introduces iterative tool-call latency and token costs that make it ill-suited for low-latency consumer chat applications.
2. Core architecture: Azure AI Search, Foundry, and MCP
Connecting enterprise data backends to agent runtimes historically required writing bespoke tool-dispatch wrappers inside proprietary frameworks. Microsoft's architecture bridges Azure AI Search with Foundry Agent Service by standardizing on the Model Context Protocol.
┌────────────────────────────────────────────────────────┐
│ Foundry Agent Runtime │
│ (Tool Selection, Reasoning, Context Management) │
└───────────────────────────┬────────────────────────────┘
│
MCP Protocol (JSON-RPC)
│
┌───────────────────────────▼────────────────────────────┐
│ Search MCP Server │
│ (Tool Definitions: list_indexes, query_search) │
└───────────────────────────┬────────────────────────────┘
│
Azure Search REST API / SDK
│
┌───────────────────────────▼────────────────────────────┐
│ Azure AI Search │
│ - Inverted BM25 Index - Vector HNSW Index │
│ - Semantic Reranker - Document Extractors │
└────────────────────────────────────────────────────────┘The system operates across three distinct operational layers:
The MCP Host (Agent Runtime)
The host is the agent execution environment—such as Microsoft Foundry Agent Service, an open-source orchestration runtime, or a custom execution framework. The host exposes conversational state, maintains the system prompt, and acts as the client consuming tool definitions supplied by downstream MCP servers.
The MCP Server for Azure Search
The MCP server translates between the standardized Model Context Protocol JSON-RPC specification and the Azure AI Search REST API. It defines tool interfaces that the agent can read, such as search_index, get_document_by_id, or list_facets. Because the MCP server handles authentication via Azure Managed Identities, API keys are never exposed in agent prompts.
The Storage and Retrieval Engine
Azure AI Search hosts the raw documents, chunked text, generated embeddings, and inverted indexes. It executes dense vector calculations using Hierarchical Navigable Small World (HNSW) graphs alongside sparse lexical search, merging them using Reciprocal Rank Fusion (RRF) before applying semantic reranking models.
3. Step-by-step setup: Building an agentic retrieval pipeline
Constructing this pipeline involves preparing an Azure AI Search index, configuring an MCP server wrapper, and exposing it to your agent runtime.
Step 1: Provision the Azure AI Search index with hybrid capabilities
Ensure your target index contains searchable text fields, a vector field containing document chunk embeddings, and filterable metadata attributes (such as department, date, or category).
1{
2 "name": "enterprise-docs-index",
3 "fields": [
4 {"name": "id", "type": "Edm.String", "key": true, "filterable": true},
5 {"name": "title", "type": "Edm.String", "searchable": true},
6 {"name": "content", "type": "Edm.String", "searchable": true},
7 {"name": "category", "type": "Edm.String", "filterable": true, "facetable": true},
8 {
9 "name": "content_vector",
10 "type": "Collection(Edm.Single)",
11 "searchable": true,
12 "dimensions": 1536,
13 "vectorSearchProfileName": "my-hnsw-profile"
14 }
15 ],
16 "vectorSearch": {
17 "algorithms": [{"name": "my-hnsw-profile", "kind": "hnsw"}]
18 }
19}Step 2: Implement the MCP search tool server
The MCP server exposes discrete actions that the LLM agent can call. Below is an idiomatic Node.js implementation using the official Model Context Protocol TypeScript SDK to wrap Azure AI Search execution.
1import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3import {
4 CallToolRequestSchema,
5 ListToolsRequestSchema,
6} from "@modelcontextprotocol/sdk/types.js";
7import { SearchClient, AzureKeyCredential } from "@azure/search-documents";
8
9const searchClient = new SearchClient(
10 process.env.AZURE_SEARCH_ENDPOINT!,
11 process.env.AZURE_SEARCH_INDEX!,
12 new AzureKeyCredential(process.env.AZURE_SEARCH_KEY!)
13);
14
15const server = new Server(
16 { name: "azure-search-mcp", version: "1.0.0" },
17 { capabilities: { tools: {} } }
18);
19
20// Define tool schema for the agent
21server.setRequestHandler(ListToolsRequestSchema, async () => ({
22 tools: [
23 {
24 name: "query_enterprise_search",
25 description: "Search internal documents using hybrid semantic queries with optional category filtering.",
26 inputSchema: {
27 type: "object",
28 properties: {
29 query: { type: "string", description: "Natural language search query" },
30 category: { type: "string", description: "Optional metadata category filter" }
31 },
32 required: ["query"]
33 }
34 }
35 ]
36}));
37
38// Handle tool execution
39server.setRequestHandler(CallToolRequestSchema, async (request) => {
40 if (request.params.name !== "query_enterprise_search") {
41 throw new Error(`Unknown tool: ${request.params.name}`);
42 }
43
44 const { query, category } = request.params.arguments as { query: string; category?: string };
45 const filter = category ? `category eq '${category}'` : undefined;
46
47 const searchResults = await searchClient.search(query, {
48 filter,
49 top: 3,
50 select: ["id", "title", "content", "category"]
51 });
52
53 const documents = [];
54 for await (const result of searchResults.results) {
55 documents.push({
56 id: result.document.id,
57 title: result.document.title,
58 snippet: result.document.content.substring(0, 500),
59 category: result.document.category
60 });
61 }
62
63 return {
64 content: [{ type: "text", text: JSON.stringify(documents) }]
65 };
66});
67
68const transport = new StdioServerTransport();
69await server.connect(transport);Step 3: Register the MCP server in Foundry or local runtime
In your agent configuration file or deployment manifest for Foundry Agent Service, register the MCP server transport:
1{
2 "mcpServers": {
3 "azureSearch": {
4 "command": "node",
5 "args": ["/dist/azure-search-mcp.js"],
6 "env": {
7 "AZURE_SEARCH_ENDPOINT": "https://my-search-service.search.windows.net",
8 "AZURE_SEARCH_INDEX": "enterprise-docs-index",
9 "AZURE_SEARCH_KEY": "${env:AZURE_SEARCH_API_KEY}"
10 }
11 }
12 }
13}Once loaded, the agent runtime automatically parses the tool schemas and invokes query_enterprise_search whenever its internal chain of thought requires document grounding.
4. Comparing retrieval architectures
Selecting the right retrieval pattern requires weighing latency, token consumption, and reasoning depth against project requirements.
| Feature / Metric | Static RAG | Agentic Retrieval (Azure + MCP) | Dedicated Vector Stores (e.g., Pinecone, Qdrant) |
|---|---|---|---|
| Query Strategy | Single-pass top-$k$ | Multi-turn iterative tool execution | Single-pass or hybrid vector filtering |
| Search Mechanism | Dense vector cosine similarity | Dense HNSW, BM25 Lexical, and Semantic Reranker | Dense vector, sparse-dense hybrid |
| Metadata Filtering | Hardcoded pre-filters | Model-generated dynamic OData filters | Static payload filtering |
| Latency Profile | Low (150ms – 400ms) | Medium to High (1,200ms – 4,500ms) | Ultra-low (50ms – 200ms) |
| Token Cost | Fixed overhead per turn | Variable (scales with tool call turns) | Fixed overhead per turn |
| Ideal Workloads | Direct Q&A, FAQ systems | Complex investigations, cross-document reconciliation | High-throughput vector search, consumer embeddings |
For developers building these loops directly on consumer workstations rather than managed cloud runtimes, our guide on building local AI agents with VRAM budgets and ReAct loops covers resource-constrained agent execution.
5. Failure modes, security boundaries, and trade-offs
While agentic retrieval delivers superior precision over unstructured data, it introduces operational risks that engineering teams must mitigate before enterprise rollout.
Runaway tool loops
When an agent fails to locate relevant facts within its initial search response, poorly tuned system prompts can cause it to loop indefinitely—reformulating slightly altered search strings until hitting model context limits.
- Mitigation: Implement hard recursion limits (e.g., maximum 3 search calls per user task) and configure strict timeout deadlines on MCP stdio or SSE transports.
Prompt injection through search payloads
Because retrieval feeds unstructured external text directly back into the agent context, a indexed document containing adversarial prompt injections can hijack the agent's execution path. This is especially risky if the agent has access to write tools (like SQL execution or email dispatch).
- Mitigation: Maintain strict separation of privilege. Search agent workers should run in read-only sandboxes without side-effect execution rights, consistent with patterns outlined in our analysis of zero-trust AI agent security protocols.
Latency penalties
Executing an MCP round-trip involves an LLM generation pass to emit the tool call, a network request to Azure AI Search, and a second LLM pass to process the results. Teams running real-time customer support bots will find this 2-to-5 second latency profile unacceptable compared to single-pass RAG.
6. Practical verdict
The combination of Azure AI Search and the Model Context Protocol solves the rigidity of conventional RAG pipelines. By standardizing retrieval on MCP, developers decouple agent reasoning logic from data storage APIs, allowing the same search tool definitions to serve Azure Foundry agents, desktop coding assistants, or open-source agent stacks.
When to adopt: Use agentic retrieval when your domain demands cross-document reconciliation, complex OData schema filtering, or dynamic query verification where single-shot vector lookups fall short.
When to avoid: Stick with static RAG or a basic vector store if your queries follow predictable question-and-answer patterns, or if your application requires sub-second response times.
Source website screenshots


Frequently asked questions
What is the advantage of using MCP over custom Python function calling?
MCP (Model Context Protocol) provides a vendor-neutral, client-server protocol for tool definitions and resource sharing over standard transports (such as stdio or HTTP/SSE). Using MCP means your Azure AI Search tool can be reused across different agent runtimes (Foundry, Claude Desktop, local orchestrators) without rewriting tool-dispatch wrappers for each framework.
Does Azure AI Search charge extra for agentic queries?
Azure AI Search charges based on your provisioned tier (Basic, Standard, Storage Optimized) and optional semantic search units. While the MCP server itself does not incur Azure charges, agentic retrieval typically performs multiple queries per user question, which increases request volume and consumption against your search service quotas.
Can agentic retrieval be implemented with open-source local LLMs?
Yes. As long as the local model is capable of reliable structured tool calling (such as modern Qwen, Llama, or Mistral variants), an open-source orchestrator can connect to an Azure AI Search MCP server. However, smaller models (<8B parameters) often struggle with multi-stage filter synthesis and reasoning over failed retrieval attempts.
How does hybrid search improve agentic accuracy?
Pure vector search often misses exact identifiers, product SKUs, or error codes due to tokenization and embedding approximations. Azure AI Search combines dense vectors with traditional BM25 inverted indexes, scoring results with Reciprocal Rank Fusion. This ensures that when an agent searches for an exact alphanumeric ID, the relevant document is not buried by generalized semantic matches.
Sources and image references
- Microsoft Learn: Build an agentic retrieval solution that connects Azure AI Search to Foundry Agent Service through MCP
- Model Context Protocol Documentation: Specification and Architecture
- NVIDIA Developer: Agentic AI Learning Path
- Airbyte Engineering: A Guide to Building AI Agents
Keep reading
Related reading
⚡ AI Engineering Briefing
AI model releases, practical tutorials, developer tools, and engineering research. Unsubscribe anytime.
Comments
Comments are temporarily unavailable while the public discussion space is being configured.