Connect a Tablestore OTS Knowledge Base in AgentCore
AgentCore knowledge bases can connect to an AgentStorage knowledge base in Tablestore, which this topic calls an OTS knowledge base. In the AgentCore console, the creation entry displays this connection type as Tablestore OTS Knowledge Base. After the connection is created, the agent retrieves the knowledge chunks that are relevant to a question and uses the retrieval results as the basis for its answer.
Scope and limits
One connection per knowledge base — Each knowledge base connection corresponds to one OTS knowledge base in one AgentStorage instance. To use multiple knowledge bases, create a separate connection for each knowledge base.
Read-only retrieval — AgentCore only accesses and uses the external knowledge base. It does not copy documents, create knowledge bases, upload, modify, or delete documents, or create or maintain AgentStorage instances, knowledge bases, documents, or indexes. Add, update, and delete documents in the Tablestore console.
Public endpoint access — AgentCore accesses OTS through the public endpoint of the AgentStorage instance. Public network access must be enabled for the target instance.
Subspace pinning — You can pin one knowledge base subspace to a connection. After a subspace is pinned, all retrievals use that subspace, and the agent cannot switch to another subspace for a single retrieval. If no subspace is pinned, no subspace is used. Pin a subspace only when every retrieval through this connection must stay within it. Leave the subspace unpinned when the agent must retrieve across the whole knowledge base.
Authorization scope — Whether you pin a subspace also determines the authorization scope of the execution role. When a subspace is pinned, you can narrow the permission scope to that subspace. When no subspace is pinned, grant the permission on the knowledge base-level resource, or allow retrieval from any subspace of the knowledge base.
Settings owned by OTS — The embedding, document chunking, metadata schema, and default retrieval configuration of the knowledge base are stored and managed by OTS. AgentCore does not copy these settings.
Immutable connection settings — The connection settings cannot be modified after the connection is created. To change the instance, the knowledge base, the endpoint, the pinned subspace, or the execution role, delete the original connection and create a new one.
Prerequisites
AgentCore uses a Function Compute (FC) execution role to retrieve from OTS knowledge bases. FC generates temporary STS credentials from this role, so you do not need to provide a long-term AccessKey. The recommended default role is AliyunAgentCoreMcpServerDefaultRole. The role must have the ots:Retrieve permission on the target OTS knowledge base. Otherwise, knowledge base retrieval fails.
Quick create: If the page shows the warning "This execution role has not been created", click Quick Create Role, then click Refresh Policy. You can click View Associated Policies to verify the policies attached to the role.
Manual creation: Go to RAM to create and configure permissions: set the trusted entity type to Cloud Service and the trusted service to Function Compute, then attach a policy that grants the ots:Retrieve permission on the target OTS knowledge base; entry points: Configure Permissions in RAM, Configure Role Permissions, Configure Role Trust Policy. Alternatively, select another existing role from the drop-down list.
Create and prepare an AgentStorage knowledge base
Go to the Tablestore AgentStorage console and create an AgentStorage instance in the target region.
Create a knowledge base in the instance, and configure the embedding, metadata, retrieval method, and reranking strategy based on your business needs.
Import the knowledge documents, and then wait for parsing, chunking, and index building to complete.
On the Retrieval Test page of the knowledge base, run tests with real questions and confirm that the expected content is retrieved.
Confirm that public network access is enabled for the AgentStorage instance.
For instructions about creating instances, configuring knowledge bases, and running retrieval tests, see the AgentStorage Console Guide and Knowledge Storage Quick Start.
Prepare the execution role
AgentCore accesses OTS through a Function Compute execution role, and Function Compute generates temporary STS credentials based on that role. The connection uses the execution role and these temporary credentials throughout.
The trusted entity of the execution role must be Function Compute. If you create the role yourself, set the trusted entity type to Alibaba Cloud Service and select Function Compute as the trusted entity.
Grant the execution role the ots:Retrieve permission on the target knowledge base or the pinned subspace, and nothing more. Use a Resource Access Management (RAM) custom policy to limit the permission scope to the current instance and knowledge base instead of attaching a system policy such as AliyunOTSFullAccess.
When the connection does not pin a subspace, the retrieval scope is the entire knowledge base. The following example shows the minimum permission policy. Replace the region, the Alibaba Cloud account ID, the instance name, and the knowledge base name:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": "ots:Retrieve",
"Resource": "acs:ots:cn-hangzhou:1234567890123456:instance/my-instance/knowledgebase/product_docs_kb"
}
]
}When the connection pins a subspace, the retrieval scope is locked to that subspace, and you can further limit the resource scope to that subspace:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": "ots:Retrieve",
"Resource": "acs:ots:cn-hangzhou:1234567890123456:instance/my-instance/knowledgebase/product_docs_kb/subspace/team_a"
}
]
}To allow retrieval from any subspace of the knowledge base, replace the trailing subspace name with *, or grant the permission on the knowledge base-level resource. For the structure of resource ARNs and the authorization levels, see Configure Access Control for Knowledge and Memory Storage Services.
Create a knowledge base connection
Before you start, confirm the instance, the knowledge base, the subspace policy, and the execution role. None of these settings can be modified after the connection is created.
Log on to the AgentCore console and go to the target workspace.
In the left-side navigation pane, choose Asset Management > Knowledge Bases.
On the Knowledge Base Connection page, click Create Knowledge Base Connection.
Select Tablestore OTS Knowledge Base, and then click Connect.
Configure the basic information and the connection settings.
Configuration item
Required
Description
Knowledge Base Connection Name
Yes
The name that identifies the connection in AgentCore. Use a name that reflects the business purpose.
Description
No
Describes the knowledge base content, the applicable scope, or the usage limits, which helps you select the connection later.
AgentStorage Instance
Yes
The AgentStorage instance where the target knowledge base resides.
OTS Knowledge Base
Yes
The knowledge base to connect to in the current instance.
AgentStorage Instance Public Endpoint
No
Auto-generated from the name and the region of the selected AgentStorage instance. It cannot be modified manually, and you do not need to enter a region.
Knowledge Base Subspace
No
If you set this value, all retrievals through this connection use the specified subspace. If you leave it blank, no subspace is used. This setting cannot be modified after the connection is created.
Execution Role
Yes
The Function Compute execution role that has the
ots:Retrievepermission on the target knowledge base or the pinned subspace.Log Configuration
No
After you turn it on, select an SLS project and a Logstore to collect runtime logs and metrics.
Verify the auto-generated endpoint before you deploy. It must be the public endpoint of the target instance in the target region, not a knowledge base console address, an internal endpoint, or a URL with a path. Click Install and Deploy to submit the configuration and create the knowledge base connection, and then wait for the connection to be created.
Return to the Knowledge Base Connection list and verify that the connection status is normal.
Use the knowledge base in an agent
Harness Agent
In the AgentCore console, open the tool configuration of the target agent, and then add the Tablestore OTS knowledge base connection that you created.
Save the agent, and then publish or start it again so that the latest configuration takes effect.
Chat with the agent and ask it to use the knowledge base. For example:
Query the product knowledge base first, then summarize the deployment steps of the product, and state which document content the answer comes from.When the knowledge base connection works, the agent first retrieves from the knowledge base, answers based on the returned knowledge chunks, and identifies the document content that it used. If the agent returns a generic answer that is unrelated to the knowledge base, see The agent does not use the knowledge base. If the retrieval returns no results, see Retrieval succeeds but returns no results.
Pro-code Agent
Use SDK to call your knowledge base after installing templates.
Use MCP to connect and query OTS knowledge base:
import asyncio
import os
from agentcore import AsyncAgentCore
KNOWLEDGE_BASE_NAME = os.environ["KNOWLEDGE_BASE_NAME"]
async def main():
async with AsyncAgentCore.auto() as core:
mcp = await core.mcp(KNOWLEDGE_BASE_NAME)
result = await mcp.call_tool(
"search_ots_knowledgebase",
{"query": "How to install a product?"},
)
print(result)
asyncio.run(main())Retrieval behavior
The knowledge base connection provides retrieval through MCP. The retrieval tool is named search_ots_knowledgebase, and the JSON examples in this topic are the input parameters of this tool. When the agent answers a question, it calls the tool through MCP and supplies these parameters. To supply the parameters yourself for testing, use the tool debugging entry under Asset Management > Tool Management.
Parameter | Type | Required | Description |
| string | Yes | The question or the retrieval text. The value must be 1 to 128 characters in length. |
| object or null | No | Overrides the retrieval configuration for this request. If you omit it, pass null, or pass an empty object, OTS resolves the configuration in the priority order described after this table. |
The simplest retrieval needs only a query string of 1 to 128 characters. Start with the default retrieval configuration that you already tuned in the knowledge base, and override it per request only when the current question needs a different retrieval scope, ranking method, or metadata filter.
OTS determines the effective retrieval configuration in the following order of priority:
The
retrieval_configurationof the current retrieval request, which takes effect only for this retrieval.The knowledge base-level retrieval configuration that was saved when the OTS knowledge base was created or updated.
The OTS system default configuration.
Per-request retrieval configuration
You express the per-request retrieval configuration through retrieval_configuration, and you can specify only some of its fields. AgentCore passes only the non-empty fields that you actually provide to OTS, and does not add default values locally.
Field | Type | Description |
|
| The retrieval method. Valid values: |
| integer | The number of vector retrieval candidates. Valid values: 1 to 100. |
| integer | The number of full-text retrieval candidates. Valid values: 1 to 100. |
| string | The reranking type. Valid values: |
| integer | The number of reranked results that are finally returned. Minimum value: 1. |
| object | The RRF parameters, used together with the |
| object | The weighted fusion parameters, used together with the |
| object | The model reranking parameters, used together with the |
| object | The filter conditions based on the knowledge base metadata. |
For the applicable scenarios of the three reranking types, the field-level definitions of each sub-object, and the field types that filter supports, see Metadata filtering.
The following example shows the input parameters of search_ots_knowledgebase for a request that uses vector retrieval, full-text retrieval, and RRF reranking at the same time:
{
"query": "What are the installation steps of the product?",
"retrieval_configuration": {
"searchType": ["DENSE_VECTOR", "FULL_TEXT"],
"denseVectorSearchConfiguration": {
"numberOfResults": 20
},
"fullTextSearchConfiguration": {
"numberOfResults": 20
},
"rerankingConfiguration": {
"type": "RRF",
"numberOfResults": 10,
"rrfConfiguration": {
"denseVectorSearchWeight": 1,
"fullTextSearchWeight": 1,
"k": 60
}
}
}
}Metadata filtering
The filter fields must already be defined in the metadata schema of the knowledge base. In the filter object, a logical operator such as andAll holds an array of condition objects, and each condition object wraps a single comparison or set operator. The following example restricts the retrieval to documents whose category is Product Documentation or Operations Manual and whose score metadata is greater than or equal to 60:
{
"query": "How do I install the client?",
"retrieval_configuration": {
"filter": {
"andAll": [
{
"in": {
"key": "category",
"value": ["Product Documentation", "Operations Manual"]
}
},
{
"greaterThanOrEquals": {
"key": "score",
"value": 60
}
}
]
}
}
}Commonly used filter operators include:
Category | Operators |
Comparison |
|
Set and string |
|
Logical combination |
|
Logical combinations support nesting. For field types, retrieval methods, reranking parameters, the applicable scenarios of the three reranking types, and the field-level definitions of rrfConfiguration, weightConfiguration, and modelConfiguration with filter.
Retrieval results
A successful retrieval returns the matching knowledge chunks together with the query that ran and the name of the knowledge base that the connection is bound to. Each chunk includes its relevance score, its document and chunk identifiers, its path in Object Storage Service (OSS), its subspace, and its metadata. If nothing matches, the data array is empty.
{
"data": [
{
"content": "Step 1: Download and install the client...",
"score": 0.85,
"doc_id": "96fb386e-xxxx",
"chunk_id": 3,
"oss_key": "oss://example-bucket/docs/product-manual.pdf",
"subspace": "default",
"metadata": {
"author": "John Doe",
"category": "Product Documentation"
}
}
],
"query": "What are the installation steps of the product?",
"knowledge_base_name": "product_docs_kb"
}Field | Description |
| The array of retrieval results. |
| The original text of the chunk. |
| The relevance score. A higher score usually indicates higher relevance. |
| The ID of the document that the chunk belongs to. |
| The ID of the chunk within the document. |
| The path of the original document in OSS. |
| The subspace that the chunk belongs to. If the connection pins a subspace, all returned chunks belong to that subspace. |
| The document metadata. |
| The query text that OTS actually ran. |
| The name of the knowledge base that the current connection is bound to. |
A failed retrieval returns a tool call error. OTS service errors usually contain Code, Message, and RequestId. Keep the RequestId when you troubleshoot a problem. For the troubleshooting steps of permission errors, see An AccessDenied error or an insufficient permissions error is returned.
Manage knowledge base connections
Create, view, and manage knowledge base connections on the Asset Management > Knowledge Bases page in AgentCore.
The connection list on this page includes the knowledge base templates that you installed from Tool Marketplace. Use the Knowledge Bases entry to create and manage your own connections.
Because a knowledge base connection provides retrieval through MCP, the same connection appears under Asset Management > Tool Management > My Tools, and the Tablestore OTS Knowledge Base template appears in Tool Marketplace. Use the Tool Management entry in the following scenarios:
View the MCP details and the retrieval tool parameters. For the complete description of the parameters, see Retrieval behavior.
View the running status or the log configuration.
Debug the tool, or extend it through custom development.
The Tool Management entry shows how the connection is implemented. Before you share any of this information externally, see Security recommendations.
FAQ
AgentStorage instances or knowledge bases do not appear when you create a connection
Confirm that the console is switched to the region where the instance resides.
Confirm that the current logon account has the permissions to view the target AgentStorage instance and knowledge base.
Confirm that the instance and the knowledge base are created, and that the knowledge base is not being deleted or in an abnormal state.
The connection is created but retrieval fails
Confirm that public network access is enabled for the AgentStorage instance.
Confirm that the auto-generated endpoint corresponds to the correct instance and region. The endpoint cannot be modified after the connection is created, so delete the connection and create a new one if it does not match.
Confirm that the execution role has the
ots:Retrievepermission on the target resource.If a subspace is configured, confirm that the resource ARN in the policy matches the subspace name.
Confirm that document parsing, chunking, and index building are complete.
AccessDenied or insufficient permissions are returned
Check the RequestId in the error, and then confirm the following items in order:
Confirm that the execution role is correct.
Confirm that the trusted entity of the role is Function Compute.
Confirm that the region, the account ID, the instance name, and the knowledge base name in the access policy are correct.
When a pinned subspace is used, confirm that the policy grants the corresponding subspace resource.
Confirm that the Action of the policy includes
ots:Retrieve.
Retrieval succeeds but returns no results
Run a retrieval test with the same query in the AgentStorage console.
Temporarily remove
retrieval_configuration.filterto check whether the filter conditions are too strict.Confirm that the metadata field names, types, and values match the metadata schema.
Retry without
retrieval_configurationto rule out the effect of a per-request configuration override.Rewrite the query and add context such as the product name, terms, or the document title.
The agent does not use the knowledge base
Confirm that the knowledge base connection status is normal.
Confirm that the connection is added to the current agent.
Save and publish the agent again so that the latest configuration takes effect.
In the agent instructions, specify the purpose of the knowledge base and the scenarios that require retrieval.
Security recommendations
Grant the execution role only the
ots:Retrievepermission on the target knowledge base or the pinned subspace, and do not grantAliyunOTSFullAccessdirectly.Use the Function Compute execution role and temporary STS credentials throughout the connection. Do not configure a long-term AccessKey.
Do not provide the Function Compute public address behind the connection to external callers.
Enable logs and set a reasonable retention period, but do not record credentials in plaintext or sensitive knowledge content.
References
Console guide: the console operations for AgentStorage instances and knowledge bases.
Quick start: the getting-started process for creating knowledge bases, importing documents, and running retrieval tests.
Retrieve and rerank: the complete definitions of retrieval methods, reranking parameters, and filter fields.
Configure access control: the structure of resource ARNs and the authorization levels.