当前位置: 首页 > news >正文

一个简单的Python文件MCP服务器

 代码先行

import asyncio
import json
import osfrom mcp.server import Server
from mcp.types import Resource, Tool, TextContent
from typing import Listapp = Server("file_list")@app.list_tools()
async def list_tools() -> List[Tool]:"""List available file tools."""return [Tool(name="list_files",description="List files in the given directory.",inputSchema={"type": "object","properties": {"text": {"type": "string","description": "The directory path to list files from."}},"required": ["text"]}),Tool(name="rename_file",description="rename the file name to a new name.",inputSchema={"type": "object","properties": {"old_name": {"type": "string","description": "the file's old name."},"new_name": {"type": "string","description": "the file's new name."}},"required": ["old_name", "new_name"]})]@app.call_tool()
async def list_files(name: str, path: dict) -> List[TextContent]:"""List files in the given directory."""try:directory = path['text']files = os.listdir(directory)return [{"type": "text","text": f"文件夹内包含的文件和文件夹有:{','.join(files)}"}]except Exception as e:raise RuntimeError(f"Error {name} in {path}: {str(e)}")@app.call_tool()
async def rename_file(name: str, path: dict) -> List[TextContent]:"""Rename a file."""old_name = path['old_name']new_name = path['new_name']os.rename(old_name, new_name)return [{"type": "text","text": f"文件 {old_name} 重命名为 {new_name} 成功。"}]async def main():"""Main entry point to run the MCP server."""from mcp.server.stdio import stdio_serverasync with stdio_server() as (read_stream, write_stream):try:await app.run(read_stream,write_stream,app.create_initialization_options())except Exception as e:raiseif __name__ == "__main__":asyncio.run(main())

核心点有三个

1.list_tools 这个是给AI展示有哪些工具可以调用的,具体工具的功能是什么,可以在这里面配置具体工具call_tools的入参数据类型,确保执行的健壮性

2.call_tool 这个是具体的实现方法,定义的名称与list_tools要一致,里面是一些具体的实现方法

3.main 这个是用来启动整个服务器的,主要是对标准数据输入输出流进行适配

使用效果

http://www.dtcms.com/a/133821.html

相关文章:

  • OpenAI 最新发布的 GPT-4.1 系列在 API 中正式上线
  • Google-Tensorflow-NLP
  • NLP高频面试题(四十三)——什么是人类偏好对齐中的「对齐税」(Alignment Tax)?如何缓解?
  • 什么样的游戏需要用到游戏盾SDK呢?
  • vue 表格某列超出显示...,悬浮tip
  • 【HarmonyOS 5】AttributeModifier和AttributeUpdater详解
  • 【C#】Html转Pdf,Spire和iTextSharp结合,.net framework 4.8
  • MAC-​​需求​​:10万订单异步执行库存扣减、短信通知。
  • #include<bits/stdc++.h>
  • macos下 ~/.zshrc~ 和 ~/.zshrc
  • WEB安全--蓝队日志--RCE数据包分析
  • 系统架构设计师:系统架构概述知识体系、考点详解、高效记忆要点、练习题并提供答案与解析
  • LeetCode面试热题150中12-18题学习笔记(用Java语言描述)
  • Java项目之基于ssm的QQ村旅游网站的设计(源码+文档)
  • Redis 适合作为微服务架构中的哪些组件?
  • 树莓派_利用Ubuntu搭建gitlab
  • 深入理解 Nacos 服务发现机制
  • RabbitMQ demo案例
  • 大前端基础学习
  • Sentinel实战教程:流量控制与Spring Boot集成
  • 日志查询 Less命令:/搜索
  • 【计网】SSL/TLS核心原理
  • 如何提高webrtc操作跟手时间,降低延迟
  • 微信小程序组件传参
  • 基础算法 —— 前缀和 【复习总结】
  • [特殊字符] KoalaAI 1.0.23 震撼升级:GPT-4.1免费畅享,AI革命触手可及!
  • Node.js 操作 MySQL 数据库
  • MySQL:存储函数和存储过程
  • 基于vue2+ElementUI的el-tree封装一个带搜索的树形组件
  • 【差分隐私相关概念】瑞丽差分隐私(RDP)-瑞丽散度约束了贝叶斯因子后验变化