基于Qwen3的MCP架构的入门:学生信息管理系统完整实现Demo为例实践指南

基于Qwen3的MCP架构的入门:学生信息管理系统完整实现Demo为例实践指南

一、MCP架构原理概述

1.1 MCP基本概念

MCP(Model Context Protocol)是一种模型上下文协议,通过统一的协议让AI模型连接各种工具和数据源,类似于AI世界的”USB-C”接口。
该协议采用会话导向的JSON-RPC框架,使大语言模型能够与外部系统和数据源进行交互。 MCP服务器充当模型与本地环境或外部系统的桥梁,向CLI暴露工具和资源,实现AI驱动的交互。

1.2 MCP架构优势

  • 工具集成:Qwen3模型通过Qwen-Agent框架支持MCP集成,允许AI代理连接各种工具。
  • 数据连接:MCP通过统一协议让AI模型连接各种工具和数据源,实现无缝数据交互。
  • 扩展性:基于Node.js的MCP服务器平台集成了Qwen CLI工具,便于扩展和维护。

二、基于Qwen3的MCP架构:学生信息管理系统完整实现Demo为例

本文将以典型的场景:学生信息管理系统设计以及功能实现为例,展现MCP的使用方式和基本实践。

2.1 业务需求分析

  • 学生总成绩计算:根据学生ID计算该学生所有科目的总成绩
  • 班级平均成绩:计算指定班级各科目的平均成绩
  • 学生历年成绩:查询指定学生在不同学年的成绩变化

2.2 MCP架构设计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
┌─────────────────────────────────────────────────────────────┐
│ Qwen3 AI Model │
│ (通过MCP协议调用外部工具,处理自然语言请求) │
└───────────────────────┬─────────────────────────────────────┘
│ MCP Protocol (JSON-RPC)

┌───────────────────────────────────────────────────────────────────┐
│ MCP Server (Node.js) │
│ ┌─────────────┐ ┌────────────----─┐ ┌───────────────────────┐ │
│ │StudentTools │ │GradeTools │ │AnalyticsTools │ │
│ │- getStudent │ │- getTotalScore │ │- getClassAverage │ │
│ │- listStudents│ │- getYearlyGrades│ |- getPerformanceTrend │ │
│ └─────────────┘ └─────────────────┘ └───────────────────────┘ │
└───────────────────────┬───────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────┐
│ Data Sources (Mock Data) │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │Students.json│ │Grades.json │ │Classes.json │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────┘

2.3 数据结构设计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// students.json
[
{
"id": "S001",
"name": "张三",
"classId": "C101",
"grade": "高一",
"enrollmentYear": 2024
},
{
"id": "S002",
"name": "李四",
"classId": "C101",
"grade": "高一",
"enrollmentYear": 2024
}
]

// grades.json
[
{
"studentId": "S001",
"subject": "数学",
"score": 85,
"semester": "2024-2025-1"
},
{
"studentId": "S001",
"subject": "语文",
"score": 92,
"semester": "2024-2025-1"
},
{
"studentId": "S002",
"subject": "数学",
"score": 78,
"semester": "2024-2025-1"
}
]

// classes.json
[
{
"id": "C101",
"name": "高一(1)班",
"gradeLevel": "高一",
"studentIds": ["S001", "S002", "S003"]
}
]

三、MCP工具实现

3.1 MCP服务器搭建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
// mcp-server.js
const express = require('express');
const { createMcpServer } = require('@qwen/mcp-server');
const fs = require('fs');
const path = require('path');

// 加载数据
const students = JSON.parse(fs.readFileSync(path.join(__dirname, 'data/students.json'), 'utf8'));
const grades = JSON.parse(fs.readFileSync(path.join(__dirname, 'data/grades.json'), 'utf8'));
const classes = JSON.parse(fs.readFileSync(path.join(__dirname, 'data/classes.json'), 'utf8'));

const app = express();
app.use(express.json());

