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

### 配置MCP参数于数据库游标中的方法 Model-Context-Protocol (MCP) 是一种用于标准化人工智能与外部数据源(如数据库)交互的协议。为了在数据库游标的上下文中应用 MCP 参数,可以通过以下方式实现: #### 1. **理解 MCP 的作用** MCP 协议的核心在于提供一个统一接口,使得 AI 能够更安全、高效地访问和操作数据库资源。它不仅限于简单的查询,还支持复杂的事务管理以及权限控制[^3]。 #### 2. **初始化数据库连接并引入 MCP 支持** 在使用 `pymysql` 进行数据库连接时,可以在建立连接的过程中加入 MCP 所需的支持模块或扩展库。以下是基于 Python 和 pymysql 实现的一个示例代码片段: ```python import pymysql from mcp_client import MCPServerConnection # 假设有一个 MCP 客户端库 # 初始化 MCP Server Connection mcp_server = MCPServerConnection(server_url="http://your-mcp-server.com", token="secure_token") # 数据库连接配置 db_config = { 'host': 'localhost', 'user': 'root', 'password': '123456', 'database': 'book' } # 添加 MCP 参数至数据库连接 db_config['client_flag'] = pymysql.constants.CLIENT.MULTI_STATEMENTS | mcp_server.get_mcp_flags() # 打开数据库连接 db = pymysql.connect(**db_config) # 创建游标对象 cursor = db.cursor() ``` 在此代码中,`MCPServerConnection` 是假设存在的一个类,代表了 MCP 客户端的功能。通过调用其 `get_mcp_flags()` 方法,可以获取适用于当前数据库会话的安全标志或其他元数据,并将其注入到数据库连接的配置中[^4]。 #### 3. **在游标中传递 MCP 上下文** 一旦建立了带有 MCP 支持的数据库连接,就可以进一步利用游标来执行受控的操作。例如,在执行 SQL 查询之前,先验证 MCP 权限或者附加额外的日志记录逻辑: ```python def execute_with_mcp(cursor, query, params=None): """ 使用 MCP 控制执行 SQL 操作。 :param cursor: 游标对象 :param query: 待执行的 SQL 字符串 :param params: 可选参数列表 """ try: # 向 MCP 服务器报告即将执行的操作 mcp_server.log_query(query=query, params=params) # 正常执行 SQL if params is None: result = cursor.execute(query) else: result = cursor.execute(query, params) return result except Exception as e: # 将错误信息发送给 MCP 服务器以便监控 mcp_server.report_error(error=str(e)) raise e # 示例:创建表的同时触发 MCP 日志记录 sql_create_table = """ CREATE TABLE IF NOT EXISTS EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); """ execute_with_mcp(cursor, sql_create_table) # 关闭连接 db.close() ``` 此函数封装了一个标准的 SQL 执行流程,并在其前后加入了 MCP 特定的行为,比如日志记录和异常上报[^3]。 #### 4. **注意事项** 当在游标中配置 MCP 参数时需要注意以下几点: - 确保 MCP 客户端库已正确安装并与目标 MCP 服务兼容。 - 对敏感操作(如 DDL/DML),应严格遵循 MCP 推荐的最佳实践以保障安全性。 - 如果涉及到跨平台或多语言环境下的 MCP 应用,则可能需要调整具体的实现细节[^4]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值