构建AI系统(三):使用Python设置您的第一个MCP服务器
off999 2025-08-01 20:08 4 浏览 0 评论
是时候动手实践了!在这一部分中,我们将设置开发环境并创建我们的第一个MCP服务器。如果您从未编写过代码,也不用担心 - 我们将一步一步来。
我们要构建什么
还记得第1部分中Maria的咖啡馆吗?我们正在创建一个反馈收集系统,该系统:
o 存储客户反馈
o 分析情感倾向(满意、中性、不满意)
o 生成总结报告
o 识别改进领域
第1步:设置您的环境
安装Python
首先,我们需要Python(3.8版本或更高):
Windows:
1. 访问python.org
2. 下载安装程序
3. 重要:勾选"Add Python to PATH"
4. 点击安装
Mac:
# 如果您有Homebrew
brew install python3
# 或者从python.org下载
Linux:
sudo apt update
sudo apt install python3 python3-pip
创建您的项目
打开您的终端(Windows上的命令提示符)并运行:
# 创建新目录
mkdir mcp-feedback-system
cd mcp-feedback-system
# 创建虚拟环境
python -m venv venv
# 激活它
# 在Windows上:
venv\Scripts\activate
# 在Mac/Linux上:
source venv/bin/activate
# 安装MCP SDK
pip install mcp
第2步:理解MCP服务器基础
MCP服务器有三个主要部分:
资源(我们有什么数据?)
# 就像菜单上的项目
- "来自客户的最近反馈"
- "本周反馈总结"
- "改进建议列表"
工具(我们能做什么?)
# 就像厨房设备
- "收集新反馈"
- "分析情感"
- "生成报告"
服务器(我们如何提供服务?)
# 就像餐厅本身
- 处理请求
- 管理连接
- 提供接口
第3步:构建我们的第一个MCP服务器
创建一个名为feedback_server.py的文件:
#!/usr/bin/env python3
"""
Customer Feedback MCP Server
A simple server for collecting and analyzing customer feedback
"""
import json
import asyncio
from datetime import datetime
from typing import Any, Dict, List
# MCP SDK imports
from mcp.server.models import InitializationOptions
from mcp.server import NotificationOptions, Server
from mcp.server.stdio import stdio_server
from mcp.types import Resource, Tool, TextContent
class FeedbackServer:
def __init__(self):
self.server = Server("customer-feedback")
self.feedback_list = []
self.setup_handlers()
def setup_handlers(self):
"""Set up all the server handlers"""
@self.server.list_resources()
async def handle_list_resources() -> List[Resource]:
"""List available resources"""
return [
Resource(
uri="feedback://recent",
name="Recent Feedback",
description="View recent customer feedback",
mimeType="application/json"
),
Resource(
uri="feedback://summary",
name="Feedback Summary",
description="Get a summary of all feedback",
mimeType="text/plain"
)
]
@self.server.read_resource()
async def handle_read_resource(uri: str) -> str:
"""Read a specific resource"""
if uri == "feedback://recent":
# Return last 5 feedback entries
recent = self.feedback_list[-5:] if self.feedback_list else []
return json.dumps(recent, indent=2)
elif uri == "feedback://summary":
# Generate summary
if not self.feedback_list:
return "No feedback collected yet."
total = len(self.feedback_list)
sentiments = {"positive": 0, "neutral": 0, "negative": 0}
for feedback in self.feedback_list:
sentiments[feedback["sentiment"]] += 1
return f"""
Feedback Summary
================
Total Feedback: {total}
Positive: {sentiments['positive']} ({sentiments['positive']/total*100:.1f}%)
Neutral: {sentiments['neutral']} ({sentiments['neutral']/total*100:.1f}%)
Negative: {sentiments['negative']} ({sentiments['negative']/total*100:.1f}%)
"""
raise ValueError(f"Unknown resource: {uri}")
@self.server.list_tools()
async def handle_list_tools() -> List[Tool]:
"""List available tools"""
return [
Tool(
name="collect_feedback",
description="Collect new customer feedback",
inputSchema={
"type": "object",
"properties": {
"customer_name": {
"type": "string",
"description": "Name of the customer"
},
"feedback": {
"type": "string",
"description": "The feedback text"
},
"rating": {
"type": "integer",
"description": "Rating from 1-5",
"minimum": 1,
"maximum": 5
}
},
"required": ["customer_name", "feedback", "rating"]
}
),
Tool(
name="analyze_sentiment",
description="Analyze sentiment of feedback text",
inputSchema={
"type": "object",
"properties": {
"text": {
"type": "string",
"description": "Text to analyze"
}
},
"required": ["text"]
}
)
]
@self.server.call_tool()
async def handle_call_tool(
name: str,
arguments: Dict[str, Any]
) -> List[TextContent]:
"""Handle tool calls"""
if name == "collect_feedback":
# Analyze sentiment based on rating
rating = arguments["rating"]
if rating >= 4:
sentiment = "positive"
elif rating == 3:
sentiment = "neutral"
else:
sentiment = "negative"
# Store feedback
feedback_entry = {
"id": len(self.feedback_list) + 1,
"timestamp": datetime.now().isoformat(),
"customer_name": arguments["customer_name"],
"feedback": arguments["feedback"],
"rating": rating,
"sentiment": sentiment
}
self.feedback_list.append(feedback_entry)
return [TextContent(
type="text",
text=f"Feedback collected successfully! ID: {feedback_entry['id']}"
)]
elif name == "analyze_sentiment":
text = arguments["text"].lower()
# Simple sentiment analysis
positive_words = ["great", "excellent", "love", "amazing", "wonderful"]
negative_words = ["bad", "terrible", "hate", "awful", "horrible"]
positive_count = sum(1 for word in positive_words if word in text)
negative_count = sum(1 for word in negative_words if word in text)
if positive_count > negative_count:
sentiment = "positive"
elif negative_count > positive_count:
sentiment = "negative"
else:
sentiment = "neutral"
return [TextContent(
type="text",
text=f"Sentiment: {sentiment}"
)]
raise ValueError(f"Unknown tool: {name}")
async def run(self):
"""Run the server"""
async with stdio_server() as (read_stream, write_stream):
await self.server.run(
read_stream,
write_stream,
InitializationOptions(
server_name="customer-feedback",
server_version="0.1.0",
capabilities=self.server.get_capabilities(
notification_options=NotificationOptions(),
experimental_capabilities={}
)
)
)
# Main entry point
async def main():
server = FeedbackServer()
await server.run()
if __name__ == "__main__":
asyncio.run(main())
第4步:测试您的服务器
让我们确保一切正常工作!首先,使脚本可执行:
# 在Mac/Linux上:
chmod +x feedback_server.py
# 在Windows上,您可以跳过这一步
现在使用MCP检查器测试它:
# 安装MCP检查器工具
pip install mcp-inspector
# 使用检查器运行您的服务器
mcp-inspector feedback_server.py
您应该看到:
o 您的服务器启动
o 可用资源(最近反馈、反馈总结)
o 可用工具(collect_feedback、analyze_sentiment)
在检查器中尝试这些命令:
1. 使用一些测试数据调用collect_feedback
2. 读取feedback://recent资源
3. 读取feedback://summary资源
第5步:理解我们构建的内容
让我们分解关键部分:
资源
我们创建了两个Agent可以读取的资源:
o feedback://recent:显示最后5个反馈条目
o feedback://summary:提供所有反馈的统计信息
工具
我们实现了两个Agent可以使用的工具:
o collect_feedback:保存新反馈,根据评分自动分析情感
o analyze_sentiment:基于关键词的简单情感分析
服务器
我们的服务器:
o 在内存中存储反馈(稍后我们将添加持久性)
o 提供标准MCP接口
o 可以被任何MCP兼容的AI Agent使用
常见问题和解决方案
"找不到Python"
o 确保Python在您的PATH中
o 尝试使用python3而不是python
"找不到模块"
o 确保您的虚拟环境已激活
o 重新安装:pip install mcp
"权限被拒绝"
o 在Mac/Linux上:使用chmod +x feedback_server.py
o 在Windows上:如果需要,以管理员身份运行
下一步是什么?
恭喜!您已经构建了您的第一个MCP服务器。在第4部分中,我们将:
o 创建一个使用我们服务器的AI Agent
o 将其连接到LLM以获得智能响应
o 构建自动化工作流
o 添加数据持久性
您的服务器现在已经准备好被AI Agent使用了。您将如何扩展它以处理您的特定用例?在评论中分享您的想法!
准备好更多内容了吗?完整的教程和额外示例可在
brandonredmond.com/learn/paths/ai-systems-intro获得。
技术要点总结
MCP服务器的核心概念
o 资源(Resources):提供数据访问的接口
o 工具(Tools):提供功能操作的接口
o 服务器(Server):协调资源和工具的统一入口
开发环境设置
1. Python环境:确保使用3.8+版本
2. 虚拟环境:隔离项目依赖
3. MCP SDK:安装必要的开发工具
代码结构分析
o 异步编程:使用async/await处理并发
o 装饰器模式:使用@self.server.list_resources()等装饰器
o 类型提示:使用typing模块提供类型安全
测试和调试
o MCP Inspector:官方测试工具
o 资源测试:验证数据访问功能
o 工具测试:验证功能操作
扩展建议
1. 数据持久化:添加数据库存储
2. 错误处理:完善异常处理机制
3. 日志记录:添加详细的日志输出
4. 配置管理:支持环境变量和配置文件
通过这个教程,您已经掌握了MCP服务器的基础知识,可以开始构建自己的AI系统了!
相关推荐
- PYTHON-简易计算器的元素介绍
-
[烟花]了解模板代码的组成importPySimpleGUIassg#1)导入库layout=[[],[],[]]#2)定义布局,确定行数window=sg.Window(...
- 如何使用Python编写一个简单的计算器程序
-
Python是一种简单易学的编程语言,非常适合初学者入门。本文将教您如何使用Python编写一个简单易用的计算器程序,帮助您快速进行基本的数学运算。无需任何高深的数学知识,只需跟随本文的步骤,即可轻松...
- 用Python打造一个简洁美观的桌面计算器
-
最近在学习PythonGUI编程,顺手用Tkinter实现了一个简易桌面计算器,功能虽然不复杂,但非常适合新手练手。如果你正在学习Python,不妨一起来看看这个项目吧!项目背景Tkint...
- 用Python制作一个带图形界面的计算器
-
大家好,今天我要带大家使用Python制作一个具有图形界面的计算器应用程序。这个项目不仅可以帮助你巩固Python编程基础,还可以让你初步体验图形化编程的乐趣。我们将使用Python的tkinter库...
- 用python怎么做最简单的桌面计算器
-
有网友问,用python怎么做一个最简单的桌面计算器。如果只强调简单,在本机运行,不考虑安全性和容错等的话,你能想到的最简单的方案是什么呢?我觉得用tkinter加eval就够简单的。现在开整。首先创...
- 说好的《Think Python 2e》更新呢!
-
编程派微信号:codingpy本周三脱更了,不过发现好多朋友在那天去访问《ThinkPython2e》的在线版,感觉有点对不住呢(实在是没抽出时间来更新)。不过还好本周六的更新可以实现,要不就放一...
- 构建AI系统(三):使用Python设置您的第一个MCP服务器
-
是时候动手实践了!在这一部分中,我们将设置开发环境并创建我们的第一个MCP服务器。如果您从未编写过代码,也不用担心-我们将一步一步来。我们要构建什么还记得第1部分中Maria的咖啡馆吗?我们正在创...
- 函数还是类?90%程序员都踩过的Python认知误区
-
那个深夜,你在调试代码,一行行检查变量类型。突然,一个TypeError错误蹦出来,你盯着那句"strobjectisnotcallable",咖啡杯在桌上留下了一圈深色...
- 《Think Python 2e》中译版更新啦!
-
【回复“python”,送你十本电子书】又到了周三,一周快过去一半了。小编按计划更新《ThinkPython2e》最新版中译。今天更新的是第五章:条件和递归。具体内容请点击阅读原文查看。其他章节的...
- Python mysql批量更新数据(兼容动态数据库字段、表名)
-
一、应用场景上篇文章我们学会了在pymysql事务中批量插入数据的复用代码,既然有了批量插入,那批量更新和批量删除的操作也少不了。二、解决思路为了解决批量删除和批量更新的问题,提出如下思路:所有更新语...
- Python Pandas 库:解锁 combine、update 和compare函数的强大功能
-
在Python的数据处理领域,Pandas库提供了丰富且实用的函数,帮助我们高效地处理和分析数据。今天,咱们就来深入探索Pandas库中四个功能独特的函数:combine、combine_fi...
- 记录Python3.7.4更新到Python.3.7.8
-
Python官网Python安装包下载下载文件名称运行后选择升级选项等待安装安装完毕打开IDLE使用Python...
- Python千叶网原图爬虫:界面化升级实践
-
该工具以Python爬虫技术为核心,实现千叶网原图的精准抓取,突破缩略图限制,直达高清资源。新增图形化界面(GUI)后,操作门槛大幅降低:-界面集成URL输入、存储路径选择、线程设置等核心功能,...
- __future__模块:Python语言版本演进的桥梁
-
摘要Python作为一门持续演进的编程语言,在版本迭代过程中不可避免地引入了破坏性变更。__future__模块作为Python兼容性管理的核心机制,为开发者提供了在旧版本中体验新特性的能力。本文深入...
- Python 集合隐藏技能:add 与 update 的致命区别,90% 开发者都踩过坑
-
add函数的使用场景及错误注意添加单一元素:正确示例:pythons={1,2}s.add(3)print(s)#{1,2,3}错误场景:试图添加可变对象(如列表)会报错(Pytho...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)