Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Note
Foundry IQ (Azure AI Search) provides direct indexing and query APIs alongside higher-level knowledge source and knowledge base APIs for managed retrieval. Use the Azure portal, REST APIs, or Azure SDKs to configure these capabilities, or connect agents to knowledge bases in the Microsoft Foundry portal.
Important
Features or capabilities marked (preview) in this article are in Public Preview and are subject to the Supplemental Terms of Use for Microsoft Azure Previews. For preview terms specific to Foundry IQ (Azure AI Search), see Preview functionality.
In an agentic retrieval pipeline, the retrieve action invokes parallel query processing from a knowledge base. You can call the retrieve action directly using the Search Service REST APIs or an Azure SDK. Each knowledge base also exposes a Model Context Protocol (MCP) endpoint for consumption by MCP-compatible agents.
To set up a pipeline that connects Foundry IQ (Azure AI Search) to Foundry Agent Service via MCP, see Tutorial: Build an end-to-end agentic retrieval solution.
Usage support
| Azure portal | Microsoft Foundry portal | .NET SDK | Python SDK | Java SDK | JavaScript SDK | REST API |
|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
Prerequisites
A Foundry IQ service with a knowledge base.
Permission to query knowledge bases. Configure keyless authentication with the Search Index Data Reader role assigned to your user account (recommended) or use a query API key.
If you call the MCP endpoint through the Azure OpenAI Responses API, you need:
A deployed LLM and the Cognitive Services OpenAI User role (or an API key) on the Foundry resource. You can reuse the LLM and resource specified in your knowledge base, if applicable.
The
Azure.AI.OpenAIpackage:dotnet add package Azure.AI.OpenAI
The
Azure.Search.DocumentsandAzure.Identitypackages listed in Create a knowledge base. Use the latest stable package for2026-10-01. Preview SDK examples use the latest preview package and its default2026-11-01-previewcontract.
If you call the MCP endpoint through the Azure OpenAI Responses API, you need:
A deployed LLM and the Cognitive Services OpenAI User role (or an API key) on the Foundry resource. You can reuse the LLM and resource specified in your knowledge base, if applicable.
The
openaipackage:pip install openai
The
azure-search-documentsandazure-identitypackages listed in Create a knowledge base. Use the latest stable package for2026-10-01. Preview SDK examples use the latest preview package and its default2026-11-01-previewcontract.
Required Search Service REST API version:
For preview features: 2026-11-01-preview
For the GA contract described here:
2026-10-01. The2026-04-01examples below retain their narrower contract.
For keyless authentication, include a Microsoft Entra ID token in the
Authorizationheader of each HTTP request.
Limitations
For search index knowledge sources, when you enable reranking, retrieve uses the knowledge source's semantic configuration. The underlying index's defaultScoringProfile might influence first-stage candidate selection, but don't rely on an arbitrary index scoring profile to control final knowledge base semantic ranking. Retrieve responses also don't surface @search.rerankerBoostedScore.
Call the retrieve action
You specify the retrieve action on a knowledge base. The request body includes query input and optional per-source parameters. Those parameters configure attached sources; omitting an entry doesn't exclude that source.
The GA 2026-10-01 REST contract supports minimal, low, and medium effort, model-backed planning, answer synthesis, citations, and SSE. The older 2026-04-01 contract supports only intents and minimal, extractive retrieval. Preview-only fields aren't accepted by the GA contract.
Retrieve with 2026-10-01 REST
First, create the model-free knowledge base using an existing, populated search index knowledge source. Use the same {{knowledge-source-name}} and credentials authorized to retrieve content. Replace the question with one relevant to your source.
POST {{search-endpoint}}/knowledgebases('core-minimal-kb')/retrieve?api-version=2026-10-01
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{search-token}}
{
"intents": [
{ "type": "semantic", "search": "What is the return policy?" }
],
"retrievalReasoningEffort": { "kind": "minimal" },
"outputMode": "extractiveData",
"includeActivity": true,
"maxRuntimeInSeconds": 30,
"maxOutputDocuments": 3,
"maxOutputSizeInTokens": 5000,
"knowledgeSourceParams": [
{
"knowledgeSourceName": "{{knowledge-source-name}}",
"kind": "searchIndex",
"alwaysQuerySource": true,
"failOnError": true,
"includeReferences": true,
"includeReferenceSourceData": true,
"maxOutputDocuments": 50
}
]
}
Reference: Knowledge Retrieval - Retrieve
Inspect response, references, and activity. This request uses one complete semantic intent and no chat model. Ordinary minimal retrieval rejects messages. For low or medium planning, configure a supported model and supply messages or semantic intents, but not both.
Only explicit alwaysQuerySource: true makes a source mandatory during model-driven selection. Ordinary minimal retrieval selects all candidate sources regardless of this flag. false or omission isn't exclusion. If a selected source fails retrieval or post-processing, failOnError causes the entire request to fail.
| GA request setting | Bounds and behavior |
|---|---|
maxRuntimeInSeconds |
10 through 600 seconds. The implementation fallback is 90 seconds; persisted defaults can affect omitted values. |
Top-level maxOutputDocuments |
1 through 200 unique documents, applied after per-source limiting. Duplicate entries don't consume another document allocation, so this value isn't a reference-array length limit. |
Per-source maxOutputDocuments |
50 through 200. Affects candidate sizing, page sizing, and per-source final pruning. |
maxOutputSizeInTokens |
At least 5,000 tokens. Controls grounding output pruning, not a guaranteed synthesized-answer length. Fallback budgets vary by effort, enabled features, and configuration. |
rerankerThreshold |
0 through 4. Set it per source when needed; don't assume a universal default score threshold. |
includeReferences, includeReferenceSourceData |
Control references and their source data separately. Source data requires references. Settings-backed defaults are references enabled and source data disabled. |
Each knowledgeSourceParams entry requires knowledgeSourceName and the source's matching kind. For a search index source, filterAddOn is combined with any stored searchIndexParameters.baseFilter using AND; it doesn't replace the stored filter.
For web sources, request language, market, count, and freshness override stored webParameters values. Omitted values then use implementation defaults: en, en-US, and a count of 20. Language and market must be supported values; count accepts 1 through 50. Freshness accepts Day, Week, Month, a valid date, or an ordered YYYY-MM-DD..YYYY-MM-DD range.
Keep stored source properties, knowledge base membership, and request parameters separate. Query hints and resultsProcessing aren't part of 2026-10-01. For stored configuration, see Knowledge source settings.
Retrieve with 2026-10-01 Python
Use the model-free knowledge base and its existing, populated search index knowledge source. Set SEARCH_ENDPOINT and SEARCH_API_KEY in your environment to the service endpoint and an authorized API key. Replace the knowledge base name and source_name with your values, and choose a question relevant to the source's content.
Run these blocks in sequence.
import os
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.knowledgebases import KnowledgeBaseRetrievalClient
from azure.search.documents.knowledgebases.models import (
KnowledgeBaseRetrievalRequest,
KnowledgeBaseSearchIndexReference,
KnowledgeRetrievalMinimalReasoningEffort,
KnowledgeRetrievalSemanticIntent,
SearchIndexKnowledgeSourceParams,
)
endpoint = os.environ["SEARCH_ENDPOINT"]
credential = AzureKeyCredential(os.environ["SEARCH_API_KEY"])
source_name = "<existing-search-index-source>"
question = "What is the return policy?"
kb_client = KnowledgeBaseRetrievalClient(
endpoint=endpoint,
credential=credential,
api_version="2026-10-01",
knowledge_base_name="<knowledge-base-name>",
)
Reference: KnowledgeBaseRetrievalClient
Create a request that uses one semantic intent, minimal effort, and extractive output. The top-level output cap is three documents; the per-source setting is 50. The request enables references and their source data separately.
baseline_request = KnowledgeBaseRetrievalRequest(
intents=[KnowledgeRetrievalSemanticIntent(search=question)],
retrieval_reasoning_effort=KnowledgeRetrievalMinimalReasoningEffort(),
output_mode="extractiveData",
include_activity=True,
max_runtime_in_seconds=30,
max_output_documents=3,
max_output_size_in_tokens=6000,
knowledge_source_params=[
SearchIndexKnowledgeSourceParams(
knowledge_source_name=source_name,
include_references=True,
include_reference_source_data=True,
always_query_source=True,
fail_on_error=False,
max_output_documents=50,
)
],
)
baseline_response = kb_client.retrieve(baseline_request)
for message in baseline_response.response:
for content in message.content:
print(content.text)
activities_by_id = {
activity.id: activity for activity in baseline_response.activity or []
}
for activity in baseline_response.activity or []:
print(activity.id, activity.type)
for reference in baseline_response.references or []:
if not isinstance(reference, KnowledgeBaseSearchIndexReference):
continue
activity = activities_by_id.get(reference.activity_source)
if getattr(activity, "knowledge_source_name", None) != source_name:
continue
print(reference.id, reference.doc_key, reference.activity_source)
print(reference.source_data)
print(reference.citation_url)
Reference: KnowledgeBaseRetrievalClient
Inspect the grounding content for information from your populated source. This response isn't a synthesized answer.
SDK and earlier-version examples
The preview SDK examples use the latest preview packages and their default 2026-11-01-preview contract.
Use a model-free knowledge base with an existing, populated search index knowledge source. Set SEARCH_ENDPOINT and SEARCH_API_KEY in your environment to the service endpoint and an authorized API key. Replace the knowledge base name and sourceName with your values, and choose a question relevant to the source's content.
Run the following setup and request blocks in sequence. Later C# model-free examples continue from this client.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Azure;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases;
using Azure.Search.Documents.KnowledgeBases.Models;
using Azure.Search.Documents.Models;
var endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));
var key = Environment.GetEnvironmentVariable("SEARCH_API_KEY");
var credential = new AzureKeyCredential(key);
var knowledgeBaseName = "<knowledge-base-name>";
var sourceName = "<existing-search-index-source>";
var question = "What is the return policy?";
var kbClient = new KnowledgeBaseRetrievalClient(
endpoint, knowledgeBaseName, credential);
Reference: KnowledgeBaseRetrievalClient
The baseline uses one semantic intent, minimal effort, extractive output, activity, and source references with source data. The source document setting is separate from the request-wide document limit.
KnowledgeBaseRetrievalRequest previewRetrievalRequest = new()
{
RetrievalReasoningEffort = new KnowledgeRetrievalMinimalReasoningEffort(),
OutputMode = KnowledgeRetrievalOutputMode.ExtractiveData,
IncludeActivity = true,
MaxRuntimeInSeconds = 30,
MaxOutputDocuments = 5
};
previewRetrievalRequest.Intents.Add(
new KnowledgeRetrievalSemanticIntent(question));
previewRetrievalRequest.KnowledgeSourceParams.Add(
new SearchIndexKnowledgeSourceParams(sourceName)
{
IncludeReferences = true,
IncludeReferenceSourceData = true,
MaxOutputDocuments = 50
});
var previewResult = await kbClient.RetrieveAsync(
previewRetrievalRequest, cancellationToken: CancellationToken.None);
KnowledgeBaseRetrievalResponse baselineResponse = previewResult.Value;
Console.WriteLine(
((KnowledgeBaseMessageTextContent)baselineResponse.Response[0].Content[0]).Text);
Reference: KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest
Inspect the returned extractive content for information from your populated source. The response is grounding data, not a model-synthesized answer. Don't use the reference-array length as a document-count guarantee.
from azure.identity import DefaultAzureCredential
from azure.search.documents.knowledgebases import KnowledgeBaseRetrievalClient
from azure.search.documents.knowledgebases.models import (
KnowledgeBaseMessage,
KnowledgeBaseMessageTextContent,
KnowledgeBaseRetrievalRequest,
SearchIndexKnowledgeSourceParams,
)
# Create knowledge base retrieval client
kb_client = KnowledgeBaseRetrievalClient(
endpoint="<search-endpoint>",
knowledge_base_name="<knowledge-base-name>",
credential=DefaultAzureCredential(),
)
request = KnowledgeBaseRetrievalRequest(
messages=[
KnowledgeBaseMessage(
role="assistant",
content=[
KnowledgeBaseMessageTextContent(
text="You can answer questions about the Earth at night. "
"Sources have a JSON format with a ref_id that must be cited in the answer. "
"If you do not have the answer, respond with 'I do not know'."
)
],
),
KnowledgeBaseMessage(
role="user",
content=[
KnowledgeBaseMessageTextContent(
text="Why is the Phoenix nighttime street grid so sharply visible from space, "
"whereas large stretches of the interstate between midwestern cities remain comparatively dim?"
)
],
),
],
knowledge_source_params=[
SearchIndexKnowledgeSourceParams(
knowledge_source_name="earth-at-night-blob-ks",
)
],
)
result = kb_client.retrieve(request)
print(result.response[0].content[0].text)
Reference: KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest
@search-endpoint = <search-endpoint> // Example: https://my-service.search.windows.net
@search-access-token = <search-access-token> // Run: az account get-access-token --scope https://search.azure.com/.default --query accessToken -o tsv
POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}
{
"messages": [
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "You can answer questions about the Earth at night. Sources have a JSON format with a ref_id that must be cited in the answer. If you do not have the answer, respond with 'I do not know'."
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "Why is the Phoenix nighttime street grid so sharply visible from space, whereas large stretches of the interstate between midwestern cities remain comparatively dim?"
}
]
}
],
"knowledgeSourceParams": [
{
"knowledgeSourceName": "earth-at-night-blob-ks",
"kind": "searchIndex"
}
]
}
Reference: Knowledge Retrieval - Retrieve
Supply images to answer synthesis (preview)
For blob, indexed OneLake, and indexed SharePoint knowledge sources that you configure with an asset store, you can supply document-embedded images to the downstream answer-synthesis model alongside text. Set enableImageServing on the matching entry in knowledgeSourceParams to override the default that's set on the knowledge base definition. The retrieve response doesn't include dedicated fields for the individual image paths or image bytes supplied to the model.
Image serving runs only when outputMode is answerSynthesis and isn't supported for knowledge sources that configure ingestionPermissionOptions. For setup steps, the precedence table, and how to inspect image serving statistics, see Surface document-embedded images in agentic retrieval (preview).
Disable reranking for a knowledge source (preview)
Starting with the 2026-08-01-preview API version, set "resultsProcessing": "none" on a knowledgeSourceParams entry to bypass reranking for a specific knowledge source and preserve its underlying result order. You can also store resultsProcessing on the knowledge source as its default. All knowledge source kinds support this property.
The following example bypasses reranking for product-catalog-ks on one retrieve request.
using System;
using System.Linq;
using Azure.Identity;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases;
using Azure.Search.Documents.KnowledgeBases.Models;
var client = new KnowledgeBaseRetrievalClient(
new Uri("<search-endpoint>"),
"product-catalog-kb",
new DefaultAzureCredential());
var request = new KnowledgeBaseRetrievalRequest
{
IncludeActivity = true
};
request.Intents.Add(
new KnowledgeRetrievalSemanticIntent(
"Find the power adapter for SKU 88421."));
request.KnowledgeSourceParams.Add(
new SearchIndexKnowledgeSourceParams("product-catalog-ks")
{
AlwaysQuerySource = true,
IncludeReferences = true,
ResultsProcessing = KnowledgeSourceResultsProcessing.None
});
var result = await client.RetrieveAsync(request);
Console.WriteLine(
$"References with a reranker score: "
+ $"{result.Value.References.Count(x => x.RerankerScore.HasValue)}");
Reference: KnowledgeBaseRetrievalClient, SearchIndexKnowledgeSourceParams
from azure.identity import DefaultAzureCredential
from azure.search.documents.knowledgebases import (
KnowledgeBaseRetrievalClient,
)
from azure.search.documents.knowledgebases.models import (
KnowledgeBaseRetrievalRequest,
KnowledgeRetrievalSemanticIntent,
SearchIndexKnowledgeSourceParams,
)
client = KnowledgeBaseRetrievalClient(
endpoint="<search-endpoint>",
knowledge_base_name="product-catalog-kb",
credential=DefaultAzureCredential(),
)
request = KnowledgeBaseRetrievalRequest(
intents=[
KnowledgeRetrievalSemanticIntent(
search="Find the power adapter for SKU 88421."
)
],
include_activity=True,
knowledge_source_params=[
SearchIndexKnowledgeSourceParams(
knowledge_source_name="product-catalog-ks",
always_query_source=True,
include_references=True,
results_processing="none",
)
],
)
result = client.retrieve(request)
reranked_count = sum(
reference.reranker_score is not None
for reference in result.references
)
print("References with a reranker score:", reranked_count)
Reference: KnowledgeBaseRetrievalClient, SearchIndexKnowledgeSourceParams
@search-endpoint = <search-endpoint>
@search-access-token = <search-access-token> // Run: az account get-access-token --scope https://search.azure.com/.default --query accessToken -o tsv
@knowledge-base-name = product-catalog-kb
POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}
{
"intents": [
{
"type": "semantic",
"search": "Find the power adapter for SKU 88421."
}
],
"includeActivity": true,
"knowledgeSourceParams": [
{
"knowledgeSourceName": "product-catalog-ks",
"kind": "searchIndex",
"alwaysQuerySource": true,
"includeReferences": true,
"resultsProcessing": "none"
}
]
}
Reference: Knowledge Retrieval - Retrieve
Set "resultsProcessing": "rerank", or omit it when no stored default exists, to use the reranking pipeline. Foundry IQ resolves the effective value for each source in this order:
resultsProcessinginknowledgeSourceParamson the retrieve request.resultsProcessingstored on the knowledge source.rerankwhen neither property is present.
For an MCP server knowledge source, a resultsProcessing value set on an individual tool takes precedence over the request and stored values.
Tip
resultsProcessing changes how results are processed, not which sources are queried. Set alwaysQuerySource to true if the knowledge source must be queried.
When the effective value is none:
- References from the knowledge source omit
rerankerScore, and results keep their underlying order within the source's retrieval activity. - When any source bypasses reranking, Foundry IQ distributes final results across activities in round-robin order, following knowledge source declaration order. Reranked activities stay ordered by score.
- Deduplication and per-source, document, and token limits still apply, so not every retrieved result appears in the response.
Foundry IQ validates rerankerThreshold in this order:
- Search resolves
resultsProcessingfrom the retrieve request and the stored knowledge source value. - If the resolved value is
noneand the request includesrerankerThreshold, Search returns400 Bad Request. - For an MCP server tool, Search applies the tool-level
resultsProcessingvalue after validating the request.
As a result, an MCP tool setting doesn't change whether the request passes validation. A tool-level none value doesn't cause a threshold error, and a tool-level rerank value doesn't prevent an error when the request or stored value resolves to none.
To confirm which mode ran, check whether the knowledge source's references include rerankerScore. Don't rely on semanticConfigurationName, which can be null rather than omitted.
Search index behavior
For knowledge sources that target a search index, the implied query type is semantic, and there's no search mode. When reranking runs, query execution uses semanticConfigurationName. Other source settings, including searchFields and sourceDataFields, apply in both modes.
Agentic retrieval doesn't accept scoringProfile or scoringParameters inputs. An underlying index's defaultScoringProfile might influence first-stage candidate selection, but it doesn't establish an arbitrary-profile final semantic ranking contract for knowledge base retrieval. If you need recency bias for indexed knowledge sources, use freshness-aware retrieval (preview) instead of an index scoring profile.
If the index includes vector fields, you need a valid vectorizer definition so the agentic retrieval engine can vectorize query inputs. Otherwise, vector fields are ignored.
For more information, see Create an index for agentic retrieval.
Stream retrieve results
Starting with the 2026-08-01-preview API version, retrieve supports server-sent events (SSE). SSE is also available in the GA 2026-10-01 REST contract. Streaming reports activity and completed output, not token-by-token answer deltas.
Stream with 2026-10-01 REST
Use the same knowledge base, populated source, and authorized credentials as the GA JSON request. The body is unchanged; explicit Accept: text/event-stream opts in. Don't add a body streaming switch or _overload query parameter.
POST {{search-endpoint}}/knowledgebases('core-minimal-kb')/retrieve?api-version=2026-10-01
Content-Type: application/json
Accept: text/event-stream
Authorization: Bearer {{search-token}}
{
"intents": [
{ "type": "semantic", "search": "What is the return policy?" }
],
"retrievalReasoningEffort": { "kind": "minimal" },
"outputMode": "extractiveData",
"includeActivity": true,
"maxRuntimeInSeconds": 30,
"maxOutputDocuments": 3,
"maxOutputSizeInTokens": 5000,
"knowledgeSourceParams": [
{
"knowledgeSourceName": "{{knowledge-source-name}}",
"kind": "searchIndex",
"alwaysQuerySource": true,
"failOnError": true,
"includeReferences": true,
"includeReferenceSourceData": true,
"maxOutputDocuments": 50
}
]
}
Reference: Knowledge Retrieval - Retrieve
The following example shows a streamed response, with payloads shortened for readability.
event: retrieval.started
data: {"requestId":"<request-id>","outputMode":"extractiveData"}
event: activity.started
data: {"id":0,"type":"searchIndex","startedAt":"<timestamp>"}
: heartbeat
event: activity.completed
data: {"id":0,"startedAt":"<start>","completedAt":"<end>"}
event: references.completed
data: [{"type":"searchIndex","id":"0","activitySource":0}]
event: response.completed
data: {"statusCode":200,"response":{}}
Earlier-version streaming examples
The following SDK and REST examples retain their preview contract, including preview-only result-processing options.
Continue from the November preview C# client setup and create the streaming request inline.
KnowledgeBaseRetrievalRequest streamRequest = new()
{
RetrievalReasoningEffort = new KnowledgeRetrievalMinimalReasoningEffort(),
OutputMode = KnowledgeRetrievalOutputMode.ExtractiveData,
IncludeActivity = true,
MaxRuntimeInSeconds = 30,
MaxOutputDocuments = 5
};
streamRequest.Intents.Add(new KnowledgeRetrievalSemanticIntent(question));
streamRequest.KnowledgeSourceParams.Add(
new SearchIndexKnowledgeSourceParams(sourceName)
{
IncludeReferences = true,
IncludeReferenceSourceData = true,
MaxOutputDocuments = 50
});
var eventCounts = new Dictionary<string, int>();
Reference: KnowledgeBaseRetrievalClient
Count the streamed event types.
await foreach (var item in kbClient.RetrieveStreamAsync(
streamRequest, cancellationToken: CancellationToken.None))
{
eventCounts.TryGetValue(item.EventType, out var count);
eventCounts[item.EventType] = count + 1;
}
foreach (var (eventType, count) in eventCounts)
{
Console.WriteLine($"{eventType}: {count}");
}
Reference: KnowledgeBaseRetrievalClient
from collections import Counter
from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes.models import (
KnowledgeSourceResultsProcessing,
)
from azure.search.documents.knowledgebases import (
KnowledgeBaseRetrievalClient,
)
from azure.search.documents.knowledgebases.models import (
KnowledgeBaseRetrievalRequest,
KnowledgeRetrievalMinimalReasoningEffort,
KnowledgeRetrievalOutputMode,
KnowledgeRetrievalSemanticIntent,
SearchIndexKnowledgeSourceParams,
)
client = KnowledgeBaseRetrievalClient(
endpoint="<search-endpoint>",
knowledge_base_name="<knowledge-base-name>",
credential=DefaultAzureCredential(),
)
request = KnowledgeBaseRetrievalRequest(
intents=[
KnowledgeRetrievalSemanticIntent(
search="What is the return policy?"
)
],
output_mode=KnowledgeRetrievalOutputMode.EXTRACTIVE_DATA,
retrieval_reasoning_effort=KnowledgeRetrievalMinimalReasoningEffort(),
include_activity=True,
knowledge_source_params=[
SearchIndexKnowledgeSourceParams(
knowledge_source_name="<knowledge-source-name>",
results_processing=KnowledgeSourceResultsProcessing.NONE,
include_references=True,
)
],
)
event_counts = Counter()
with client.retrieve_stream(request) as stream:
for event in stream:
event_counts[event.event_type] += 1
for event_type, count in event_counts.items():
print(f"{event_type}: {count}")
Reference: KnowledgeBaseRetrievalClient
To opt in to streaming, include the Accept: text/event-stream header in a retrieve request. Without this header, the retrieve action returns its standard JSON response.
POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Content-Type: application/json
Accept: text/event-stream
Authorization: Bearer {{search-access-token}}
{
"intents": [
{
"type": "semantic",
"search": "What is the return policy?"
}
],
"outputMode": "extractiveData",
"retrievalReasoningEffort": {
"kind": "minimal"
},
"includeActivity": true,
"knowledgeSourceParams": [
{
"knowledgeSourceName": "{{knowledge-source-name}}",
"kind": "searchIndex",
"resultsProcessing": "none",
"includeReferences": true
}
]
}
Reference: Knowledge Retrieval - Retrieve
Event lifecycle
Instead of returning a single response, the service keeps one HTTP connection open with content type text/event-stream; charset=utf-8. Named events use UTF-8 encoding and LF line endings: an event: line, a data: line containing JSON, and a blank line. The service flushes each event or heartbeat comment.
A successful stream uses the following lifecycle:
| Event | When it's sent | What it contains |
|---|---|---|
retrieval.started |
First event after preparation and validation succeed and the stream opens. | requestId, knowledgeBaseName, outputMode, and reasoningEffort after defaults resolve. The field is reasoningEffort, not retrievalReasoningEffort. Preview auto reports the initial effort, not later escalation. |
activity.started |
When a query-planning, source, or model activity begins. Activities can interleave. | Direct payload with id, type, startedAt, and optional knowledgeSourceName, not an activity wrapper. Suppressed when includeActivity is false. |
activity.completed |
When that activity finishes. Correlate by id. |
The completed activity record directly, without a wrapper. Suppressed when includeActivity is false. |
answer.completed |
For each response message when outputMode is answerSynthesis. |
messageIndex and the complete message. There's no token-by-token delta event. |
references.completed |
After all references are resolved. | The event data is the full references array, without an object wrapper. |
response.completed |
The terminal event for a successful or partially successful stream. | An object with statusCode (200 or 206) and response containing the complete retrieve response. See Troubleshoot the retrieve action. |
error |
Instead of references.completed and response.completed when retrieval fails after the stream opens. |
The error and any activity records that completed before the failure. |
Events arrive in order. Each activity.started event precedes the activity.completed event with the same id, but activities can interleave. Completed activity records also include startedAt and completedAt timestamps. While the stream is idle, the server sends a : heartbeat comment approximately every 15 seconds to keep the connection open. SSE clients can ignore these comments.
Handle errors, cancellation, and fallback
Preflight failures: If request validation fails before the stream opens, such as for a malformed request body, the retrieve action returns a standard JSON error response and never opens the stream.
Midstream retrieval failures: A reported retrieval exception produces terminal
errorinstead of normal completion. Its payload containserrorand optional completedactivity. The HTTP status remains200once the stream opens. Serialization or transport failures can truncate the stream without a terminal error event.Cancellation or disconnect: Client cancellation ends the stream without a final event. Treat a stream without
response.completedas incomplete, including transport or serialization truncation.JSON fallback: With
2026-10-01or2026-11-01-preview, a missingAcceptheader or a value such asapplication/json,*/*,text/*, ortext/event-stream;q=0returns standard JSON. Opt-in requires an explicit, case-insensitivetext/event-streammember with positive quality. Explicit SSE on a version that doesn't support it returns406 Not Acceptable.
Filter search index knowledge sources at query time
When retrieving from a search index knowledge source, you can apply an OData filter at query time to narrow the results to specific documents or fields. The filter expression uses OData syntax and is passed via the filterAddOn parameter.
Filter syntax and examples
The filterAddOn parameter accepts OData filter expressions. Example patterns include:
- Metadata fields:
city eq 'Phoenix',status eq 'active' - Date ranges:
publishDate ge 2024-01-01 and publishDate le 2024-12-31 - Numeric ranges:
price ge 100 and price le 5000 - Text matching:
substringof('climate', description),indexof(title, 'urgent') ge 0 - Logical operators:
(category eq 'News' or category eq 'Analysis') and status eq 'published'
Continue from the November preview C# client and request setup. This variation requires a filterable country field with values such as Canada and United States in the backing index. Use a fresh request and a filter that matches your content. A stored base filter still combines with FilterAddOn using AND; changing this request doesn't change that stored filter.
KnowledgeBaseRetrievalRequest filteredRequest = new()
{
RetrievalReasoningEffort = new KnowledgeRetrievalMinimalReasoningEffort(),
OutputMode = KnowledgeRetrievalOutputMode.ExtractiveData,
IncludeActivity = true,
MaxRuntimeInSeconds = 30,
MaxOutputDocuments = 5
};
filteredRequest.Intents.Add(new KnowledgeRetrievalSemanticIntent(question));
filteredRequest.KnowledgeSourceParams.Add(
new SearchIndexKnowledgeSourceParams(sourceName)
{
IncludeReferences = true,
IncludeReferenceSourceData = true,
MaxOutputDocuments = 50,
FilterAddOn = "country eq 'Canada'"
});
KnowledgeBaseRetrievalResponse filteredResponse = (await kbClient.RetrieveAsync(
filteredRequest, cancellationToken: CancellationToken.None)).Value;
Console.WriteLine(
((KnowledgeBaseMessageTextContent)filteredResponse.Response[0].Content[0]).Text);
Reference: SearchIndexKnowledgeSourceParams
Continue from Retrieve with 2026-10-01 Python, using its client and imports. This example assumes a filterable id field and a document whose key is ca-leave. Replace that value with one from your source.
filtered_request = KnowledgeBaseRetrievalRequest(
intents=[KnowledgeRetrievalSemanticIntent(search=question)],
retrieval_reasoning_effort=KnowledgeRetrievalMinimalReasoningEffort(),
output_mode="extractiveData",
include_activity=True,
max_runtime_in_seconds=30,
max_output_documents=3,
max_output_size_in_tokens=6000,
knowledge_source_params=[
SearchIndexKnowledgeSourceParams(
knowledge_source_name=source_name,
include_references=True,
include_reference_source_data=True,
always_query_source=True,
fail_on_error=False,
max_output_documents=50,
filter_add_on="id eq 'ca-leave'",
)
],
)
filtered_response = kb_client.retrieve(filtered_request)
for message in filtered_response.response:
for content in message.content:
print(content.text)
Reference: SearchIndexKnowledgeSourceParams
The request filter combines with the stored base filter using AND. For example, with a filterable country field and a stored country eq 'CA' filter, a fresh request with filter_add_on="country eq 'US'" can return no matching content.
POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}
{
"messages": [
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "You are a support agent. Answer questions based on published documentation. If you don't know the answer, say so."
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "What is the process for submitting an expense report?"
}
]
}
],
"knowledgeSourceParams": [
{
"knowledgeSourceName": "internal-documentation-ks",
"kind": "searchIndex",
"filterAddOn": "status eq 'published'"
}
]
}
Multi-filter example
You can combine multiple filters to further refine results.
searchIndexParams.FilterAddOn = "(status eq 'published' or status eq 'internal') and created ge 2025-01-01";
filter_add_on="(status eq 'published' or status eq 'internal') and created ge 2025-01-01"
{
"knowledgeSourceName": "internal-documentation-ks",
"kind": "searchIndex",
"filterAddOn": "(status eq 'published' or status eq 'internal') and created ge 2025-01-01"
}
Override stored query hints at query time (preview)
Starting with the 2026-08-01-preview API version, you can override the query hints stored on a search index knowledge source for a single retrieve request by setting queryHintOverrides on its knowledgeSourceParams entry.
The override replaces the entire stored queryHints object rather than merging entry by entry, so include every hint that you want to apply. Omit queryHintOverrides to use the stored hints.
When the retrieval reasoning effort isn't minimal, an HTTP 400 response depends on the stored filter hints, not the override contents or boost kind. The service validates stored filter hints against the knowledge base model before applying queryHintOverrides. Therefore, a GPT-4o or GPT-4.1 family model rejects the request even when the override is empty or contains only boosts. Stored boosts alone don't trigger this validation. Use a compatible model or remove the stored filter hints first.
The following example replaces all stored hints with one fieldValue boost for Japanese content. The service doesn't apply any stored filter or other stored boost to this request.
using System;
using Azure.Identity;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases;
using Azure.Search.Documents.KnowledgeBases.Models;
var endpoint = new Uri("<search-endpoint>");
var retrievalClient = new KnowledgeBaseRetrievalClient(
endpoint,
"product-kb",
new DefaultAzureCredential());
var languageBoost =
new SearchIndexKnowledgeSourceFieldValueBoost(
"language",
2.0);
languageBoost.FieldValues.Add("ja-JP");
var queryHintOverrides =
new SearchIndexKnowledgeSourceQueryHints();
queryHintOverrides.Boosts.Add(languageBoost);
var request = new KnowledgeBaseRetrievalRequest
{
RetrievalReasoningEffort =
new KnowledgeRetrievalLowReasoningEffort(),
IncludeActivity = true
};
request.Messages.Add(
new KnowledgeBaseMessage([
new KnowledgeBaseMessageTextContent(
"Find Japanese service guidance for Model-X200.")
])
{
Role = "user"
});
request.KnowledgeSourceParams.Add(
new SearchIndexKnowledgeSourceParams(
"product-docs-ks")
{
QueryHintOverrides = queryHintOverrides
});
var result = await retrievalClient.RetrieveAsync(request);
Reference: KnowledgeBaseRetrievalClient, SearchIndexKnowledgeSourceParams
from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes.models import (
SearchIndexKnowledgeSourceFieldValueBoost,
SearchIndexKnowledgeSourceQueryHints,
)
from azure.search.documents.knowledgebases import (
KnowledgeBaseRetrievalClient,
)
from azure.search.documents.knowledgebases.models import (
KnowledgeBaseMessage,
KnowledgeBaseMessageTextContent,
KnowledgeBaseRetrievalRequest,
KnowledgeRetrievalLowReasoningEffort,
SearchIndexKnowledgeSourceParams,
)
retrieval_client = KnowledgeBaseRetrievalClient(
endpoint="<search-endpoint>",
credential=DefaultAzureCredential(),
knowledge_base_name="product-kb",
)
query_hint_overrides = SearchIndexKnowledgeSourceQueryHints(
boosts=[
SearchIndexKnowledgeSourceFieldValueBoost(
field="language",
field_values=["ja-JP"],
boost=2.0,
)
]
)
request = KnowledgeBaseRetrievalRequest(
messages=[
KnowledgeBaseMessage(
role="user",
content=[
KnowledgeBaseMessageTextContent(
text="Find Japanese service guidance for Model-X200."
)
],
)
],
knowledge_source_params=[
SearchIndexKnowledgeSourceParams(
knowledge_source_name="product-docs-ks",
query_hint_overrides=query_hint_overrides,
)
],
retrieval_reasoning_effort=(
KnowledgeRetrievalLowReasoningEffort()
),
include_activity=True,
)
result = retrieval_client.retrieve(request)
Reference: KnowledgeBaseRetrievalClient, SearchIndexKnowledgeSourceParams
POST {{search-endpoint}}/knowledgebases('product-kb')/retrieve?api-version=2026-11-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}
{
"messages": [{
"role": "user",
"content": [{
"type": "text",
"text": "Find Japanese service guidance for Model-X200."
}]
}],
"knowledgeSourceParams": [{
"knowledgeSourceName": "product-docs-ks",
"kind": "searchIndex",
"queryHintOverrides": {
"boosts": [{
"kind": "fieldValue",
"field": "language",
"fieldValues": ["ja-JP"],
"boost": 2.0
}]
}
}],
"retrievalReasoningEffort": {"kind": "low"},
"includeActivity": true
}
Reference: Knowledge Retrieval - Retrieve
To confirm that the service applied your override, set includeActivity on the request and inspect the returned searchIndex activity. Its queryHintProcessing object reports what the model generated. For this example, it contains a generatedBoost for the language boost, but no generatedFilter because the override replaced the stored filter hint. Because query hints are best effort, treat this activity as confirmation rather than checking for an exact expression.
{
"type": "searchIndex",
"queryHintProcessing": {
"generatedBoost": "language:(ja\\-JP)^2"
},
"searchIndexArguments": {
"queryType": "full"
}
}
For the stored definition, supported hint types, and composition with deterministic filters, see Configure query hints (preview).
Enforce permissions at query time (preview)
Changes to access permissions that you set outside of 2026-11-01-preview can take time to appear in 2026-11-01-preview retrieval results.
If your knowledge sources contain permission-protected content, pass the end user's identity on the retrieve request so that each user sees only content they're authorized to access. For search indexes with native permission filtering enabled, omitting x-ms-query-source-authorization retains only public all grants; it doesn't return unfiltered results or match storage RBAC scopes. Operation authorization is still required. Remote sources also use authorization from the retrieve request but enforce permissions at the source and might require a source-specific token and header.
ADLS Gen2 supported ACL/RBAC and standard Blob container RBAC ingestion and query filtering are generally available in REST API 2026-10-01. See Blob/ADLS permission configuration for the GA path. Other source types, Purview, and independent retrieve preview controls retain their documented availability.
Permissions enforcement has two parts:
Ingestion time: For indexed knowledge sources only, set
ingestionPermissionOptionsto ingest permission metadata alongside content.Query time: Pass the user's authorization in the header required by the knowledge source. Most sources use
x-ms-query-source-authorization. The exception is Work IQ, which usesx-ms-query-work-iq-source-authorization.
Ingestion-time configuration
The following table shows which knowledge sources require ingestion-time configuration and how each source enforces permissions.
| Knowledge source | Requires ingestionPermissionOptions |
How permissions are enforced |
|---|---|---|
| Blob or ADLS Gen2 | ✅ | Ingested RBAC scopes, ACLs, or Microsoft Purview matched against user identity. |
| OneLake | ✅ | Ingested Microsoft Purview sensitivity labels, or OneLake source permissions using indexed source locations and query-time OneLake authorization (2026-11-01-preview). |
| Indexed SharePoint | ✅ | Ingested SharePoint ACLs or Microsoft Purview sensitivity labels matched against user identity. |
| Remote SharePoint | ❌ | Copilot Retrieval API queries SharePoint directly using the user's token. |
| Fabric Data Agent | ❌ | The retrieval engine exchanges the user's token for a Microsoft Fabric–scoped token and queries the data agent on their behalf. |
| Fabric Ontology | ❌ | The retrieval engine exchanges the user's token for a Microsoft Fabric–scoped token and queries the ontology item on their behalf. |
| Work IQ | ❌ | The retrieval engine exchanges an app-audience user assertion from x-ms-query-work-iq-source-authorization for a Work IQ–scoped token. |
For generated indexes that depend on ingestionPermissionOptions, omitting that configuration doesn't ingest permission metadata. A source identity header can't compensate for missing metadata. This is separate from native permission-filtered Search indexes, whose permission fields can already exist in the index.
Query-time authorization
For non–Work IQ knowledge sources, request a delegated user access token for Search using https://search.azure.com/.default and pass it in x-ms-query-source-authorization. This token represents the user whose content access is evaluated; it doesn't need Search role assignments.
The caller's token in Authorization separately authorizes the Search operation. It can represent an application service principal or managed identity with the required Search role. Caller support doesn't establish document-permission subject support; see Query-time token roles and permission flows.
For Work IQ knowledge sources, this section doesn't apply. Use the Work IQ–specific user assertion flow described in Enforce permissions at query time.
For administrative investigations with GA elevated read, query the underlying search index directly. The 2026-10-01 retrieve REST API doesn't declare the x-ms-enable-elevated-read header.
In the .NET SDK, pass the token as the querySourceAuthorization parameter on RetrieveAsync:
using Azure;
using Azure.Identity;
using Azure.Search.Documents.KnowledgeBases;
using Azure.Search.Documents.KnowledgeBases.Models;
// Service credential: Authenticates to the search service
var serviceCredential = new DefaultAzureCredential();
// User identity token: Represents the end user for document-level permissions filtering
var userTokenContext = new Azure.Core.TokenRequestContext(
new[] { "https://search.azure.com/.default" }
);
string userToken = (await serviceCredential.GetTokenAsync(userTokenContext)).Token;
// Create the retrieval client with the service credential
var kbClient = new KnowledgeBaseRetrievalClient(
endpoint: new Uri("<search-endpoint>"),
knowledgeBaseName: "<knowledge-base-name>",
credential: serviceCredential
);
var request = new KnowledgeBaseRetrievalRequest();
request.Messages.Add(
new KnowledgeBaseMessage(
content: new[] {
new KnowledgeBaseMessageTextContent(
"What companies are in the financial sector?")
}
) { Role = "user" }
);
// Pass the user identity token for permissions filtering
var result = await kbClient.RetrieveAsync(
request, querySourceAuthorization: userToken);
var text = (result.Value.Response[0].Content[0] as KnowledgeBaseMessageTextContent)!.Text;
Console.WriteLine(text);
Reference: KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest
In the Python SDK, pass the token as the query_source_authorization parameter on retrieve:
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from azure.search.documents.knowledgebases import KnowledgeBaseRetrievalClient
from azure.search.documents.knowledgebases.models import (
KnowledgeBaseMessage, KnowledgeBaseMessageTextContent,
KnowledgeBaseRetrievalRequest,
)
# Service credential: Authenticates to the search service
service_credential = DefaultAzureCredential()
# User identity token: Represents the end user for document-level permissions filtering
user_token_provider = get_bearer_token_provider(
service_credential, "https://search.azure.com/.default")
user_token = user_token_provider()
# Create the retrieval client with the service credential
kb_client = KnowledgeBaseRetrievalClient(
endpoint="<search-endpoint>",
knowledge_base_name="<knowledge-base-name>",
credential=service_credential,
)
request = KnowledgeBaseRetrievalRequest(
messages=[
KnowledgeBaseMessage(
role="user",
content=[KnowledgeBaseMessageTextContent(
text="What companies are in the financial sector?")],
)
]
)
# Pass the user identity token for permissions filtering
result = kb_client.retrieve(
retrieval_request=request, query_source_authorization=user_token)
print(result.response[0].content[0].text)
Reference: KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest
In the REST API, include the x-ms-query-source-authorization header with the user's access token:
@search-endpoint = <search-endpoint>
@search-access-token = <search-access-token> // Service credential
@user-access-token = <user-access-token> // User identity token
POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Authorization: Bearer {{search-access-token}}
Content-Type: application/json
x-ms-query-source-authorization: {{user-access-token}}
{
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What companies are in the financial sector?"
}
]
}
]
}
Reference: Knowledge Retrieval - Retrieve
Review the response
The retrieve action returns three main components:
In 2026-10-01, these components are response, optional activity, and optional references. The outputMode selects either extractive data or model-backed answer synthesis. The following tabs retain their earlier-version examples.
- Extracted response or synthesized answer (preview) (depending on output mode)
- Activity array
- References array
Extracted response
The extracted response is a single, unified string that you typically pass to an LLM. The LLM consumes the string as grounding data and uses it to formulate a response. Your API call to the LLM includes the unified string and instructions for the model, such as whether to use the grounding exclusively or as a supplement.
The body of the response is structured in the chat message style format, and the content is serialized JSON.
"response": [
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "[{\"ref_id\":\"0\",\"title\":\"Urban Structure\",\"terms\":\"Location of Phoenix, Grid of City Blocks, Phoenix Metropolitan Area at Night\",\"content\":\"<content chunk redacted>\"}]"
}
]
}
]
Key points:
content.typehas one valid value:text.content.textis a JSON-encoded string containing the most relevant documents (or chunks) found in the search index, given the query and chat history inputs. This string is your grounding data that an LLM uses to formulate a response to the user's question.Final content is subject to per-source and request-wide document and token limits. Reranked results also use the effective source threshold.
The string starts with the reference ID of the chunk (used for citation purposes), and any fields specified in the semantic configuration of the target index. In this example, assume the semantic configuration in the target index has a "title" field, a "terms" field, and a "content" field.
Retrieve responses don't include
@search.rerankerBoostedScore.The request's token budget controls grounding output pruning. Use
maxOutputSizeInTokensin2026-10-01; the earlier preview examples usemaxOutputSize.- For documents omitted because they exceed the output budget, see Empty responses.
Activity array
The activity array reports planning, source queries, and model operations when diagnostics are included. When 206 Partial Content reflects a recorded source failure, inspect that activity's error. Other partial outcomes, such as a recoverable minimal-retrieval timeout, need separate interpretation. A 502 Bad Gateway response might provide failure details only in the top-level error.
In 2026-10-01, an activity's optional warning is a string, distinct from error. Multiple warnings are joined with newlines. For example, an activity can warn that no documents survive final output because its most relevant document is too large for the context window. A warning alone doesn't determine the HTTP status.
The activity array includes the following components:
| Section | Description |
|---|---|
| Source-specific activity | For each knowledge source included in the query, this section reports on elapsed time and which arguments were used in the query, including semantic ranker. Knowledge source types include searchIndex, azureBlob, and other supported knowledge sources. |
agenticReasoning |
This section reports on token consumption for agentic reasoning during retrieval, which depends on the specified retrieval reasoning effort (preview). |
modelQueryPlanning |
For knowledge bases that use an LLM for query planning, this section reports on the token count used for input and the token count for the subqueries. It includes a model field with a modelName field containing the public model name, not the deployment name, of the model that ran the activity. |
modelAnswerSynthesis |
For knowledge bases that use answer synthesis (preview), this section reports on the token count for formulating the answer and the token count of the answer output. It includes a model field with a modelName field containing the public model name, not the deployment name, of the model that ran the activity. |
modelWebSummarization |
For knowledge bases that use web summarization, this section reports on token consumption for summarizing web results. It includes a model field with a modelName field containing the public model name, not the deployment name, of the model that ran the activity. |
model |
For model-backed activity records, this section identifies the model used to perform the activity. This section appears only when you set includeActivity to true. |
imageServing |
For knowledge sources that have image serving (preview) enabled, this section reports imagesRetrieved, imagesSentToModel, totalImageSizeBytes, and whether indexing-time verbalizationUsed was on. Inspect verbalizationUsed and imagesSentToModel independently. A response can report verbalizationUsed as true and still send images to the downstream model. To find the number of dropped images, subtract imagesSentToModel from imagesRetrieved. |
The following example shows the activity array.
"activity": [
{
"type": "modelQueryPlanning",
"id": 0,
"inputTokens": 2302,
"outputTokens": 109,
"elapsedMs": 2396
},
{
"type": "searchIndex",
"id": 1,
"knowledgeSourceName": "demo-financials-ks",
"queryTime": "2025-11-04T19:25:23.683Z",
"count": 26,
"elapsedMs": 1137,
"searchIndexArguments": {
"search": "List of companies in the financial sector according to SEC GICS classification",
"filter": null,
"sourceDataFields": [ ],
"searchFields": [ ],
"semanticConfigurationName": "en-semantic-config"
}
},
{
"type": "searchIndex",
"id": 2,
"knowledgeSourceName": "demo-healthcare-ks",
"queryTime": "2025-11-04T19:25:24.186Z",
"count": 17,
"elapsedMs": 494,
"searchIndexArguments": {
"search": "List of companies in the financial sector according to SEC GICS classification",
"filter": null,
"sourceDataFields": [ ],
"searchFields": [ ],
"semanticConfigurationName": "en-semantic-config"
}
},
{
"type": "agenticReasoning",
"id": 3,
"retrievalReasoningEffort": {
"kind": "low"
},
"reasoningTokens": 103368
},
{
"type": "modelAnswerSynthesis",
"id": 4,
"inputTokens": 5821,
"outputTokens": 344,
"elapsedMs": 3837
}
]
References array
The optional references array describes retained grounding data, not every candidate that was found or ranked. Per-source includeReferences controls whether references are included; includeReferenceSourceData separately controls their source data. Deduplication and final pruning mean the document cap isn't a reference-count guarantee.
In 2026-10-01, indexed references can include an optional citationUrl. It points to the backing-index document, not the original file or web document. The earlier-version tabs in this article retain their original response shapes.
The references array includes the following components:
| Field | Description |
|---|---|
type |
The knowledge source type that produced the reference, such as searchIndex. |
id |
The reference ID for an item within a response. It's not the document key in the search index. Use it to provide citations. |
activitySource |
Cross-references the id of the activity entry that produced the reference, which is useful for citation linking. |
docKey |
For an indexed reference, the document key in the backing search index. |
sourceData |
The grounding data used to generate the response. For an indexed reference, fields can include an id and semantic fields, such as title, terms, and content. The shape varies by reference type. |
citationUrl (preview) |
A service-generated, read-only URL that resolves to the reference's document in the backing index. Returned only for indexed knowledge sources. To follow the URL, see Look up documents with citation URLs (preview). |
The following example shows the references array.
"references": [
{
"type": "searchIndex",
"id": "0",
"activitySource": 2,
"docKey": "policy=aug-2026",
"citationUrl": "https://my-search-service.search.windows.net/indexes/my-index/docs/policy%3Daug-2026?$select=title%2Ccontent%2Ccategory%2Cid%2Clanguage&api-version=2026-11-01-preview",
"sourceData": null
},
{
"type": "searchIndex",
"id": "1",
"activitySource": 2,
"docKey": "2",
"citationUrl": "https://my-search-service.search.windows.net/indexes/my-index/docs/2?$select=title%2Ccontent%2Ccategory%2Cid%2Clanguage&api-version=2026-11-01-preview",
"sourceData": null
}
]
Look up documents with citation URLs
Starting with the 2026-08-01-preview API version, a reference from an indexed knowledge source can include a citationUrl in the retrieve response. Use this URL to fetch the indexed fields for that reference, such as title and content, so you can render a citation preview showing where an answer came from without opening the original source document. The citationUrl is an authenticated lookup into the backing index, separate from the source docUrl and blobUrl.
Citation URLs are also supported in 2026-10-01 for searchIndex, azureBlob, indexedOneLake, indexedSharePoint, indexedSql, and file references. They don't require answer synthesis. References must be enabled for the source, and the URL can be omitted when the backing index or document key can't be resolved. Selected fields follow the resolved source selection; wildcard or absent selection doesn't add a $select restriction.
Use the returned URL unchanged, including its API version and escaping. The following examples use the 2026-11-01-preview contract.
The following example shows a sanitized citation URL.
"citationUrl": "https://my-search-service.search.windows.net/indexes/my-index/docs/policy%3Daug-2026?$select=title%2Ccontent%2Ccategory%2Cid%2Clanguage&api-version=2026-11-01-preview"
The selected fields and their order depend on the indexed source and retrieval configuration.
Important
Follow the complete URL from the response verbatim and render the returned JSON fields in your app. Don't construct, parse, or normalize the URL.
Following a citation URL is a Documents-Get operation against the backing index. It requires document-read authorization, such as Search Index Data Reader, separately from KB definition access. Native document permissions still apply; an unauthorized or missing document can return 404. The following examples authenticate the HTTP GET to the Foundry IQ service.
Azure AI Search SDK document lookup methods require the endpoint, index name, document key, selected fields, and API version as separate inputs. They don't accept an absolute citation URL. These examples use an authenticated HTTP GET to preserve the complete service-generated URL.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Azure.Core;
using Azure.Identity;
// citationUrl comes from a retrieve response
string citationUrl = "<citation-url>";
var credential = new DefaultAzureCredential();
AccessToken token = await credential.GetTokenAsync(
new TokenRequestContext(
new[] { "https://search.azure.com/.default" }));
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token.Token);
string document = await httpClient.GetStringAsync(citationUrl);
Console.WriteLine(document);
Reference: DefaultAzureCredential
import json
from urllib.request import Request, urlopen
from azure.identity import DefaultAzureCredential
# citation_url comes from a retrieve response
citation_url = "<citation-url>"
credential = DefaultAzureCredential()
token = credential.get_token("https://search.azure.com/.default")
document_request = Request(
citation_url,
headers={"Authorization": f"Bearer {token.token}"},
)
with urlopen(document_request) as response:
document = json.load(response)
print(json.dumps(document, indent=2))
Reference: DefaultAzureCredential
GET {{citation-url}}
Authorization: Bearer {{search-access-token}}
Reference: Documents - Get
The document lookup returns the selected index fields as JSON:
{
"id": "policy=aug-2026",
"title": "Escaped citation key",
"content": "Citation interoperability uses an escaped document key for the August preview.",
"category": "release",
"language": "en-US"
}
When you consume a citation URL, keep the following in mind:
Check for
citationUrlbefore you render a citation. It can be absent if the response omits references or the service can't resolve the backing index or document key.For native document-permission filtering, include the appropriate user's
x-ms-query-source-authorizationtoken on the lookup as well as an authorized service credential.Handle lookup failures in your application rather than treating the URL as a permanent or independently authorized download link.
Inspect sensitivity label metadata in the response (preview)
The same timing behavior described in Enforce permissions at query time applies here: changes to access permissions that you set outside of 2026-11-01-preview can take time to appear in 2026-11-01-preview retrieve responses.
When you query a knowledge base that ingests Microsoft Purview sensitivity labels, the retrieve response includes label metadata at two levels:
| Location | Field | Description |
|---|---|---|
| Per reference | sensitivityLabelInfo |
The sensitivity label applied to each document returned in the references array. |
| Response | metadata.responseSensitivityLabelInfo |
An aggregate label that represents the highest-priority sensitivity label across all referenced documents in the response. Useful for client-side display banners and policy enforcement. |
Microsoft Graph computes the response-level label from the per-reference labels using the Microsoft Purview label inheritance rules. Typically, the most restrictive label wins.
The following example shows a retrieve response with two referenced documents (one Confidential, one Internal) and the resulting response-level label.
{
"response": [
{
"role": "assistant",
"content": [
{ "type": "text", "text": "[ ... grounding data ... ]" }
]
}
],
"references": [
{
"type": "azureBlob",
"id": "0",
"activitySource": 1,
"docKey": "contract-2026.pdf",
"sensitivityLabelInfo": {
"labelId": "<label-guid>",
"labelName": "Confidential",
"color": "#FF0000",
"tooltip": "Confidential — Recipients can read but not forward.",
"isEncrypted": true,
"priority": 3
},
"sourceData": null
},
{
"type": "azureBlob",
"id": "1",
"activitySource": 1,
"docKey": "policy-overview.pdf",
"sensitivityLabelInfo": {
"labelId": "<label-guid>",
"labelName": "Internal",
"color": "#FFA500",
"tooltip": "For internal use only.",
"isEncrypted": false,
"priority": 1
},
"sourceData": null
}
],
"metadata": {
"responseSensitivityLabelInfo": {
"labelId": "<label-guid>",
"labelName": "Confidential",
"color": "#FF0000",
"tooltip": "Confidential — Recipients can read but not forward.",
"isEncrypted": true,
"priority": 3
}
}
}
Reference types that surface sensitivity labels
The field name and availability of label metadata depend on the knowledge source type that produced each reference.
Reference type |
Label field | Available when... |
|---|---|---|
azureBlob |
sensitivityLabelInfo |
The blob knowledge source includes sensitivityLabel in ingestionPermissionOptions. |
indexedOneLake |
sensitivityLabelInfo |
The OneLake knowledge source includes sensitivityLabel in ingestionPermissionOptions. |
indexedSharePoint |
sensitivityLabelInfo |
The SharePoint-indexed knowledge source includes sensitivityLabel in ingestionPermissionOptions. |
searchIndex |
sensitivityLabelInfo |
The underlying index has purviewEnabled set to true and a field marked with sensitivityLabelId: true. |
Display and audit recommendations
Use
sensitivityLabelInfo.labelIdto look up the full label definition through the Microsoft Graph sensitivity label APIs when you need additional properties, such as policy controls or permissions.Use
metadata.responseSensitivityLabelInfoto render a response-level sensitivity banner or apply policy controls, such as disabling copy and share, across the answer.If your knowledge source points to a chunked index, such as one populated through integrated vectorization or a custom Text Split skill, make sure the skillset projects the sensitivity label to each chunk row. Without this mapping, chunk-level references aren't filtered correctly at query time.
For auditable administrative access to labeled content, query the underlying search index with Elevated read for administrative investigations.
MCP server behavior
The MCP endpoint exposed by each knowledge base surfaces the same sensitivity label fields as the REST API. When an MCP-compatible client invokes the knowledge_base_retrieve tool, the tool result contains the same per-reference sensitivityLabelInfo and response-level metadata.responseSensitivityLabelInfo documented earlier in this section. MCP clients enforce label-aware display and policy controls based on these fields.
Retrieve action examples (preview)
The REST examples use the latest preview API, 2026-11-01-preview; SDK examples retain their existing preview package contract. They include preview-only options that aren't part of 2026-10-01. For the GA request shape, see Retrieve with 2026-10-01 REST.
- Inspect model names in activity logs
- Exclude a knowledge source from a request
- Let the service choose the reasoning effort
Inspect model names in activity logs
Set includeActivity to true to return model identity fields in model-backed activity records. Use these fields to confirm which configured model handled query planning, answer synthesis, or web summarization during a retrieve request. The following example overrides the stored result processing for the selected source on the request.
In 2026-11-01-preview, distinguish the configuration kind microsoftRetriever1 from the activity model name microsoft-retriever-1. With includeActivity: true, inspect actual model-backed planning activity rather than inferring execution from the KB definition. Microsoft Retriever 1 only plans retrieval. If an external model synthesizes the answer, inspect the separate modelAnswerSynthesis activity to identify that model.
using Azure.Identity;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases;
using Azure.Search.Documents.KnowledgeBases.Models;
var kbClient = new KnowledgeBaseRetrievalClient(
new Uri("<search-endpoint>"),
"<knowledge-base-name>",
new DefaultAzureCredential()
);
var retrievalRequest = new KnowledgeBaseRetrievalRequest();
retrievalRequest.Messages.Add(
new KnowledgeBaseMessage(
content: new[]
{
new KnowledgeBaseMessageTextContent(
"Which policy applies to returns?"
)
}
) { Role = "user" }
);
retrievalRequest.IncludeActivity = true;
retrievalRequest.KnowledgeSourceParams.Add(
new SearchIndexKnowledgeSourceParams(
"<knowledge-source-name>"
)
{
ResultsProcessing = KnowledgeSourceResultsProcessing.None
}
);
var result = await kbClient.RetrieveAsync(retrievalRequest);
foreach (var activity in result.Value.Activity)
{
KnowledgeBaseActivityRecordModel? model = activity switch
{
KnowledgeBaseModelQueryPlanningActivityRecord queryPlanning =>
queryPlanning.Model,
KnowledgeBaseModelAnswerSynthesisActivityRecord answerSynthesis =>
answerSynthesis.Model,
KnowledgeBaseModelWebSummarizationActivityRecord webSummarization =>
webSummarization.Model,
_ => null
};
if (model is not null)
{
Console.WriteLine(
$"modelName={model.ModelName}, deploymentId={model.DeploymentId}");
}
}
Reference: KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest
from azure.identity import DefaultAzureCredential
from azure.search.documents.knowledgebases import (
KnowledgeBaseRetrievalClient,
)
from azure.search.documents.knowledgebases.models import (
KnowledgeBaseMessage,
KnowledgeBaseMessageTextContent,
KnowledgeBaseModelAnswerSynthesisActivityRecord,
KnowledgeBaseModelQueryPlanningActivityRecord,
KnowledgeBaseModelWebSummarizationActivityRecord,
KnowledgeBaseRetrievalRequest,
SearchIndexKnowledgeSourceParams,
)
kb_client = KnowledgeBaseRetrievalClient(
"<search-endpoint>",
DefaultAzureCredential(),
knowledge_base_name="<knowledge-base-name>",
)
model_activity_types = (
KnowledgeBaseModelQueryPlanningActivityRecord,
KnowledgeBaseModelAnswerSynthesisActivityRecord,
KnowledgeBaseModelWebSummarizationActivityRecord,
)
request = KnowledgeBaseRetrievalRequest(
messages=[
KnowledgeBaseMessage(
role="user",
content=[
KnowledgeBaseMessageTextContent(
text="Which policy applies to returns?"
)
],
)
],
include_activity=True,
knowledge_source_params=[
SearchIndexKnowledgeSourceParams(
knowledge_source_name="<knowledge-source-name>",
results_processing="none",
)
],
)
result = kb_client.retrieve(request)
for entry in result.activity or []:
if isinstance(entry, model_activity_types) and entry.model:
print(
"modelName=", entry.model.model_name,
"deploymentId=", entry.model.deployment_id,
)
Reference: KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest
POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Authorization: Bearer {{search-access-token}}
Content-Type: application/json
{
"messages": [
{
"role": "user",
"content": [
{ "type": "text", "text": "Which policy applies to returns?" }
]
}
],
"includeActivity": true,
"knowledgeSourceParams": [
{
"knowledgeSourceName": "{{knowledge-source-name}}",
"kind": "searchIndex",
"resultsProcessing": "none"
}
]
}
Reference: Knowledge Retrieval - Retrieve
The following response excerpt shows the nested model identity:
{
"activity": [
{
"type": "modelQueryPlanning",
"id": 0,
"model": {
"modelName": "gpt-5-mini",
"deploymentId": "gpt-5-mini-deployment"
},
"inputTokens": 1842,
"outputTokens": 87,
"elapsedMs": 1923
},
{
"type": "searchIndex",
"id": 1,
"knowledgeSourceName": "operations-ks",
"count": 12,
"elapsedMs": 234
},
{
"type": "modelAnswerSynthesis",
"id": 2,
"model": {
"modelName": "gpt-5-mini",
"deploymentId": "gpt-5-mini-deployment"
},
"inputTokens": 2418,
"outputTokens": 179,
"elapsedMs": 931
}
]
}
Exclude a knowledge source from a request
Starting with the 2026-08-01-preview API version, set neverQuerySource to true for each knowledge source you want to exclude from a retrieve request. Request-time neverQuerySource overrides a stored alwaysQuerySource value for that request without changing the stored value.
This exclusion flag isn't supported in 2026-10-01. In supporting preview contracts, the same request entry can't set both neverQuerySource and alwaysQuerySource to true, and a request can't exclude every source.
The following example queries a knowledge base that contains product-docs-ks and troubleshooting-ks, excluding troubleshooting-ks from the request.
For the C# variation, continue from the November preview client setup. Supply a second existing attached search index source to exclude, different from sourceName. NeverQuerySource changes this preview request only, not the knowledge base's stored membership.
var excludedSourceName = "<second-attached-search-index-source>";
KnowledgeBaseRetrievalRequest excludedRequest = new()
{
RetrievalReasoningEffort = new KnowledgeRetrievalMinimalReasoningEffort(),
OutputMode = KnowledgeRetrievalOutputMode.ExtractiveData,
IncludeActivity = true,
MaxRuntimeInSeconds = 30,
MaxOutputDocuments = 5
};
excludedRequest.Intents.Add(new KnowledgeRetrievalSemanticIntent(question));
excludedRequest.KnowledgeSourceParams.Add(
new SearchIndexKnowledgeSourceParams(sourceName)
{
IncludeReferences = true,
IncludeReferenceSourceData = true,
MaxOutputDocuments = 50
});
excludedRequest.KnowledgeSourceParams.Add(
new SearchIndexKnowledgeSourceParams(excludedSourceName)
{
NeverQuerySource = true
});
KnowledgeBaseRetrievalResponse excludedResponse = (await kbClient.RetrieveAsync(
excludedRequest, cancellationToken: CancellationToken.None)).Value;
Console.WriteLine(
((KnowledgeBaseMessageTextContent)excludedResponse.Response[0].Content[0]).Text);
Reference: SearchIndexKnowledgeSourceParams
request = KnowledgeBaseRetrievalRequest(
messages=[
KnowledgeBaseMessage(
role="user",
content=[
KnowledgeBaseMessageTextContent(
text="Explain the official SSO provisioning steps."
)
],
)
],
knowledge_source_params=[
SearchIndexKnowledgeSourceParams(
knowledge_source_name="product-docs-ks",
),
SearchIndexKnowledgeSourceParams(
knowledge_source_name="troubleshooting-ks",
never_query_source=True,
),
],
)
result = kb_client.retrieve(request)
Reference: SearchIndexKnowledgeSourceParams
POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Authorization: Bearer {{search-access-token}}
Content-Type: application/json
{
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Explain the official SSO provisioning steps."
}
]
}
],
"knowledgeSourceParams": [
{
"knowledgeSourceName": "product-docs-ks",
"kind": "searchIndex"
},
{
"knowledgeSourceName": "troubleshooting-ks",
"kind": "searchIndex",
"neverQuerySource": true
}
]
}
Reference: Knowledge Retrieval - Retrieve
Let the service choose the reasoning effort
Set retrievalReasoningEffort.kind to auto in a retrieve request to override the knowledge base default. For more information about automatic reasoning, see Set the retrieval reasoning effort (preview).
{
"retrievalReasoningEffort": {
"kind": "auto"
}
}
Reference: Knowledge Retrieval - Retrieve
Troubleshoot the retrieve action
In 2026-10-01, distinguish partial retrieval, source failure, and server timeout. For SSE, these outcomes appear in terminal event data after the stream opens, not in its opening HTTP status.
| Status | Meaning |
|---|---|
200 OK |
Retrieval succeeded. A document can still be omitted if its content exceeds the output budget. For more information, see Empty responses. |
400 Bad Request |
The retrieve request failed validation before retrieval began. |
206 Partial Content |
Finalization records source retrieval or post-processing failures without a terminal failure policy. Ordinary minimal extractive retrieval can also return accumulated results after a server timeout. |
502 Bad Gateway |
Every retrieval activity failed and none delivered retained results, or a source marked failOnError: true has a retrieval or post-processing failure. |
504 Gateway Timeout |
In ordinary minimal retrieval, a server timeout without recoverable extractive results is a hard timeout. A client cancellation is a separate outcome. |
400 Bad Request
Use the top-level error to identify the invalid request property. Common causes include:
- A
knowledgeSourceNameinknowledgeSourceParamsisn't attached to the knowledge base, or itskinddoesn't match the attached source. - A request value is outside its supported range, or one option requires another option that isn't enabled. For example,
includeReferenceSourceDatarequiresincludeReferences. retrievalReasoningEffort.kindisauto, but the request uses a contract that doesn't support it, including2026-10-01.- The request uses
auto,low, ormedium, but the knowledge base doesn't define a supported model. - For request-time source exclusion (preview), the same entry sets both
alwaysQuerySourceandneverQuerySourcetotrue, or every attached knowledge source is excluded.
206 Partial Content
Inspect each activity entry that contains an error. A source retrieval activity identifies the failed knowledge source, and a model activity identifies the failed processing stage. The response body still contains the results that succeeded.
For source retrieval activity errors, common causes include:
- Invalid query-time input, such as a malformed
filterAddOnexpression. - Knowledge source or index configuration drift, such as a renamed field, missing semantic configuration, or invalid vectorizer.
- Missing or invalid dependency authorization, or insufficient permissions for the identity used to query the source.
- Dependency throttling, timeout, or transient availability failures.
For a model activity error, use the activity type to identify the failed processing stage. For example, a modelWebSummarization error indicates that web result summarization failed.
If your application permits partial results, process the successful results and record each failed source or model stage.
For a supported source that must be selected and must succeed, set both alwaysQuerySource and failOnError. Selection and failure policy are independent. failOnError covers recorded source retrieval and post-processing failures; it isn't a blanket policy for every model activity failure.
502 Bad Gateway
The top-level error describes one of two hard-failure paths:
- Every retrieval activity failed without retained results: A successful zero-match retrieval isn't a failed activity. Inspect the recorded failures for shared configuration, authorization, dependency, or availability issues.
- A
failOnErrorsource failed: A selected source has a recorded retrieval or post-processing failure. Other sources might have succeeded, but the source's failure policy prevents a partial result.
For common source retrieval errors, see 206 Partial Content.
A hard 502 response might omit the activity array and provide the source name and underlying failure only in the top-level error message.
Empty responses
A search can find matches that don't survive final output because their grounded content is too large for the token budget. An activity with matches but no surviving documents can include the warning string, "No results were returned because the most relevant document was too large to fit within the context window." This warning doesn't by itself assign 206 or another status. To retain more content, increase the request token budget: maxOutputSizeInTokens in GA 2026-10-01, or maxOutputSize in the earlier preview examples.
To avoid this behavior, index large source documents as smaller chunks with stable identifiers and source metadata. This applies especially to long manuals, policies, or knowledge base articles.
Call the MCP endpoint
Warning
MCP implementations are susceptible to risks, such as attacks, cascading failures, and loss of human oversight. You can mitigate these risks by vetting MCP servers for security and reliability, following Microsoft's recommended practices and industry best practices, and implementing approval mechanisms and monitoring cascading behaviors.
MCP is an open protocol that standardizes how AI applications connect to external data sources and tools.
In Foundry IQ, each knowledge base is a standalone MCP server that exposes the knowledge_base_retrieve tool. Any MCP-compatible client, including Foundry Agent Service, GitHub Copilot, Claude, and Cursor, can invoke this tool to query the knowledge base.
By using 2026-11-01-preview, the same endpoint also exposes custom knowledge base retrieval tools.
Authenticate to the MCP endpoint
Each knowledge base has an MCP endpoint at the following URL:
https://<search-service-name>.search.windows.net/knowledgebases/<knowledge-base-name>/mcp?api-version=<api-version>
The API version you specify determines what the connection returns. By using 2026-11-01-preview, the knowledge base returns synthesized answers when the underlying knowledge base is configured with a supported model and a compatible reasoning effort. By using 2026-04-01, retrieval is always minimal and extractive, and the connection returns grounding data only.
How you authenticate to this endpoint depends on your MCP client. When you use the Azure OpenAI Responses API with the knowledge_base_retrieve MCP tool, you authenticate both the Responses API call to Azure OpenAI and the MCP request to Foundry IQ. If your MCP client calls this endpoint directly, you authenticate only to Foundry IQ.
For Foundry IQ authentication, use one of the following methods:
- Pass a bearer token in the
Authorizationheader (recommended) - Pass an admin key in the
api-keyheader
Note
MCP clients configure custom headers differently. For example, Foundry Agent Service injects headers through project connections, while clients such as GitHub Copilot require headers in MCP server JSON.
Use a bearer token for MCP authentication
The recommended method for MCP authentication is a bearer token, which avoids storing sensitive keys in configuration files. The identity behind the token must have the Search Index Data Reader role assigned on the Foundry IQ service. For more information, see Connect your app to Foundry IQ using identities.
#pragma warning disable OPENAI001
using Azure.AI.OpenAI;
using Azure.Core;
using Azure.Identity;
using OpenAI.Responses;
using System;
using System.Collections.Generic;
string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!; // Example: https://<resource-name>.openai.azure.com
string mcpServerUrl = Environment.GetEnvironmentVariable("AZURE_SEARCH_MCP_ENDPOINT")!; // Example: https://<search-service-name>.search.windows.net/knowledgebases/<knowledge-base-name>/mcp?api-version=<api-version>
DefaultAzureCredential credential = new();
// Create the Azure OpenAI Responses client
AzureOpenAIClient azureClient = new(new Uri(openAiEndpoint), credential);
ResponsesClient openAIClient = azureClient.GetResponsesClient();
// Get a bearer token for Azure AI Search
string searchToken = credential.GetToken(
new TokenRequestContext(new[] { "https://search.azure.com/.default" })
).Token;
// Configure the MCP tool for knowledge base retrieval
McpTool mcpTool = ResponseTool.CreateMcpTool(
serverLabel: "search_kb",
serverUri: new Uri(mcpServerUrl),
headers: new Dictionary<string, string>
{
["Authorization"] = $"Bearer {searchToken}",
},
allowedTools: new McpToolFilter { ToolNames = { "knowledge_base_retrieve" } },
toolCallApprovalPolicy: new McpToolCallApprovalPolicy(
GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)
);
// Build the response request with the MCP tool attached
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem(
"What causes the strongest nighttime brightness patterns in this dataset?")
},
Tools = { mcpTool }
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
Reference: Use the Azure OpenAI Responses API
import os
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import AzureOpenAI
openai_endpoint = os.environ["AZURE_OPENAI_ENDPOINT"] # Example: https://<resource-name>.openai.azure.com
mcp_server_url = os.environ["AZURE_SEARCH_MCP_ENDPOINT"] # Example: https://<search-service-name>.search.windows.net/knowledgebases/<knowledge-base-name>/mcp?api-version=<api-version>
credential = DefaultAzureCredential()
# Create token providers for Azure OpenAI and Azure AI Search
openai_token_provider = get_bearer_token_provider(
credential, "https://cognitiveservices.azure.com/.default"
)
search_token_provider = get_bearer_token_provider(
credential, "https://search.azure.com/.default"
)
# Create the Azure OpenAI client
client = AzureOpenAI(
azure_endpoint=openai_endpoint,
azure_ad_token_provider=openai_token_provider,
api_version=os.environ["OPENAI_API_VERSION"], # Example: 2025-04-01-preview
)
# Create a response using the MCP tool configuration
response = client.responses.create(
model="MODEL_NAME",
input="What causes the strongest nighttime brightness patterns in this dataset?",
tools=[
{
"type": "mcp",
"server_label": "search_kb",
"server_url": mcp_server_url,
"allowed_tools": ["knowledge_base_retrieve"],
"headers": {
"Authorization": f"Bearer {search_token_provider()}"
},
"require_approval": "never",
}
],
)
print(response.output_text)
Reference: Use the Azure OpenAI Responses API
// This code snippet is currently unavailable.
Use an admin key for MCP authentication
An admin key grants full read-write access to the Foundry IQ service, so use it only in development environments or when a bearer token isn't available. For more information, see Connect to Foundry IQ using API keys.
Tip
The following example shows only the header that differs from the bearer token example. For the full setup, see Use a bearer token for MCP authentication.
#pragma warning disable OPENAI001
using OpenAI.Responses;
using System;
using System.Collections.Generic;
string mcpServerUrl = Environment.GetEnvironmentVariable("AZURE_SEARCH_MCP_ENDPOINT")!; // Example: https://<search-service-name>.search.windows.net/knowledgebases/<knowledge-base-name>/mcp?api-version=<api-version>
string searchAdminKey = Environment.GetEnvironmentVariable("AZURE_SEARCH_ADMIN_KEY")!; // Example: <search-api-key>
McpTool mcpTool = ResponseTool.CreateMcpTool(
serverLabel: "search_kb",
serverUri: new Uri(mcpServerUrl),
headers: new Dictionary<string, string> { ["api-key"] = searchAdminKey },
allowedTools: new McpToolFilter { ToolNames = { "knowledge_base_retrieve" } },
toolCallApprovalPolicy: new McpToolCallApprovalPolicy(
GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)
);
Reference: Use the Azure OpenAI Responses API
import os
mcp_server_url = os.environ["AZURE_SEARCH_MCP_ENDPOINT"] # Example: https://<search-service-name>.search.windows.net/knowledgebases/<knowledge-base-name>/mcp?api-version=<api-version>
search_admin_key = os.environ["AZURE_SEARCH_ADMIN_KEY"] # Example: <search-api-key>
tools = [
{
"type": "mcp",
"server_label": "search_kb",
"server_url": mcp_server_url,
"allowed_tools": ["knowledge_base_retrieve"],
"headers": {"api-key": search_admin_key},
"require_approval": "never",
}
]
Reference: Use the Azure OpenAI Responses API
// This code snippet is currently unavailable.
Review the MCP response
When an MCP client invokes knowledge_base_retrieve, it receives an MCP tool result instead of the retrieve action's response, activity, and references envelope. Many MCP clients surface that tool result under a top-level result object, so the payload you should expect is result.content[].
{
"result": {
"content": [
{
"type": "text",
"text": "[{\"ref_id\":\"0\",\"title\":\"Urban Structure\",\"terms\":\"Location of Phoenix, Grid of City Blocks, Phoenix Metropolitan Area at Night\",\"content\":\"<content chunk redacted>\"}]"
}
]
}
}
Key points:
result.content[]contains the MCP tool output returned by the knowledge base.result.content[].typeistext.result.content[].textcontains the retrieved grounding data as a JSON-encoded string.Unlike the retrieve action, the current MCP response doesn't return separate
activityorreferencesarrays, and it doesn't populateresourceentries for the returned content.