Tool integration

Updated at:

High-code applications use the MCP (Model Context Protocol) to integrate various tools, which extends an AI agent's capabilities to include knowledge retrieval, external service calls, application orchestration, and data access.

Overview

On the Tools page for your high-code application, you can add and manage the agent's tools.

Adding tools in the console is for display and management only. The actual tool-calling logic must be implemented in your code using the MCP protocol.

High-code applications support the following four types of tools:

Tool type

Description

Use cases

Knowledge base

Publishing a configured knowledge base as an MCP service provides the agent with supplemental knowledge and improves response accuracy.

Scenarios that require domain-specific knowledge, such as product documentation Q&A, corporate knowledge retrieval, and automated FAQ responses.

MCP service

Enable services from the MCP Marketplace or convert existing plugins to give the agent new skills.

External service call scenarios, such as web searches, weather queries, financial data analysis, and business information lookups.

Application component

Integrate existing agents or workflows as components to provide your agent with more powerful capabilities.

Multi-agent collaboration, complex task orchestration, and reusing existing workflows in high-code applications.

Data connector

A bridge on the Model Studio platform to external data, providing stable and secure enterprise-grade data services.

External data access scenarios, such as reading tabular data, file processing, and connecting to corporate databases.

For a standard high-code application, we recommend the following project structure: tool_use_demo.zip.

my-agent-app/
├── main.py              # Entry point (required, application startup)
├── requirements.txt     # Python dependency declarations
├── tools/               # Tool function modules (grouped by feature)
│   ├── search.py        # Search tool
│   ├── knowledge.py     # Knowledge base tool
│   └── data.py          # Data connector tool
├── prompts/             # System prompt templates
│   └── system.txt
└── utils/               # General utilities
    └── helpers.py

In the requirements.txt file, we recommend pinning the version number for all dependencies using ==. Avoid using range constraints like >=. Pinning versions ensures a consistent dependency environment for every build, preventing build failures or runtime errors caused by upstream dependency updates.

Integration procedure

