当前位置: 首页 > 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 这个是用来启动整个服务器的,主要是对标准数据输入输出流进行适配

使用效果

相关文章:

  • 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集成
  • 圆桌丨中俄权威专家详解:两国携手维护战后国际秩序,捍卫国际公平正义
  • 驱逐行动再加码?特朗普或向利比亚和卢旺达遣送非法移民
  • 我国科研团队发布第四代量子计算测控系统
  • 消费者在天猫一旗舰店换手机电池疑遭套路致手机损坏,平台已介入
  • “穿越看洪武”,明太祖及其皇后像台北故宫博物院南园展出
  • “模”范生上海,如何再进阶?