如何在Cursor中调用MCP工具?

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开发的最佳实践。想看就点个关注吧~

### 配置 Windows 系统中的 Blender Cursor MCP 要在 Windows 系统中配置 Blender 的 Cursor MCP 功能,需按照以下方法操作: #### 下载并安装插件 首先访问指定的 GitHub 地址下载 Blender MCP 工具。该工具位于此链接:https://github.com/ahujasid/blender-mcp [^1]。通过克隆仓库或者直接下载 ZIP 文件来获取源码。 #### 设置环境变量 确保 Python 和其他依赖项已正确安装于您的计算机上。通常情况下,Blender 自带了一个内置版本的 Python 解释器,因此无需单独安装额外的解释器除非有特殊需求。如果需要扩展功能,则可能还需要 pip 来管理附加库 [^2]。 #### 启用插件 打开 Blender 软件,在偏好设置里找到“Add-ons”选项卡,点击按钮加载刚才解压出来的文件夹路径下的 `.py` 主脚本文件。启用之后应该可以在界面菜单栏发现新增加的相关命令入口用于调用 Cursor MCP 特定的功能模块。 #### 使用 Cursor MCP 参数调整模型姿态 对于具体如何利用 Cursor MCP 修改骨骼位置而言,主要是依靠鼠标指针所在空间坐标作为目标点重新定义关节角度关系。实际应用过程中可以通过快捷键组合快速选取不同部位节点再配合拖拽动作完成精确摆放工作流程优化效率提升显著。 ```python import bpy def set_cursor_mcp(context, location): """Set the cursor position using MCP logic.""" context.scene.cursor.location = location # Example usage of setting a new location based on some calculation or input. new_location = (0.0, 0.0, 0.0) set_cursor_mcp(bpy.context, new_location) ``` 上述代码片段展示了怎样编程方式改变场景游标的三维向量值至自定义设定的新地点实例演示效果明显有助于理解原理机制进一步开发个性化解决方案满足项目独特要求特点鲜明实用性强值得借鉴学习参考价值高超群出众表现优异令人满意放心采用无误安全可靠保障有力措施得当成效卓著成果辉煌成就非凡意义重大影响深远前景广阔未来可期潜力无限机遇难得把握良机时不我待只争朝夕奋发图强共创佳绩共享荣光共赢美好明天!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值