Integrating tools into a high-code application involves three steps:

  1. Step 1: Add a tool

    On the Tools page of your high-code application, select the required tool type (knowledge base, MCP service, application component, or data connector). Click the + button in the corresponding section, then search for and add the tool in the panel that appears.

  2. Step 2: Integrate in code

    After adding a tool, the system automatically configures the relevant environment variables. In your code, use fastmcp.Client to connect to the MCP service and call the tool. For 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:
    """Calls the web search tool through an MCP service.

    Args:
        query: The search keyword.

    Returns:
        ToolResponse with 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)])
  1. Step 3: Deploy and verify

    Redeploy the application to apply the changes. Then, verify that the tool call works correctly in the API testing or Text Chat Experience panel on the right.

Knowledge base

A knowledge base provides an agent with domain-specific knowledge to improve response accuracy. You must first publish a configured knowledge base as an MCP service before a high-code application can call it.

Add a knowledge base
  1. On the Tools page, go to the Knowledge base section and click the + button to open the Select Knowledge Base panel.
  2. In the panel, search for or browse existing knowledge bases, and click Add to associate one with your application. To create a new one, click Create Knowledge Base.
  3. Once added, the knowledge base appears in the tool list. You can switch to the Added tab to view all 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:
    """Retrieves relevant content from the product documentation knowledge base.

    Args:
        query: The user's search query.
        top_k: The number of documents to return. Default is 5.

    Returns:
        ToolResponse with retrieved documents.
    """
    api_key = os.environ.get("DASHSCOPE_API_KEY")
    # After publishing the knowledge base as an MCP service, get the corresponding 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

An MCP service enables an agent to call external skills. You can enable ready-made services from the MCP Marketplace, create a custom MCP service, or convert an existing plugin.

Add an MCP service
  1. On the Tools page, go to the MCP service section and click the + button to open the Select MCP Service panel.

  2. In the panel, choose the source of the MCP service:

    • MCP Marketplace: Browse and enable platform-provided MCP services, such as web search, financial data analysis, and business information lookups. You can filter by "Enabled" and "Not Enabled".
    • Custom MCP: Add a self-created MCP service, or use Convert from Plugin to convert an existing plugin to an MCP service.
  3. Select the desired MCP service and click Add or Enable Now to complete the 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:
    """Queries real-time information using the web search service from the MCP Marketplace.

    Args:
        query: The search keyword.

    Returns:
        ToolResponse with search results.
    """
    api_key = os.environ.get("DASHSCOPE_API_KEY")
    # After enabling the service from the MCP Marketplace, get the corresponding 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 allow you to integrate existing agents or workflows as subcomponents into your current high-code application, enabling multi-agent collaboration and complex task orchestration.

Add an application component
  1. On the Tools page, go to the Application component section and click the + button to open the Select Application Component panel.
  2. In the panel, search for or browse existing agent and workflow applications, and click Add to integrate one as a component. To create a new application, click Create Application.
  3. Once added, the application component appears in 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:
    """Calls the translation agent to translate text into the target language.

    Args:
        text: The text content to be translated.
        target_lang: The target language code, such as en, ja, or ko.

    Returns:
        ToolResponse with translation result.
    """
    api_key = os.environ.get("DASHSCOPE_API_KEY")
    # The mcpCode corresponding to the application component.
    transport = StreamableHttpTransport(
        _MCP_URL="https://dashscope.aliyuncs.com/api/v1/mcps/{application_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)])

Data connector

On the Model Studio platform, data connectors act as a bridge for agents, workflows, and knowledge bases to access external data. They provide stable, secure, enterprise-grade data services.

Data files are transmitted over the public internet. Do not transfer sensitive data through data connectors.

Add a data connector
  1. On the Tools page, go to the Data connector section and click the + button to open the Select Data Connector panel.

  2. In the panel, select a data connector. The platform provides two default connectors:

    • Default Table Connector: Used to read and process tabular data, such as CSV and Excel files.
    • Default File Connector: Used to read and process various types of file data.
  3. Click Add to complete the configuration. To create a custom connector, click Create Connector.

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 query_sales_data(start_date: str, end_date: str) -> ToolResponse:
    """Queries sales data for a specified time range using a data connector.

    Args:
        start_date: The start date, in YYYY-MM-DD format.
        end_date: The end date, in YYYY-MM-DD format.

    Returns:
        ToolResponse with query results.
    """
    api_key = os.environ.get("DASHSCOPE_API_KEY")
    # The mcpCode corresponding to the data connector.
    transport = StreamableHttpTransport(
        _MCP_URL="https://dashscope.aliyuncs.com/api/v1/mcps/{data_connector_mcpCode}/mcp",
        headers={"Authorization": f"Bearer {api_key}"},
    )
    async with Client(transport=transport) as client:
        result = await client.call_tool("query_data", {
            "start_date": start_date,
            "end_date": end_date
        })
    if result and result.content:
        text = "\n".join(
            block.text for block in result.content if hasattr(block, "text")
        )
    else:
        text = "No relevant data found."
    return ToolResponse(content=[TextBlock(type="text", text=text)])

MCP development essentials

All tools are integrated using the MCP (Model Context Protocol). The following are key points to consider when developing MCP tools.

Tool naming and description

The name and docstring of a tool function directly influence the large language model's decision to call it. They should accurately describe the tool's functionality and use cases.

# Good naming: The function name and docstring clearly describe the tool's purpose.
async def search_product_docs(query: str, top_k: int = 5) -> ToolResponse:
    """Searches the product documentation knowledge base for technical documents and how-to guides related to a user's query.
    Use this for questions about product features, configuration methods, and troubleshooting."""
    ...

# Poor naming: Too generic, making it difficult for the large language model to determine when to use it.
async def search(q: str) -> ToolResponse:
    """A search tool."""
    ...

Parameter definition

Provide clear type annotations and documentation for each parameter to help the large language model correctly extract and pass argument values.

async def get_weather(city: str, unit: str = "celsius") -> ToolResponse:
    """Gets the current weather information for a specified city.

    Args:
        city: The name of the city, such as 'Hangzhou' or 'Beijing'.
        unit: The temperature unit, either 'celsius' or 'fahrenheit'. Default is 'celsius'.
    """
    ...

Error handling

Tool functions should handle exceptions gracefully and return meaningful error messages instead of allowing unhandled exceptions to interrupt the conversation.

async def query_database(sql: str) -> ToolResponse:
    """Queries 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="The 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 you add a tool, the system automatically injects the necessary connection information into the runtime environment as environment variables. The following are commonly used system environment variables:

Environment variable

Description

DASHSCOPE_API_KEY

The Model Studio API key, used to call model services and tool APIs.

DASHSCOPE_API_HEADERS

Additional header information for API requests.

PATH

The system path variable, which includes the Python runtime path.

PYTHONPATH

The Python module search path.

TZ

The time zone setting.

You can view and edit all environment variables in the Deployment page's Environment Variables section. You can also confirm the environment variables injected for a new tool in this section.

FAQ

Q: What is the relationship between tools added in the console and tools in the code?

A: Adding a tool in the console is for declaring how the tool is called and managing its link to the application. The system also automatically injects the necessary environment variables. However, the actual tool-calling logic must be implemented in your 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 the Model Studio platform. Then, add it to your application on the Tools page. After adding it, the system automatically injects the knowledge base's connection information (such as its endpoint and ID). You then need to implement the retrieval logic in your code by calling the knowledge base's MCP service with fastmcp.Client.

Q: How do I use services from the MCP Marketplace?

A: Find the service you need in the MCP Marketplace and click Enable Now to activate it. Then, add it to your application on the Tools page. An enabled MCP service provides a standard calling interface. Use the environment variables in your code to get the connection information and call the service.

Q: Do I need to redeploy after adding a tool?

A: Yes. You must redeploy the application after adding or removing a tool for the new environment variables and tool configurations to take effect.

Q: Why is a tool's description important?

A: The large language model uses a tool's description to decide when to call it. The description should include the tool's function, use cases, and input/output details. Avoid generic descriptions like "a search tool," as the model might fail to select the tool correctly.