Skip to main content
高代码应用

Tool Integration

High-code applications integrate various tools via the MCP (Model Context Protocol) to extend AI Agent capabilities—such as knowledge retrieval, external service invocation, and application orchestration.

Overview

On the Tools page of a high-code application’s detail view, you can add and manage tools used by your Agent. While added tools are displayed for reference, their actual invocation logic must be implemented in code using the MCP protocol.
Tools added in the console serve primarily for visualization and management. The real tool-calling logic must be implemented in your code using the MCP protocol.
High-code applications support the following three types of tools:
Tool TypeDescriptionUse Cases
Knowledge BaseA configured knowledge base published as an MCP service, providing supplemental domain-specific knowledge to improve response accuracy.Product documentation Q&A, enterprise knowledge search, automated FAQ responses—any scenario requiring specialized domain knowledge.
MCP ServiceMCP services obtained either from the MCP Plaza or via plugin conversion, granting Agents new functional capabilities.Web search, weather lookup, financial data analysis, enterprise business registration queries—external service invocation scenarios.
Application ComponentExisting Agents or workflows integrated as reusable components to enhance current Agent functionality.Multi-Agent collaboration, complex task orchestration, reusing existing workflows in high-code applications.
A well-structured high-code application project is recommended to follow this layout: tool_use_demo.zip.
my-agent-app/
├── main.py              # Entry point (required)
├── requirements.txt     # Python dependency declarations
├── tools/               # Tool function modules (organized by capability)
│   ├── search.py        # Search-related tools
│   ├── knowledge.py     # Knowledge base tools
├── prompts/             # System prompt templates
│   └── system.txt
└── utils/               # Utility classes
└── helpers.py
In requirements.txt, use == to pin exact versions for all dependencies—avoid version ranges like >=. Pinning versions ensures consistent dependency environments across builds and prevents failures or runtime issues caused by upstream dependency updates.

Integration Workflow

Integrating tools into a high-code application involves three steps: Step 1: Add Tools On the Tools page of your high-code application, select the desired tool type (Knowledge Base, MCP Service, or Application Component), click the + button in its section, and search for and add the tool in the pop-up panel. Step 2: Code Integration
After adding a tool, the system automatically injects relevant environment variables. In your code, use fastmcp.Client to connect to the MCP service and invoke the tool. Example:
import os
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport

async def web_search(query: str) -> ToolResponse:
"""Invoke web search via MCP service.

Args:
query: Search keyword.

Returns:
ToolResponse containing search results.
"""
api_key = os.environ.get("DASHSCOPE_API_KEY")
transport = StreamableHttpTransport(
_MCP_URL="https://dashscope.aliyuncs.com/api/v1/mcps/{mcpCode}/mcp",
headers={"Authorization": f"Bearer {api_key}"},
)
async with Client(transport=transport) as client:
result = await client.call_tool("{toolName}", {"query": query})
if result and result.content:
text = "\n".join(
block.text for block in result.content if hasattr(block, "text")
)
else:
text = "No results found."
return ToolResponse(content=[TextBlock(type="text", text=text)])
Step 3: Deploy & Verify
Redeploy your application to activate the newly added tools. Then verify correct tool invocation using the API Test panel or the text-based chat interface on the right.

Knowledge Base

A knowledge base provides domain-specific supplementary knowledge to Agents, improving response accuracy. To be callable by a high-code application, a knowledge base must first be published as an MCP service.

Adding a Knowledge Base

On the Tools page, under the Knowledge Base section, click + to open the knowledge base selection panel. Search or browse existing knowledge bases and click Add to associate one with your application. To create a new knowledge base, click Create Knowledge Base. Once added, the knowledge base appears in the tool list. Switch to the Added tab to view all currently associated knowledge bases.

Code Integration Example

import os
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport

async def search_knowledge(query: str, top_k: int = 5) -> ToolResponse:
"""Retrieve relevant content from the product documentation knowledge base.

Args:
query: User's question.
top_k: Number of documents to return (default: 5).

Returns:
ToolResponse containing retrieved documents.
"""
api_key = os.environ.get("DASHSCOPE_API_KEY")
# After publishing the knowledge base as an MCP service, obtain its mcpCode from the Tools page
transport = StreamableHttpTransport(
_MCP_URL="https://dashscope.aliyuncs.com/api/v1/mcps/{knowledge-base-mcpCode}/mcp",
headers={"Authorization": f"Bearer {api_key}"},
)
async with Client(transport=transport) as client:
result = await client.call_tool("retrieve", {
"query": query,
"top_k": top_k
})
if result and result.content:
text = "\n".join(
block.text for block in result.content if hasattr(block, "text")
)
else:
text = "No relevant documents found."
return ToolResponse(content=[TextBlock(type="text", text=text)])

MCP Service

MCP services empower Agents with external capabilities. You can enable pre-built services from the MCP Plaza—or build custom MCP services or convert existing plugins.

Adding an MCP Service

On the Tools page, under the MCP Service section, click + to open the MCP service selection panel. Select the source of your MCP service:
  • MCP Plaza: Browse and enable platform-provided MCP services (e.g., web search, financial data analysis, enterprise registration lookup). Filter by “Enabled” or “Not Enabled.”
  • Custom MCP: Add your own MCP service, or convert an existing plugin into an MCP service using Plugin → MCP.
Select your desired MCP service and click Add or Enable Now to complete configuration.

Code Integration Example

import os
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport

