简单使用MCP
1 简介
模型上下文协议(Model Context Protocol,MCP)是由Anthropic(产品是Claude)推出的开放协议,它规范了应用程序如何向LLM提供上下文。MCP可帮助你在LLM之上构建代理和复杂的工作流。
从官网上看核心的功能点主要有Server、Resources、Tools、Prompts、Images。
Server的主要功能是通过MCP协议实现服务连接管理、协议合规性验证、消息路由等。
Resources的主要功能是向LLM传递数据,包括本地资源和远程资源等;
Tools的主要功能是向LLM提供函数调用和数据计算等;
Prompts主要功能是帮助LLM有效的与服务交互;
Images主要功能是自动化处理图像;
# 官网地址
https://modelcontextprotocol.io/introduction
# Github地址
https://github.com/modelcontextprotocol
# Python服务
https://github.com/modelcontextprotocol/python-sdk
# Java服务
https://github.com/modelcontextprotocol/java-sdk
# 第三方的MCP
# fastmcp的Github
https://github.com/jlowin/fastmcp
# fastmcp的官网
https://gofastmcp.com/getting-started/welcome
2 简单实现
注意:我没有完全调试起来,感觉MCP还需要继续发展,很多东西都不太完善。
使用pip安装mcp。
pip install "mcp[cli]"
构建mcp服务
mcp_server.py
# server.py
from mcp.server import FastMCP
# Create an MCP server
mcp = FastMCP("Demo")
# Add an addition tool
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
# Add a dynamic greeting resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting"""
return f"Hello, {name}!"
if __name__ == '__main__':
mcp.run(transport="sse", host="0.0.0.0", port=8000)
启动服务
mcp dev mcp_server.py
启动后的调试页面