使用说明
第3部分:使用Python SDK进行简单的服务器设置
构建您的第一台MCP服务器
让我们用一个工具创建一个简单的演示服务器:
# server.py
from mcp.server.fastmcp import FastMCP
# Create an MCP server
mcp = FastMCP("DemoServer")
# Simple tool
@mcp.tool()
def say_hello(name: str) -> str:
"""Say hello to someone
Args:
name: The person's name to greet
"""
return f"Hello, {name}! Nice to meet you."
# Run the server
if __name__ == "__main__":
mcp.run()
运行服务器
有几种方法可以运行MCP服务器:
1.MCP Inspector开发模式
测试服务器的最简单方法是使用MCP检查器:
mcp dev server.py
这将在本地运行您的服务器,并将其连接到MCP Inspector,这是一个基于web的工具,可以让您直接与服务器的工具和资源进行交互。这非常适合测试。
2.克劳德桌面集成
如果你安装了Claude Desktop,你可以安装服务器与Claude一起使用:
mcp install server.py
这将把您的服务器添加到Claude Desktop的配置中,使其可供Claude使用。
3.直接执行(仅需要或SSE)
您也可以直接运行服务器:
# Method 1: Running as a Python script
python server.py
# Method 2: Using UV (recommended)
uv run server.py
运行MCP服务器时会发生什么?
当您运行MCP服务器时:
- 服务器使用您定义的功能(工具、资源等)进行初始化
- 它开始监听特定传输上的连接
默认情况下,MCP服务器不使用传统的web服务器端口。相反,它们使用以下任一端口:
- stdio传输:服务器通过标准输入和输出进行通信(默认为
mcp run与Claude Desktop集成) - SSE运输:用于基于HTTP的通信(显式配置时使用)
如果你想通过HTTP使用特定端口公开你的服务器,你需要修改你的服务器以使用SSE传输:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("MyServer", host="127.0.0.1", port=8050)
# Add your tools and resources here...
if __name__ == "__main__":
# Run with SSE transport on port 8000
mcp.run(transport="sse")
然后,您可以使用以下命令运行它:
python server.py
这将在以下位置启动您的服务器 http://127.0.0.1:8050.
客户端实现(带标准I/O)
现在,让我们看看如何创建一个使用我们服务器的客户端:
import asyncio
import nest_asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
# Define server parameters
server_params = StdioServerParameters(
command="python", # The command to run your server
args=["server.py"], # Arguments to the command
)
# Connect to the server
async with stdio_client(server_params) as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
# Initialize the connection
await session.initialize()
# List available tools
tools_result = await session.list_tools()
print("Available tools:")
for tool in tools_result.tools:
print(f" - {tool.name}: {tool.description}")
# Call our calculator tool
result = await session.call_tool("add", arguments={"a": 2, "b": 3})
print(f"2 + 3 = {result.content[0].text}")
if __name__ == "__main__":
asyncio.run(main())
该客户:
- 通过stdio创建与服务器的连接
- 建立MCP会话
- 列出可用工具
- 呼叫
add带参数的工具
客户端实现(带服务器发送事件)
以下是如何使用SSE连接到您的服务器:
import asyncio
import nest_asyncio
from mcp import ClientSession
from mcp.client.sse import sse_client
async def main():
# Connect to the server using SSE
async with sse_client("http://localhost:8050/sse") as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
# Initialize the connection
await session.initialize()
# List available tools
tools_result = await session.list_tools()
print("Available tools:")
for tool in tools_result.tools:
print(f" - {tool.name}: {tool.description}")
# Call our calculator tool
result = await session.call_tool("add", arguments={"a": 2, "b": 3})
print(f"2 + 3 = {result.content[0].text}")
if __name__ == "__main__":
asyncio.run(main())
客户端实现(使用流式HTTP)- 新
备注:引入了流式HTTP传输 2025年3月24日 现在是 生产部署的推荐方法取代苏格兰和南方能源运输。 在官方文档中了解更多信息.
为什么是流式HTTP?
流式HTTP比SSE有几个优点:
- 更好的性能:在高并发下提高3-5倍
- 简化架构:单个端点,而不是单独的HTTP+SSE端点
- 增强的可扩展性:更好地支持多节点部署
- 现代标准:基于当前的HTTP流媒体标准构建
工作原理:
流式HTTP使用单个HTTP端点(/mcp)它支持有状态和无状态操作模式。与需要维护单独端点的SSE不同,Streamable HTTP为所有MCP通信提供了一个统一的接口。
以下是如何使用新的Streamable HTTP传输进行连接:
import asyncio
import nest_asyncio
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
async def main():
# Connect to the server using Streamable HTTP
async with streamablehttp_client("http://localhost:8050/mcp") as (read_stream, write_stream, get_session_id):
async with ClientSession(read_stream, write_stream) as session:
# Initialize the connection
await session.initialize()
# List available tools
tools_result = await session.list_tools()
print("Available tools:")
for tool in tools_result.tools:
print(f" - {tool.name}: {tool.description}")
# Call our calculator tool
result = await session.call_tool("add", arguments={"a": 2, "b": 3})
print(f"2 + 3 = {result.content[0].text}")
if __name__ == "__main__":
asyncio.run(main())
与SSE的主要区别:
| 苏格兰和南方能源公司运输 | 可流式HTTP传输 |
|---|---|
/sse 端点 |
/mcp 端点 |
返回2个值: (read, write) |
返回3个值: (read, write, get_session_id) |
| 独立的HTTP+SSE流 | 统一的HTTP流 |
| 有利于发展 | 推荐用于生产 |
你应该选择哪种方法?
- 使用stdio 如果您的客户端和服务器将在同一进程中运行,或者您直接从客户端启动服务器进程。
- 使用流式HTTP 适用于需要最佳性能和可扩展性的生产部署。
- 使用SSE 用于开发或使用尚未支持Streamable HTTP的旧MCP实现时。
对于大多数生产后端集成 可流式传输的HTTP 该方法提供了最佳的性能和现代架构,而stdio可能更易于开发或紧密耦合的系统。
