Building AI Agents with Qwen3 and Qwen‑Agent: A Hands‑On Guide to MCP Integration
This tutorial walks through registering a Qwen3 API key, setting up Qwen‑Agent, creating a multi‑turn chatbot, and integrating the MCP SQLite tool to enable natural‑language driven database operations, complete with step‑by‑step code examples and screenshots.
Register Qwen3 API‑Key
Log in to the Alibaba Cloud Bailei Large Model Service platform at https://bailian.console.aliyun.com/. If a prompt to enable model services appears, click “Enable Now”.
Navigate to the “My API‑Key” page at https://bailian.console.aliyun.com/?spm=a2c4g.11186623.0.0.60907980MjFErt&tab=model#/api-key and click “Create My API‑Key”.
In the API‑Key list, click “View” to obtain the key. This key is required for calling Qwen3 models.
Quick start with Qwen‑Agent
What is Qwen‑Agent?
Qwen‑Agent is an open‑source agent development framework released by Alibaba’s Tongyi team. It is built on Qwen large language models and provides tool calling, planning, memory, long‑text retrieval‑augmented generation (RAG), and UI interaction capabilities.
Build a multi‑turn dialogue bot
Install the required packages in an Anaconda environment:
conda create -n qwen_agent python=3.12
pip install -U "qwen-agent[rag,code_interpreter,gui,mcp]"
pip install uvImport the core classes:
from qwen_agent.agents import Assistant
from qwen_agent.utils.output_beautify import typewriter_printConfigure the model service (replace 'YOUR_API_KEY' with the key obtained above):
llm_cfg = {
'model': 'qwen3-235b-a22b',
'model_server': 'dashscope',
'api_key': 'YOUR_API_KEY',
'generate_cfg': {
'top_p': 0.8
}
}Create the assistant object:
bot = Assistant(
llm=llm_cfg,
system_message='You are a helpful assistant.',
name='Smart Assistant'
)Run a conversation loop:
messages = []
while True:
query = input('
User request (type "quit" to exit): ')
if query == 'quit':
break
messages.append({'role': 'user', 'content': query})
print('AI reply:')
response_plain_text = ''
for response in bot.run(messages=messages):
response_plain_text = typewriter_print(response, response_plain_text)
messages.extend(response)Integrate MCP tools
Overview
Qwen‑Agent can connect to MCP services using the stdio development mode, where the MCP server runs as a subprocess and the agent communicates with it via standard input/output.
Connect to mcp-server-sqlite
Define the MCP configuration and create the assistant:
def init_agent_service():
llm_cfg = {
'model': 'qwen3-235b-a22b',
'model_server': 'dashscope',
'api_key': 'YOUR_API_KEY',
'generate_cfg': {'top_p': 0.8}
}
tools = [{
"mcpServers": {
"sqlite": {
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "test.db"]
}
}
}]
bot = Assistant(
llm=llm_cfg,
name='Database Administrator',
description='You can perform CRUD operations on a local database.',
system_message='You act as a database assistant.',
function_list=tools,
)
return botRun a query that creates a students table and inserts a record:
def run_query(query=None):
bot = init_agent_service()
messages = []
messages.append({'role': 'user', 'content': [{'text': query}]})
previous_text = ''
print('Database Administrator: ', end='')
for response in bot.run(messages):
previous_text = typewriter_print(response, previous_text)
if __name__ == '__main__':
query = "帮我创建一个学生表,表名是students,包含id, name, age, gender, score字段,然后插入一条数据,id为1,name为张三,age为20,gender为男,score为95"
run_query(query)The agent automatically installs missing dependencies, then calls the MCP functions sqlite-create_table and sqlite-write_query to create the table and insert the data. After execution, a test.db file appears in the working directory.
Verify the result with the standard sqlite3 tool:
import sqlite3
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
# List tables
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print('Tables:', cursor.fetchall())
# Query first table if it exists
tables = cursor.fetchall()
if tables:
table_name = 'students'
cursor.execute(f"SELECT * FROM {table_name};")
print(f'Data in {table_name}:', cursor.fetchall())
else:
print('No tables found.')
conn.close()The output confirms that the students table was created and the record was inserted.
Fun with Large Models
Master's graduate from Beijing Institute of Technology, published four top‑journal papers, previously worked as a developer at ByteDance and Alibaba. Currently researching large models at a major state‑owned enterprise. Committed to sharing concise, practical AI large‑model development experience, believing that AI large models will become as essential as PCs in the future. Let's start experimenting now!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
