vscode集成MCP Server

前言

本文介绍如何在 VS Code 中集成自行开发的 MCP (Model Context Protocol) Server。通过配置 .vscode/mcp.json 文件,可以将自定义的 MCP Server 注册到 VS Code 的 GitHub Copilot 中,从而让 AI 助手能够调用用户开发的工具函数。整个过程包括:编写 MCP Server 代码、配置服务器启动参数、启动服务并测试调用。

注意,Copilot不是必须的,只是vscode 官方对copilot集成更好,其它第三方的模型也能使用MCP Server。

使用Copilot

  1. 编写数学工具的mcp server. math.py
from fastmcp import FastMCP
from typing import TypeAlias, Union
from datetime import datetime

mcp = FastMCP("math")

Number: TypeAlias = Union[int, float]

@mcp.tool()
def add(a: Number, b: Number) -> Number:
    """Add two numbers
    
    Args:
        a (Number): The first number
        b (Number): The second number

    Returns:
        Number: The sum of a and b
    """
    return a + b

@mcp.tool()
def subtract(a: Number, b: Number) -> Number:
    """Subtract two numbers
    
    Args:
        a (Number): The first number
        b (Number): The second number

    Returns:
        Number: The difference of a and b
    """
    return a - b

@mcp.tool()
def multiply(a: Number, b: Number) -> Number:
    """Multiply two numbers
    
    Args:
        a (Number): The first number
        b (Number): The second number

    Returns:
        Number: The product of a and b
    """
    return a * b

@mcp.tool()
def divide(a: Number, b: Number) -> Number:
    """Divide two numbers
    
    Args:
        a (Number): The numerator
        b (Number): The denominator

    Returns:
        Number: The quotient of a and b

    Raises:
        ValueError: If b is zero
    """
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

@mcp.tool()
def is_greater_than(a: Number, b: Number) -> bool:
    """Check if a is greater than b
    
    Args:
        a (Number): The first number
        b (Number): The second number

    Returns:
        bool: True if a is greater than b, False otherwise
    """
    return a > b

@mcp.tool()
async def get_weather(city: str) -> str:  
    """Get weather for a given city.
    
    Args:
        city (str): The city name

    Returns:
        str: A string describing the weather in the given city
    """
    return f"It's always sunny in {city}!"

@mcp.tool()
async def get_current_datetime() -> str:
    """Get current date and time.
    
    Returns:
        str: The current date and time in YYYY-MM-DD HH:MM:SS %z format
    """
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S %z")


if __name__ == "__main__":
    # mcp.run(transport="http", host="localhost", port=8001, show_banner=False)
    mcp.run(transport="stdio", show_banner=False)

  1. 创建.vscode/mcp.json
{
    "servers": {
        "math": {
            "command": "uv",
            "args": [
                "--directory",
                "/home/rainux/Documents/workspace/py-dev/mcp-local",
                "run",
                "math.py"
            ]
        }
    }
}
  1. mcp.json文件中会显示一个启动的图标,点击启动。
  2. 在copilot 聊天窗口中,右下角有一个"配置工具"的图标,点击后在弹出的菜单中可以看到一个math server.
  3. 提问测试。如果没调用到mcp tool,可以尝试按Ctrl + Shift + P,输入Reload Window 来重新加载窗口,或者在mcp.json文件中重启mcp server,或者重启vscode.

非Copilot, 以通义灵码为例

在通义灵码的聊天窗口中按提示添加MCP Server 的配置,在手动添加的配置文件中填写如下内容。保存后通义灵码会自动启动MCP Server,然后测试能否调用MCP Tool即可。

{
  "mcpServers": {
    "math": {
      "type": "stdio",
      "command": "uv",
      "args": [
        "--directory",
        "/home/rainux/Documents/workspace/py-dev/mcp-local",
        "run",
        "math.py"
      ],
      "env": {
        "ROOT_DIR": "/home/rainux/Documents/workspace/py-dev/mcp-local"
      }
    }
  }
}

参考

posted @ 2025-11-13 19:47  花酒锄作田  阅读(93)  评论(0)    收藏  举报