MCP相当于LLM的手脚,增加了大模型的执行能力。在介绍下Cline之前,我们先介绍下MCP主机。如果把LLM类比作分布式事务的事务管理器,那么MCP server相当于分布式事务中的资源管理器,MCP主机就是分布式事务中的资源协调者。它工作的流程如下:
当用户向MCP主机询问天气的时候,MCP主机会把用户的问题和主机上配置的MCP工具都放在提示词里,发给LLM,LLM先思考看自己能否给出答案,比如天气这种实时变化的知识,LLM解答不了,所以它从提示词中给的MCP工具列表中,根据提示词的描述,选定工具返回给MCP主机。MCP主机询问用户授权,用户授权后调用MCP server查询天气,将返回的结果提交给LLM,LLM总结后返回给MCP服务器,然后展示给用户,用户就看到了结果。
目前比较成熟的MCP主机如下:
其中cline是vscode的开源插件https://github.com/cline/cline,下面我们介绍下如何配置使用:在vscode 插件市场中搜索Cline,然后安装:
安装完成后配置Cline,由于知名的LLM都是收费的,我们配置下免费的大模型智普。(网上说可以访问glfh.chat网站,该网站提供了多个免费的开源模型,包括:llama3.1 405B、千问2.5 coder 32B、llama3.3 70B,实测发现由于防火墙的原因,访问不了)。
这里我们选择OpenAI Compatible的大模型提供商,然后填入智普的api地址和token。保存就可以了,我们测试下:
能返回结果说明成功了,下面我们接着制作自己的mcp server,交给cline使用。我们使用python开发mcp server。
开发之前先使用脚手架uv(https://github.com/astral-sh/uv)来初始化python环境
pip3 install uv -i https://mirrors.aliyun.com/pypi/simple/ Installing collected packages: uv Successfully installed uv-0.7.8 [notice] A new release of pip is available: 23.2.1 -> 25.1.1 [notice] To update, run: python3.11 -m pip install –upgrade pip
安装完检测下版本
GPT plus 代充 只需 145 % uv –version uv 0.7.8 (0ddcc1905 2025-05-23)
初始化一个项目
�it weather Initialized project weather at /Users/xia*****/py/weather
初始化一个虚拟环境
GPT plus 代充 只需 145�nv Using CPython 3.11.6 interpreter at: /usr/local/opt/python@3.11/bin/python3.11 Creating virtual environment at: .venv Activate with: source .venv/bin/activate
% source .venv/bin/activate (py)
进入目录,安装依赖包
GPT plus 代充 只需 145% uv add "mcp[cli]" httpx -i https://mirrors.aliyun.com/pypi/simple/ warning: Indexes specified via --index-url will not be persisted to the pyproject.toml file; use --default-index instead. warning: VIRTUAL_ENV=/Users/xia*****/py/.venv does not match the project environment path .venv and will be ignored; use --active to target the active environment instead Resolved 29 packages in 2.76s Prepared 27 packages in 2.44s Installed 27 packages in 140ms
- annotated-types==0.7.0
- anyio==4.9.0
- certifi==2025.4.26
- click==8.1.8
- h11==0.16.0
- httpcore==1.0.9
- httpx==0.28.1
- httpx-sse==0.4.0
- idna==3.10
- markdown-it-py==3.0.0
- mcp==1.9.1
- mdurl==0.1.2
- pydantic==2.11.5
- pydantic-core==2.33.2
- pydantic-settings==2.9.1
- pygments==2.19.1
- python-dotenv==1.1.0
- python-multipart==0.0.20
- rich==14.0.0
- shellingham==1.5.4
- sniffio==1.3.1
- sse-starlette==2.3.5
- starlette==0.46.2
- typer==0.15.4
- typing-extensions==4.13.2
- typing-inspection==0.4.1
- uvicorn==0.34.2
�d fastmcp -i https://mirrors.aliyun.com/pypi/simple/ warning: Indexes specified via--index-urlwill not be persisted to thepyproject.tomlfile; use--default-indexinstead. warning:VIRTUAL_ENV=/Users/xia*****/py/.venvdoes not match the project environment path.venvand will be ignored; use--activeto target the active environment instead Resolved 33 packages in 1.02s Prepared 4 packages in 371ms Installed 4 packages in 43ms - exceptiongroup==1.3.0
- fastmcp==2.5.0
- openapi-pydantic==0.5.1
- websockets==15.0.1
然后编辑下我们的mcp server代码weather.py,具体如下
GPT plus 代充 只需 145
from typing import Any import httpx from mcp.server.fastmcp import FastMCPInitialize 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:
GPT plus 代充 只需 145
try: response = await client.get(url, headers=headers, timeout=30.0) response.raise_for_status() return response.json() except Exception: return Nonedef format_alert(feature: dict) -> str: """Format an alert feature into a readable string.""" props = feature["properties"] return f""" Event: Area: Severity: Description: Instructions: """ @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:
GPT plus 代充 只需 145
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 "
".join(alerts) @mcp.tool() async def get_forecast(latitude: float, longitude: float) -> str: """Get weather forecast for a location. Args:
GPT plus 代充 只需 145
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:
GPT plus 代充 只需 145
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’]} """
GPT plus 代充 只需 145
forecasts.append(forecast)return "
".join(forecasts) if name == "main":
Initialize and run the server
mcp.run(transport=‘stdio’)
我们写了一个叫weather的mcp server,提供了两个工具get_alerts和get_forecast然后启动我们的mcp server
% uv run weather.py点击Config MCP Servers就能配置mcp server。接下来在mcp 主机上配置mcp server的地址,才能链接上。具体配置如下:
GPT plus 代充 只需 145
{ "mcpServers": { "weather": { "command": "uv", "args": ["--directory", "/Users/xia*****/py/weather/", "run", "weather.py"] } } }
配置完成后我们测试下,提问:“德克萨斯州有哪些活跃的天气警报?”,会提示我们是否使用mcp工具,点击是:
返回结果如下:
GPT plus 代充 只需 145
The weather alerts for Texas include the following:
- Heat Advisory:
- Area: Jim Wells; Inland Kleberg; Inland Nueces; Inland San Patricio
- Severity: Moderate
- Description: Heat index values up to 111 expected. Drink plenty of fluids, stay in an air-conditioned room, stay out of the sun, and check up on relatives and neighbors.
- Flood Warning:
- Area: Angelina, Houston, Polk, Trinity, Tyler
- Description: Minor flooding is forecast for the Neches River near Diboll. Do not drive cars through flooded areas and caution is advised when walking near riverbanks.
我们测试下第二个工具,提问:“预测下德州的天气”
至此Cline的配置和使用介绍完毕。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/244071.html