Qwen3-Qwen Agent-MCP-Demo
一、Introduction
Qwen Agent is Alibaba's Qwen 3 based agent development framework, which supports tool invocation and MCP access, helping developers build AI applications with task planning capabilities; MCP is a standardized protocol for decoupling large models from external tools.Qwen-Agent .
1、Characteristics
- Strengthen tool invocation capability : Support agents to automatically invoke built-in tools (code interpreter, browser assistant) and user-defined tools, and expand function boundaries through Function Calling.
- Standardized MCP access : integrate the MCP tool access process, and only configure MCP parameters to call external tools (such as databases and APIs) to reduce development costs.
- Task planning and context memory .
- Long text processing and RAG integration : relying on the search enhancement generation mechanism, it supports 8K to 1 million tokens long document processing, and improves the efficiency of context understanding through block retrieval.
- UI front-end interaction support : provide visual interface components, optimize human-computer interaction experience, and facilitate multiple rounds of dialogue and result display.
二、Operation steps
**1、**Qwen-Agent accesses mcp-server-sqlite
1.1 Import the related package and initialize the Assistant class. At the same time, access the mcp server sqliteMCP server. The process of accessing the mcp needs to first define a tools array to store the mcp server configuration in the JSON schema format. We need to install the Cline plug-in in VsCode. In Cline, check * _ Use MCP servers _ * to ensure that the MCP Server service functions normally and that node.js has been installed. The latest version needs to be installed.
1.2 Cline connects to MCP Server. First click Cline in Vs Code, then click the small icon of MCP Servers, and then click the small icon next to the plus sign in the upper right corner. After entering the new interface, click Edit MCP Servers Configuration File. The process is shown in the following figure:
1.3 Import related configuration files at the configuration file of MCP Servers在MCP Servers
from qwen_agent.agents import Assistant
from qwen_agent.utils.output_beautify import typewriter_print
def init_agent_service():
# Configuration for the language model backend
llm_cfg = {
'model': 'qwen3-235b-a22b',
'model_server': 'dashscope',
'api_key': 'your_api_key',
'generate_cfg': {
'top_p': 0.8
}
}
# Define MCP service configuration (similar to Function Calling JSON Schema)
tools = [{
"mcpServers": {
"sqlite": {
"command": "uvx",
"args": [
"mcp-server-sqlite",
"--db-path",
"test.db"
]
}
}
}]
# Initialize the database assistant with specified capabilities
bot = Assistant(
llm=llm_cfg,
name='Database Administrator',
description='You are a database administrator capable of CRUD operations on a local database',
system_message='You act as a database assistant with SQL query execution capabilities',
function_list=tools,
)
return bot
def run_query(query=None):
# Initialize the database assistant
bot = init_agent_service()
# Setup conversation context
messages = []
messages.append({'role': 'user', 'content': [{'text': query}]})
# Track previous output for incremental printing
previous_text = ""
print('Database Administrator: ', end='', flush=True)
# Stream and print the response incrementally
for response in bot.run(messages):
previous_text = typewriter_print(response, previous_text)
if __name__ == '__main__':
# Example query: Create a students table and insert sample data
query = '帮我创建一个学生表,表名是students,包含id, name, age, gender, score字段,然后插入一条数据,id为1,name为张三,age为20,gender为男,score为95'
run_query(query)
2、Python routinepython
2.1 Define database assistant in VS Code, and construct prompt words for Qwen Agent to help us create a student table and add some data.
from qwen_agent.agents import Assistant
from qwen_agent.utils.output_beautify import typewriter_print
def init_agent_service():
"""
Initialize the database assistant service with specified configurations.
Returns:
Assistant: Configured database assistant instance.
"""
# Configuration for the large language model backend
llm_cfg = {
'model': 'qwen3-235b-a22b',
'model_server': 'dashscope',
'api_key': 'your_api_key',
'generate_cfg': {
'top_p': 0.8 # Probability threshold for nucleus sampling
}
}
# Tool configuration using MCP service schema (similar to OpenAI Function Calling)
tools = [{
"mcpServers": {
"sqlite": {
"command": "uvx",
"args": [
"mcp-server-sqlite",
"--db-path",
"test.db" # SQLite database file path
]
}
}
}]
# Initialize database assistant with LLM and toolchain
bot = Assistant(
llm=llm_cfg,
name='Database Administrator',
description='Professional database administrator capable of performing CRUD operations on local SQLite databases.',
system_message='You are a database assistant specialized in generating and executing SQL queries.',
function_list=tools, # Toolchain for database operations
)
return bot
def run_query(query: str = None) -> None:
"""
Execute a database query using the initialized assistant.
Args:
query (str): Natural language query to be translated into SQL.
"""
# Initialize database assistant
bot = init_agent_service()
# Prepare conversation messages
messages = [
{
'role': 'user',
'content': [{'text': query}]
}
]
# Track previous output for incremental display
previous_text = ""
# Print response incrementally
print('Database Administrator: ', end='', flush=True)
for response in bot.run(messages):
previous_text = typewriter_print(response, previous_text)
if __name__ == '__main__':
# Example usage: Create students table and insert sample data
sample_query = '帮我创建一个学生表,表名是students,包含id, name, age, gender, score字段,然后插入一条数据,id为1,name为张三,age为20,gender为男,score为95'
run_query(sample_query)
After the code is executed, UVX detects that some dependent libraries are not installed, and the dependencies required for automatic installation. After completing the related dependency installation, Qwen Agent detects that a student table needs to be created and data inserted in the user's request. Qwen 3 model understands the generation thinking process of the mcp server sqlite server's functions, uses sqlite-create_table to create a table, and uses sqlite-write_query to insert data.
2.2 After executing the program, it is found that there is an additional database file named 'test. db' in the local directory.
It can be seen that Qwen Agent successfully created the data table and inserted the data. The practice of using Qwen3 series of large models and Qwen Agent tools to quickly access the MCP server and develop AI Agent agent has been completed.