初始化和构建 Model Context Protocol (MCP)
初始化和构建 Model Context Protocol (MCP) 本页将介绍如何开始使用 Model Context Protocol (MCP),以及构建一个基本的 MCP 结构所需的核心步骤和概念。初始化和构建 MCP 主要涉及定义和组织你的上下文数据,使其符合 MCP 的结构化要求。
初始化 MCP 结构 使用uv初始化mcp项目
1 2 3 uv init mcp-project cd mcp-projectuv add mcp[cli]
实现一个简单加法 MCP 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 from mcp.server.fastmcp import FastMCPmcp = FastMCP("AddMathServer" ) @mcp.tool( description=""" 执行两个整数的加法运算。 适用于需要精确整数相加的场景,如计算器、统计数据汇总等。 """ )def add (a:int ,b:int )->int : """ Add two integers. Args: a (int): The first integer. b (int): The second integer. Returns: int: The sum of a and b. """ return a + b if __name__ == "__main__" : mcp.run()
MVP验证 使用Roo Cline验证MCP: python运行 1 2 3 4 5 6 7 8 9 10 { "mcpServers" : { "add-server" : { "command" : "python" , "args" : [ "add-mcp/main.py" ] } } }
uv运行 1 2 3 4 5 6 7 8 9 10 11 12 13 { "mcpServers" : { "add-server" : { "command" : "uv" , "args" : [ "--directory" , "D:\\backup\\programming\\mcp\\add-mcp" , "run" , "main.py" ] } } }
注意:
使用uv运行时,需要指定目录,否则会报错
使用uv运行时,需要把loglevel设置为ERROR,否则会把INFO日志识别为报错
亮绿灯说明成功跑通
使用加法相关的prompt调用该MCP
回显:
1 2 3 4 5 6 7 8 9 10 Roo想在add-server MCP上使用工具: add 执行两个整数的加法运算。 适用于需要精确整数相加的场景,如计算器、统计数据汇总等。 参数: { "a" : 19 , "b" : 5 } 响应: 24
更多资源