// 创建MCP服务器
const mcpServer = createMcpServer({
port: 8080,
tools: {
// 学生信息工具
getStudent: {
description: "根据学生ID获取学生详细信息",
parameters: {
type: "object",
properties: {
studentId: { type: "string", description: "学生ID,如S001" }
},
required: ["studentId"]
},
handler: async ({ studentId }) => {
const student = students.find(s => s.id === studentId);
return student || { error: "学生不存在" };
}
},

// 成绩工具
getTotalScore: {
description: "计算指定学生的总成绩",
parameters: {
type: "object",
properties: {
studentId: { type: "string", description: "学生ID" }
},
required: ["studentId"]
},
handler: async ({ studentId }) => {
const studentGrades = grades.filter(g => g.studentId === studentId);
const total = studentGrades.reduce((sum, g) => sum + g.score, 0);
const subjects = studentGrades.map(g => g.subject);

return {
studentId,
totalScore: total,
subjectCount: studentGrades.length,
subjects: subjects
};
}
},

// 班级分析工具
getClassAverage: {
description: "计算指定班级的平均成绩",
parameters: {
type: "object",
properties: {
classId: { type: "string", description: "班级ID,如C101" },
subject: { type: "string", description: "科目名称,可选" }
},
required: ["classId"]
},
handler: async ({ classId, subject }) => {
const classInfo = classes.find(c => c.id === classId);
if (!classInfo) return { error: "班级不存在" };

let filteredGrades = grades.filter(g =>
classInfo.studentIds.includes(g.studentId)
);

if (subject) {
filteredGrades = filteredGrades.filter(g => g.subject === subject);
}

if (filteredGrades.length === 0) {
return { error: "没有找到相关成绩数据" };
}

const average = filteredGrades.reduce((sum, g) => sum + g.score, 0) / filteredGrades.length;

return {
classId: classInfo.id,
className: classInfo.name,
subject: subject || "所有科目",
averageScore: parseFloat(average.toFixed(2)),
studentCount: classInfo.studentIds.length,
gradeCount: filteredGrades.length
};
}
},

// 历史成绩工具
getYearlyGrades: {
description: "获取指定学生的历年成绩",
parameters: {
type: "object",
properties: {
studentId: { type: "string", description: "学生ID" },
year: { type: "string", description: "学年,如2024-2025,可选" }
},
required: ["studentId"]
},
handler: async ({ studentId, year }) => {
let studentGrades = grades.filter(g => g.studentId === studentId);

if (year) {
studentGrades = studentGrades.filter(g => g.semester.startsWith(year));
}

// 按学年分组
const yearlyData = {};
studentGrades.forEach(grade => {
const year = grade.semester.split('-')[0];
if (!yearlyData[year]) {
yearlyData[year] = [];
}
yearlyData[year].push({
subject: grade.subject,
score: grade.score,
semester: grade.semester
});
});

return {
studentId,
yearlyGrades: yearlyData,
totalYears: Object.keys(yearlyData).length
};
}
}
}
});

// 启动服务器
mcpServer.start();
console.log('MCP服务器启动在 http://localhost:8080');

3.2 Qwen3模型集成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# qwen_agent.py
from qwen_agent import Agent
from qwen_agent.tools import MCPTool

class StudentManagementAgent(Agent):
def __init__(self):
super().__init__(
name="学生管理助手",
description="帮助查询学生信息、成绩统计和分析的AI助手",
tools=[
MCPTool(
name="mcp_student_tools",
description="MCP学生管理工具集",
mcp_server_url="http://localhost:8080"
)
]
)

def process_query(self, user_query):
"""处理用户查询,自动选择合适的MCP工具"""
system_prompt = """
你是一个专业的学生管理助手,可以帮用户查询学生信息、计算成绩、分析班级数据等。
请根据用户的问题选择合适的工具:
- 查询学生基本信息时,使用getStudent工具
- 计算学生总成绩时,使用getTotalScore工具
- 查询班级平均成绩时,使用getClassAverage工具
- 查询学生历年成绩时,使用getYearlyGrades工具

请以自然、友好的方式与用户交流,提供清晰、准确的答案。
"""

response = self.chat(
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_query}
]
)

return response

四、完整Demo演示

4.1 启动MCP服务器

1
2
3
4
5
# 安装依赖
npm install express @qwen/mcp-server

# 启动MCP服务器
node mcp-server.js

