MCP极简入门:超快速上手运行简单的MCP服务和MCP客户端

MCP是什么?

首先我们快速过一下MCP的基本概念,接着我们会通过一个简单的天气服务的教程,来上手学会使用MCP服务和在主机运行服务。本文根据官方教程改编。

1. MCP的基本概念

MCP(Model Context Protocol,模型上下文协议)是一个开放协议,旨在标准化应用程序如何向大型语言模型(LLM)提供上下文。它允许LLM与外部数据源和工具无缝集成,从而使AI模型能够访问实时数据并执行更复杂的任务。

官方MCP Github主页
官方文档Introduction
支持MCP特性的客户端列表

2. MCP的架构

MCP的核心组件包括:

  • 主机(Host):运行LLM的应用程序(如Claude Desktop),负责发起与MCP服务器的连接。
  • 客户端(Client):在主机应用程序内部运行,与MCP服务器建立1:1连接。
  • 服务器(Server):提供对外部数据源和工具的访问,响应客户端的请求。
  • LLM:大型语言模型,通过MCP获取上下文并生成输出。
  • 工作流程
    1. 主机启动客户端。
    2. 客户端连接到MCP服务器。
    3. 服务器提供资源、提示或工具。
    4. LLM使用这些信息生成响应。
      在这里插入图片描述

3. MCP的原语

MCP通过三种主要原语(Primitives)增强LLM的功能,理解这些原语是编写MCP的关键:

  1. 提示(Prompts):预定义的指令或模板,指导LLM如何处理输入或生成输出。
  2. 资源(Resources):提供额外上下文的结构化数据,例如文件或数据库内容。
  3. 工具(Tools):可执行的函数,允许LLM执行操作(如查询API)或检索信息。
  • 关键点:这些原语是MCP的核心,决定了服务器能为LLM提供什么能力。

MCP Server 构建一个简单的MCP服务器

在我们的示例中,使用 Claude for Desktop 作为客户端,自己编写python文件作为服务端,在 Claude Desktop 里调用server.py。

先决条件

  • 已安装 python 3.10 或更高
  • 已安装 Claude for Desktop

1. 安装uv,设置环境变量

打开 Powershell,输入如下命令:

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

打开系统高级环境变量,在 Path 将uv路径添加进去:

C:\Users\windows\.local\bin

在这里插入图片描述

重启 Powershell 。
在命令行输入 uv --version , 能返回版本信息就算安装成功了:

在这里插入图片描述

2. 创建和设置项目

打开 Powershellcd 到你想要创建项目的目录位置,如:

在这里插入图片描述

接着依次输入以下命令:

# Create a new directory for our project
uv init weather
cd weather# Create virtual environment and activate it
uv venv
.venv\Scripts\activate# Install dependencies
uv add mcp[cli] httpx# Create our server file。new-item 是powershell 命令,用于创建文件
new-item weather.py

3. 添加代码

将以下代码整个复制到 weather.py

