使用mcp自定义编写mcp tool,使用 conda 启动,在cline中配置使用

自定义 mcp tool 例子

python 复制代码
## /langchain_learn/mcp学习/base_mcp_tool_study2.py
# 导入必要模块
import os
from typing import Optional
from mcp.server.fastmcp import FastMCP

# 初始化 MCP 服务器实例,指定服务器名称和版本
mcp_server = FastMCP(name="DemoServer", version="1.0.0")

#mcp_server.tool() 将函数注册为 mcp tool 工具

@mcp_server.tool()
def list_files(directory: str = "/work/langchain_learn") -> list:
    """
    获取指定目录的文件列表(默认查看桌面)
    Args:
        directory (str): 要查询的目录路径,支持 ~ 符号
    Returns:
        list: 文件名列表
    """
    try:
        # 处理跨平台路径格式
        expanded_path = os.path.expanduser(directory)
        return os.listdir(expanded_path)
    except Exception as e:
        return [f"Error: {str(e)}"]

@mcp_server.tool()
def calculate(expression: str) -> Optional[float]:
    """
    执行数学计算(支持加减乘除)
    Args:
        expression (str): 数学表达式,如 "3 + 5 * 2"
    Returns:
        float: 计算结果(保留两位小数)
    """
    try:
        # 安全计算实现(实际生产环境应使用更安全的计算方式)
        result = eval(expression)
        return round(float(result), 2)
    except:
        return None


if __name__ == "__main__":
    # 启动服务器,使用 stdio 传输协议
    mcp_server.run(
        transport='stdio',   # 标准输入输出通信
    )

cline 中 添加 下方 配置

在vscode中点击cline,然后点击下图中的模块

然后点击 已安装,点击下方 配置mcp 服务器,将下方的json 文件内容 放入 配置mcp 服务器中的 mcpServers 对应的 值中。

json 复制代码
"myserver2": { #自定义 mcp 服务器的名字,与文件名无关
      "command": "/miniforge3/envs/langchain/bin/python", #想要使用的 conda中的某个虚拟环境下的 python解释器
      "args": [
        "/langchain_learn/mcp学习/base_mcp_tool_study2.py" #上方mcp 工具文件 的绝对路径
      ],
      "disabled": false,
      "autoApprove": [
        "multiplay"
      ],
      "description": "演示服务器(含文件查询和计算)" #当前服务器的描述,具体是可以做什么
    },
相关推荐
薛定谔的猫3691 小时前
深入浅出 Model Context Protocol (MCP):连接 AI 与外部数据的桥梁
ai·llm·agent·mcp·modelcontextprotocol
Jing_jing_X1 小时前
MCP (二)原理深度解析:一次工具调用到底发生了什么?
ai编程·mcp
tiger从容淡定是人生2 天前
AI替代软件战略(一):从 CCleaner 到 MCP 架构重构 —— TigerCleaner 的工程实践
人工智能·重构·架构·c#·mcp
Echo_NGC22372 天前
【论文解读】Attention Is All You Need —— AI 时代的“开山之作“,经典中的经典(transformer小白导读)
人工智能·python·深度学习·神经网络·机器学习·conda·transformer
何中应2 天前
Conda安装&使用
python·conda·python3.11
@SmartSi2 天前
Spring AI 实战:如何使用 MCP Server 搭建 MCP 天气查询服务
spring ai·mcp
qcx232 天前
拆解 Warp AI Agent(五):跨生态联邦——10 种 Skill + MCP + 多 Harness 互操作设计
人工智能·rust·ai agent·skill·warp·mcp·harness
无糖可乐没有灵魂2 天前
AI Agent结构图例和工作流程描述
ai·llm·prompt·agent·mcp·skills
Joseph Cooper3 天前
AI Agent 落地入门:从模型、工具到 Skills 与 MCP 的分工
人工智能·ai·agent·claude·skill·mcp