4.2 使用Qwen3进行交互

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# demo.py
from qwen_agent import Agent
from student_management_agent import StudentManagementAgent

# 初始化代理
agent = StudentManagementAgent()

# 示例1:查询学生总成绩
query1 = "张三的总成绩是多少?"
response1 = agent.process_query(query1)
print(f"用户:{query1}")
print(f"助手:{response1}\n")

# 示例2:查询班级平均成绩
query2 = "高一(1)班的数学平均成绩是多少?"
response2 = agent.process_query(query2)
print(f"用户:{query2}")
print(f"助手:{response2}\n")

# 示例3:查询学生历年成绩
query3 = "李四在2024-2025学年的成绩如何?"
response3 = agent.process_query(query3)
print(f"用户:{query3}")
print(f"助手:{response3}")

4.3 预期输出结果

1
2
3
4
5
6
7
8
9
10
用户:张三的总成绩是多少?
助手:张三同学的总成绩是177分,共参加了2门科目考试:数学(85分)、语文(92分)。

用户:高一(1)班的数学平均成绩是多少?
助手:高一(1)班的数学平均成绩是81.5分,共有2名学生参加了数学考试。

用户:李四在2024-2025学年的成绩如何?
助手:李四在2024-2025学年的成绩如下:
- 数学:78分(2024-2025-1学期)
该学年共1门科目成绩记录。

五、MCP调用流程详解

5.1 工具调用流程

  1. 用户输入:用户提出自然语言问题
  2. 意图识别:Qwen3模型分析用户意图,确定需要调用的MCP工具
  3. 参数提取:模型从用户输入中提取工具所需的参数
  4. MCP调用:通过JSON-RPC协议调用MCP服务器上的对应工具
  5. 数据处理:MCP工具处理业务逻辑,访问数据源
  6. 结果返回:工具返回结构化数据给Qwen3模型
  7. 自然语言生成:模型将结构化数据转换为自然语言回复

5.2 JSON-RPC调用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Qwen3调用getTotalScore工具的请求
{
"jsonrpc": "2.0",
"method": "getTotalScore",
"params": {
"studentId": "S001"
},
"id": "req_123456"
}

// MCP服务器返回的响应
{
"jsonrpc": "2.0",
"result": {
"studentId": "S001",
"totalScore": 177,
"subjectCount": 2,
"subjects": ["数学", "语文"]
},
"id": "req_123456"
}

六、个人最佳实践与优化建议(仅供参考⚠️)

6.1 性能优化

  • 缓存机制:对频繁查询的数据进行缓存,减少数据库访问
  • 批量处理:支持批量获取多个学生的成绩数据
  • 异步调用:对于耗时操作,采用异步处理机制

6.2 安全性考虑

  • 参数验证:严格验证工具输入参数,防止SQL注入等攻击
  • 权限控制:基于角色的访问控制,限制敏感数据访问
  • 审计日志:记录所有工具调用,便于追踪和分析

6.3 扩展性设计

  • 插件机制:支持动态加载新的MCP工具
  • 多数据源支持:可连接MySQL、MongoDB等不同数据库
  • 微服务架构:将不同功能模块拆分为独立的微服务

七、小结

通过MCP(Model Context Protocol)架构,Qwen3模型能够无缝连接外部工具和数据源,实现复杂业务逻辑的处理。 在学生信息管理系统中,MCP充当了AI模型与业务数据之间的桥梁,使AI助手能够提供精准、实时的学生成绩分析服务。 这种架构不仅提高了系统的可维护性和扩展性,还为AI应用的开发提供了标准化的工具集成方案。

MCP协议的标准化设计让开发者可以专注于业务逻辑的实现,而不必担心AI模型与外部系统的集成复杂性,真正实现了”多快好省”的AI应用开发理念。
未来,相信随着MCP生态的不断完善,这种架构模式将在更多行业赋能,彻底改变人机交互模式。

基于Qwen3的MCP架构的入门:学生信息管理系统完整实现Demo为例实践指南

https://www.wdft.com/6e5682ad.html

Author

Jaco Liu

Posted on

2025-12-27

Updated on

2026-01-26

Licensed under