from typing import Any  
import httpx  
from mcp.server.fastmcp import FastMCP  # Initialize FastMCP server  
mcp = FastMCP("weather")  # Constants  
NWS_API_BASE = "https://api.weather.gov"  
USER_AGENT = "weather-app/1.0"  async def make_nws_request(url: str) -> dict[str, Any] | None:  """Make a request to the NWS API with proper error handling."""  headers = {  "User-Agent": USER_AGENT,  "Accept": "application/geo+json"  }  async with httpx.AsyncClient() as client:  try:  response = await client.get(url, headers=headers, timeout=30.0)  response.raise_for_status()  return response.json()  except Exception:  return None  def format_alert(feature: dict) -> str:  """Format an alert feature into a readable string."""  props = feature["properties"]  return f"""  
Event: {props.get('event', 'Unknown')}  
Area: {props.get('areaDesc', 'Unknown')}  
Severity: {props.get('severity', 'Unknown')}  
Description: {props.get('description', 'No description available')}  
Instructions: {props.get('instruction', 'No specific instructions provided')}  
"""  @mcp.tool()  
async def get_alerts(state: str) -> str:  """Get weather alerts for a US state.  Args:        state: Two-letter US state code (e.g. CA, NY)    """    url = f"{NWS_API_BASE}/alerts/active/area/{state}"  data = await make_nws_request(url)  if not data or "features" not in data:  return "Unable to fetch alerts or no alerts found."  if not data["features"]:  return "No active alerts for this state."  alerts = [format_alert(feature) for feature in data["features"]]  return "\n---\n".join(alerts)  @mcp.tool()  
async def get_forecast(latitude: float, longitude: float) -> str:  """Get weather forecast for a location.  Args:        latitude: Latitude of the location        longitude: Longitude of the location    """    # First get the forecast grid endpoint  points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"  points_data = await make_nws_request(points_url)  if not points_data:  return "Unable to fetch forecast data for this location."  # Get the forecast URL from the points response  forecast_url = points_data["properties"]["forecast"]  forecast_data = await make_nws_request(forecast_url)  if not forecast_data:  return "Unable to fetch detailed forecast."  # Format the periods into a readable forecast  periods = forecast_data["properties"]["periods"]  forecasts = []  for period in periods[:5]:  # Only show next 5 periods  forecast = f"""  
{period['name']}:  
Temperature: {period['temperature']}°{period['temperatureUnit']}  
Wind: {period['windSpeed']} {period['windDirection']}  
Forecast: {period['detailedForecast']}  
"""  forecasts.append(forecast)  return "\n---\n".join(forecasts)  if __name__ == "__main__":  # Initialize and run the server  mcp.run(transport='stdio')

如果代码里提示依赖错误,安装对应的包就好。

4. 运行服务

打开 Claude for Desktop , 点击左上角菜单 —— File —— Settings —— Developer

点击 Edit Config ,就会在 C:\Users\windows\AppData\Roaming\Claude 目录下自动创建 claude_desktop_config.json 文件。

打开 claude_desktop_config.json , 添加如下代码:

{"mcpServers": {"weather": {"command": "uv","args": ["--directory","T:\\PythonProject\\weather","run","weather.py"]}}
}

其中路径为在上一步创建的weather目录, 使用绝对路径

这会告诉 Claude for Desktop ,

  • 我们的服务名叫 weather ,
  • 通过 uv --directory T:\\PythonProject\\weather run weather 来启动服务。

保存文件。

5. 在Claude中使用服务

打开任务管理器,将 Claude 结束任务,彻底关掉。
重新打开 Claude for Desktop

如果在Claude的对话框下看到了一把锤子,说明我们的MCP服务配置成功了。
在这里插入图片描述

点击锤子能看到:
在这里插入图片描述

在设置页显示如下:
在这里插入图片描述

下面测试服务:

在对话框输入:what’s the weather in NY

在这里插入图片描述

服务配置成功啦!

MCP Client

要使用Claude API, 需要充值购买credits
否则请求会报Error: Error code: 403 - {‘error’: {‘type’: ‘forbidden’, ‘message’: ‘Request not allowed’}}

1. 创建和设置项目

前期的步骤与上文介绍的一致,先决条件和uv的安装看 MCP Server 部分。
打开Powershell , cd 到python项目的目录下,依次输入如下命令:

# Create project directory
uv init mcp-client
cd mcp-client# Create virtual environment
uv venv# Activate virtual environment
# On Windows:
.venv\Scripts\activate
# On Unix or MacOS:
source .venv/bin/activate# Install required packages
uv add mcp anthropic python-dotenv# Create our main file
new-item client.py

2. 配置API_KEY

new-item .env

打开.env文件,复制以下代码:

ANTHROPIC_API_KEY=<your key here>

在Claude控制台创建KEY(需充值才能用),将API Key复制到.env (确保key的安全,不要分享出去!)

.env文件添加到.gitignore , 在 powershell 输入以下命令:

echo ".env" >> .gitignore

3. 添加代码

import asyncio  
from typing import Optional  
from contextlib import AsyncExitStack  from mcp import ClientSession, StdioServerParameters  
from mcp.client.stdio import stdio_client  from anthropic import Anthropic  
from dotenv import load_dotenv  load_dotenv()  # load environment variables from .env  class MCPClient:  def __init__(self):  # Initialize session and client objects  self.session: Optional[ClientSession] = None  self.exit_stack = AsyncExitStack()  self.anthropic = Anthropic()  # methods will go here  async def connect_to_server(self, server_script_path: str):  """Connect to an MCP server  Args:            server_script_path: Path to the server script (.py or .js)        """        is_python = server_script_path.endswith('.py')  is_js = server_script_path.endswith('.js')  if not (is_python or is_js):  raise ValueError("Server script must be a .py or .js file")  command = "python" if is_python else "node"  server_params = StdioServerParameters(  command=command,  args=[server_script_path],  env=None  )  stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))  self.stdio, self.write = stdio_transport  self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))  await self.session.initialize()  # List available tools  response = await self.session.list_tools()  tools = response.tools  print("\nConnected to server with tools:", [tool.name for tool in tools])  async def process_query(self, query: str) -> str:  """Process a query using Claude and available tools"""  messages = [  {  "role": "user",  "content": query  }  ]  response = await self.session.list_tools()  available_tools = [{  "name": tool.name,  "description": tool.description,  "input_schema": tool.inputSchema  } for tool in response.tools]  # Initial Claude API call  response = self.anthropic.messages.create(  model="claude-3-5-sonnet-20241022",  max_tokens=1000,  messages=messages,  tools=available_tools  )  # Process response and handle tool calls  tool_results = []  final_text = []  assistant_message_content = []  for content in response.content:  if content.type == 'text':  final_text.append(content.text)  assistant_message_content.append(content)  elif content.type == 'tool_use':  tool_name = content.name  tool_args = content.input  # Execute tool call  result = await self.session.call_tool(tool_name, tool_args)  tool_results.append({"call": tool_name, "result": result})  final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")  assistant_message_content.append(content)  messages.append({  "role": "assistant",  "content": assistant_message_content  })  messages.append({  "role": "user",  "content": [  {  "type": "tool_result",  "tool_use_id": content.id,  "content": result.content  }  ]  })  # Get next response from Claude  response = self.anthropic.messages.create(  model="claude-3-5-sonnet-20241022",  max_tokens=1000,  messages=messages,  tools=available_tools  )  final_text.append(response.content[0].text)  return "\n".join(final_text)  async def chat_loop(self):  """Run an interactive chat loop"""  print("\nMCP Client Started!")  print("Type your queries or 'quit' to exit.")  while True:  try:  query = input("\nQuery: ").strip()  if query.lower() == 'quit':  break  response = await self.process_query(query)  print("\n" + response)  except Exception as e:  print(f"\nError: {str(e)}")  async def cleanup(self):  """Clean up resources"""  await self.exit_stack.aclose()  async def main():  if len(sys.argv) < 2:  print("Usage: python client.py <path_to_server_script>")  sys.exit(1)  client = MCPClient()  try:  await client.connect_to_server(sys.argv[1])  await client.chat_loop()  finally:  await client.cleanup()  if __name__ == "__main__":  import sys  asyncio.run(main())

如果开头anthropic报错,安装anthropic就好。

4. 运行Client

这里我们使用上文创建的mcp服务weather
在powershell输入:

uv run client.py T:/PythonProject/weather/weather.py

接着,我们就可以在 Query 输入问题了。

至此,我们的第一个MCP服务端和客户端编写完成。


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/31119.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

DeepSeek进阶应用(一):结合Mermaid绘图(流程图、时序图、类图、状态图、甘特图、饼图)

&#x1f31f;前言: 在软件开发、项目管理和系统设计等领域&#xff0c;图表是表达复杂信息的有效工具。随着AI助手如DeepSeek的普及&#xff0c;我们现在可以更轻松地创建各种专业图表。 名人说&#xff1a;博观而约取&#xff0c;厚积而薄发。——苏轼《稼说送张琥》 创作者&…

海康线扫相机平场矫正教程

0、平场矫正前的准备确认 1、白纸准备 确保视野中有一张平整且无折痕的白纸&#xff0c;使其完全铺满相机的整个视野。 2、行高设置 将行高参数设定为 2048。 3、灰度值控制 相机端图像的灰度值应维持在 120 - 180 这个区间内。同时&#xff0c;最亮像素点与最暗像素点的灰度…

数智读书笔记系列015 探索思维黑箱:《心智社会:从细胞到人工智能,人类思维的优雅解读》读书笔记

引言 《The Society of Mind》&#xff08;《心智社会》&#xff09;的作者马文・明斯基&#xff08;Marvin Minsky&#xff09;&#xff0c;是人工智能领域的先驱和奠基者之一 &#xff0c;1969 年获得图灵奖&#xff0c;被广泛认为是对人工智能领域影响最大的科学家之一。他…

游戏引擎学习第148天

回顾并规划今天的工作 没有使用引擎&#xff0c;也没有任何库支持&#xff0c;只有我们自己&#xff0c;编写游戏的所有代码&#xff0c;不仅仅是小小的部分&#xff0c;而是从头到尾。现在&#xff0c;我们正处于一个我一直想做的任务中&#xff0c;虽然一切都需要按部就班&a…

bug-Ant中a-select的placeholder不生效(绑定默认值为undefined)

1.问题 Ant中使用a-select下拉框时&#xff0c;placeholder设置输入框显示默认值提示&#xff0c;vue2ant null与undefined在js中明确的区别&#xff1a; null&#xff1a;一个值被定义&#xff0c;定义为“空值” undefined&#xff1a;根本不存在定义 2.解决 2.1 a-select使…

DeepSeek教我写词典爬虫获取单词的音标和拼写

Python在爬虫领域展现出了卓越的功能性&#xff0c;不仅能够高效地抓取目标数据&#xff0c;还能便捷地将数据存储至本地。在众多Python爬虫应用中&#xff0c;词典数据的爬取尤为常见。接下来&#xff0c;我们将以dict.cn为例&#xff0c;详细演示如何编写一个用于爬取词典数据…

springboot-自定义注解

1.注解的概念 注解是一种能被添加到java代码中的【元数据&#xff0c;类、方法、变量、参数和包】都可以用注解来修饰。用来定义一个类、属性或一些方法&#xff0c;以便程序能被捕译处理。 相当于一个说明文件&#xff0c;告诉应用程序某个被注解的类或属性是什么&#xff0c…

低代码开发直聘管理系统

低代码 DeepSeek 组合的方式开发直聘管理系统&#xff0c;兼职是开挂的存在。整个管理后台系统 小程序端接口的输出&#xff0c;只花了两个星期不到。 一、技术栈 后端&#xff1a;SpringBoot mybatis MySQL Redis 前端&#xff1a;Vue elementui 二、整体效果 三、表结…

【面试】Kafka

Kafka 1、为什么要使用 kafka2、Kafka 的架构是怎么样的3、什么是 Kafka 的重平衡机制4、Kafka 几种选举过程5、Kafka 高水位了解过吗6、Kafka 如何保证消息不丢失7、Kafka 如何保证消息不重复消费8、Kafka 为什么这么快 1、为什么要使用 kafka 1. 解耦&#xff1a;在一个复杂…

文件操作详解(万字长文)

C语言文件操作 一、为什么使用文件&#xff1f;二、文件分类三、文件的打开和关闭四、文件的顺序读写4.1fputc4.2fgetc4.3fputs4.4fgets4.5 fprintf4.6 fscanf4.7 fwrite4.8 fread 五、文件的随机读写5.1 fseek5.2 ftell和rewind六、文件读取结束的判定七、文件缓冲区 一、为什…

突破极限!蓝耘通义万相2.1引爆AI多模态新纪元——性能与应用全方位革新

云边有个稻草人-CSDN博客 目录 一、 引言 二、 蓝耘通义万相2.1版本概述 三、 蓝耘通义万相2.1的核心技术改进 【多模态数据处理】 【语音识别与文本转化】 【自然语言处理&#xff08;NLP&#xff09;改进】 【跨平台兼容性】 四、 蓝耘注册 部署流程—新手也能轻松…

力扣-股票买入问题

dp dp元素代表最大利润 f[j][1] 代表第 j 次交易后持有股票的最大利润。在初始状态&#xff0c;持有股票意味着你花钱买入了股票&#xff0c;此时的利润应该是负数&#xff08;扣除了买入股票的成本&#xff09;&#xff0c;而不是 0。所以&#xff0c;把 f[j][1] 初始化为负…

ubuntu22.04本地部署OpenWebUI

一、简介 Open WebUI 是一个可扩展、功能丰富且用户友好的自托管 AI 平台&#xff0c;旨在完全离线运行。它支持各种 LLM 运行器&#xff0c;如 Ollama 和 OpenAI 兼容的 API&#xff0c;并内置了 RAG 推理引擎&#xff0c;使其成为强大的 AI 部署解决方案。 二、安装 方法 …

Unity开发——CanvasGroup组件介绍和应用

CanvasGroup是Unity中用于控制UI的透明度、交互性和渲染顺序的组件。 一、常用属性的解释 1、alpha&#xff1a;控制UI的透明度 类型&#xff1a;float&#xff0c;0.0 ~1.0&#xff0c; 其中 0.0 完全透明&#xff0c;1.0 完全不透明。 通过调整alpha值可以实现UI的淡入淡…

LVGL直接解码png图片的方法

通过把png文件解码为.C文件&#xff0c;再放到工程中的供使用&#xff0c;这种方式随时速度快&#xff08;应为已经解码&#xff0c;代码中只要直接加载图片数据显示出来即可&#xff09;&#xff0c;但是不够灵活&#xff0c;适用于哪些简单又不经常需要更换UI的场景下使用。如…

【算法day5】最长回文子串——马拉车算法

最长回文子串 给你一个字符串 s&#xff0c;找到 s 中最长的 回文 子串。 https://leetcode.cn/problems/longest-palindromic-substring/description/ 算法思路&#xff1a; class Solution { public:string longestPalindrome(string s) {int s_len s.size();string tmp …

JavaWeb-HttpServletRequest请求域接口

文章目录 HttpServletRequest请求域接口HttpServletRequest请求域接口简介关于请求域和应用域的区别 请求域接口中的相关方法获取前端请求参数(getParameter系列方法)存储请求域名参数(Attribute系列方法)获取客户端的相关地址信息获取项目的根路径 关于转发和重定向的细致剖析…

Dify 本地部署教程

目录 一、下载安装包 二、修改配置 三、启动容器 四、访问 Dify 五、总结 本篇文章主要记录 Dify 本地部署过程,有问题欢迎交流~ 一、下载安装包 从 Github 仓库下载最新稳定版软件包,点击下载~,当然也可以克隆仓库或者从仓库里直接下载zip源码包。 目前最新版本是V…

css错峰布局/瀑布流样式(类似于快手样式)

当样式一侧比较高的时候会自动换行&#xff0c;尽量保持高度大概一致&#xff0c; 例&#xff1a; 一侧元素为5&#xff0c;另一侧元素为6 当为5的一侧过于高的时候&#xff0c;可能会变为4/7分部dom节点 如果不需要这样的话删除样式 flex-flow:column wrap; 设置父级dom样…

Docker入门篇1:搜索镜像、拉取镜像、查看本地镜像列表、删除本地镜像

大家好我是木木&#xff0c;在当今快速发展的云计算与云原生时代&#xff0c;容器化技术蓬勃兴起&#xff0c;Docker 作为实现容器化的主流工具之一&#xff0c;为开发者和运维人员带来了极大的便捷 。下面我们一起开始入门第一篇&#xff1a;搜索镜像、拉取镜像、查看本地镜像…