async def web_search(query: str) -> ToolResponse:
"""Query real-time information using the web search service from the MCP Plaza.

Args:
query: Search keyword.

Returns:
ToolResponse containing search results.
"""
api_key = os.environ.get("DASHSCOPE_API_KEY")
# After enabling the service in the MCP Plaza, obtain its mcpCode
transport = StreamableHttpTransport(
_MCP_URL="https://dashscope.aliyuncs.com/api/v1/mcps/{mcp-service-mcpCode}/mcp",
headers={"Authorization": f"Bearer {api_key}"},
)
async with Client(transport=transport) as client:
result = await client.call_tool("web_search", {"query": query})
if result and result.content:
text = "\n".join(
block.text for block in result.content if hasattr(block, "text")
)
else:
text = "No results found."
return ToolResponse(content=[TextBlock(type="text", text=text)])

Application Component

Application components let you embed previously built Agents or workflows as sub-components into your current high-code application—enabling multi-Agent collaboration and complex task orchestration.

Adding an Application Component

On the Tools page, under the Application Component section, click + to open the component selection panel. Search or browse existing Agents and workflow applications, then click Add to integrate them as components. To create a new application, click Create Application. Once added, view all associated application components under the Added tab.

Code Integration Example

import os
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport

async def call_translation_agent(text: str, target_lang: str = "en") -> ToolResponse:
"""Call a translation Agent to translate text into the target language.

Args:
text: Text to translate.
target_lang: Target language code (e.g., `en`, `ja`, `ko`).

Returns:
ToolResponse containing translation result.
"""
api_key = os.environ.get("DASHSCOPE_API_KEY")
# Obtain the mcpCode corresponding to this application component
transport = StreamableHttpTransport(
_MCP_URL="https://dashscope.aliyuncs.com/api/v1/mcps/{app-component-mcpCode}/mcp",
headers={"Authorization": f"Bearer {api_key}"},
)
async with Client(transport=transport) as client:
result = await client.call_tool("translate", {
"text": text,
"target_lang": target_lang
})
if result and result.content:
translated = "\n".join(
block.text for block in result.content if hasattr(block, "text")
)
else:
translated = "Translation failed."
return ToolResponse(content=[TextBlock(type="text", text=translated)])

Key Considerations for MCP Protocol Development

All tools integrate via the MCP (Model Context Protocol). Below are critical best practices when developing MCP tools.

Tool Naming & Description

The function name and docstring directly influence how large models decide when to invoke the tool. Be precise and descriptive about functionality and use cases.
# Good naming — clear function name and docstring
async def search_product_docs(query: str, top_k: int = 5) -> ToolResponse:
"""Search technical documentation and user guides in the product knowledge base.
Useful for answering questions about features, configuration, and troubleshooting."""
...

# Poor naming — overly generic; model cannot infer usage context
async def search(q: str) -> ToolResponse:
"""A search tool."""
...

Parameter Definition

Provide explicit type annotations and detailed parameter descriptions to help large models correctly extract and pass arguments.
async def get_weather(city: str, unit: str = "celsius") -> ToolResponse:
"""Fetch current weather for a given city.

Args:
city: City name (e.g., 'Hangzhou', 'Beijing').
unit: Temperature unit ('celsius' or 'fahrenheit'); defaults to 'celsius'.
"""
...

Error Handling

Handle exceptions gracefully and return meaningful error messages—never let uncaught exceptions break the conversation flow.
async def query_database(sql: str) -> ToolResponse:
"""Query the business database."""
try:
api_key = os.environ.get("DASHSCOPE_API_KEY")
transport = StreamableHttpTransport(
_MCP_URL="https://dashscope.aliyuncs.com/api/v1/mcps/{mcpCode}/mcp",
headers={"Authorization": f"Bearer {api_key}"},
)
async with Client(transport=transport) as client:
result = await client.call_tool("query_db", {"sql": sql})
text = "\n".join(
block.text for block in result.content if hasattr(block, "text")
)
return ToolResponse(content=[TextBlock(type="text", text=text)])
except ConnectionError:
return ToolResponse(content=[
TextBlock(type="text", text="Data service is temporarily unavailable. Please try again later.")
])
except Exception as e:
return ToolResponse(content=[
TextBlock(type="text", text=f"Query failed: {e}")
])

Environment Variables

After adding tools, the system automatically injects connection details as environment variables. Commonly used ones include:
Environment VariableDescription
DASHSCOPE_API_KEYBailing Platform API key, required for calling model and tool APIs.
DASHSCOPE_API_HEADERSAdditional headers included in API requests.
PATHSystem path variable containing Python runtime paths.
PYTHONPATHPython module search path.
TZTimezone setting.
You can view and edit all environment variables in the Environment Variables section of the deployment page. Auto-injected variables from added tools are also visible here.

Frequently Asked Questions

Q: What is the relationship between tools added in the console and those implemented in code?
A: Console-added tools serve for visualization and managing associations—and trigger automatic injection of related environment variables. Actual tool invocation logic must be implemented in code using the MCP protocol.
Q: How do I integrate a knowledge base into a high-code application?
A: First create and configure the knowledge base on Bailing Platform, then add it to your application via the Tools page. Once added, the system injects connection details (e.g., endpoint, ID), and you implement retrieval logic in code using fastmcp.Client to call its MCP service.
Q: How do I use MCP Plaza services?
A: Locate the desired service in the MCP Plaza, click Enable Now, then add it to your application via the Tools page. Enabled services expose standardized interfaces—you retrieve connection info from environment variables and invoke them in code.
Q: Do I need to redeploy after adding or removing tools?
A: Yes. Redeployment is required for newly injected environment variables and updated tool configurations to take effect.
Q: Why is the tool’s description so important?
A: Large models rely on the description to determine when to call a tool. It should clearly state the tool’s purpose, applicable scenarios, and input/output behavior. Avoid vague descriptions like “search tool”—they hinder accurate tool selection.