Cursor 实现了一个 MCP 客户端。这就是为什么我们可以在Cursor中通过配置MCP服务端来调用工具。

参考Cursor官方文档:

https://docs.cursor.com/context/model-context-protocol

Cursor 可支持任意数量的 MCP 服务器。它支持标准输入输出流(stdio)和服务器发送事件(sse)传输。

截图中高亮的话很关键,就是:“目前 MCP 工具并非适用于所有模型,仅在 Composer 中的 Agent 处可用”。

这句话折磨了我一整天,我的Cursor就没有Composer面板。后来发现是版本的原因,在新版本中,Composer被藏到了聊天框的左下角,并改名为“Edit”。

改版前:

改版后:

好,接下来让我们试试如何在cursor里面使用它。

本示例参考Anthropic和Cursor的官方文档修改而成,因为更新速度太快,这两个文档似乎不太能对得上,如果你直接照着做大概率是会失败的。不过问题不大,跟着本文就能搭建成功。

整体的思路是使用Cursor作为客户端,通过MCP协议,访问MCP服务端,调用MCP服务端暴露的两个工具 get-alerts 和 get-forecast,这两个工具会联网获取天气预警和天气预报 。

第一步:搭建MCP 快速入门天气服务器

参考:

https://modelcontextprotocol.io/quickstart/server#what-we%E2%80%99ll-be-building

pip install uv

因为我正在使用Windows,所以步骤如下:

# 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
type nul >>weather.py

打开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')

执行weather.py

uv run weather.py

正常情况应该是这个样子,什么都没有

第二步:配置Cusor

参考:

https://docs.cursor.com/context/model-context-protocol

打开Cursor,找到设置:

设置MCP服务

点击“+ Add new MCP server”添加MCP服务,并填写配置

第三步:在AI聊天中调用MCP工具

在AI聊天框选择“Edit”

询问天气,可以看到调用了MCP工具“get_forcast”

询问预警,可以看到调用了MCP工具“get_alerts”

整个过程非常丝滑。至此,我们已经完整体验了从搭建MCP服务,到在Cursor中通过MCP客户端调用MCP服务来使用工具的完整过程。

https://mp.weixin.qq.com/s/ZINe1CL1P8sDVi6FdkZqQA

下一篇,让我们来玩一些更实用的MCP工具,探索利用Cursor和MCP开发的最佳实践。想看就点个关注吧~

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