FastMCP 文件系统提供器自动发现组件
FastMCP 的 FileSystemProvider 递归扫描目录中的 Python 文件,自动注册用独立装饰器标记的工具、资源和提示,让项目结构充当组件注册表,并支持开发期重载与单文件失败隔离。
`FileSystemProvider` 扫描 Python 文件的目录,并自动注册装饰的函数 `@tool`, `@resource`,或 `@prompt`。这使得基于文件的组织模式类似于 Next.js 路由,其中您的项目结构成为您的组件登记册。 ## 为什么文件系统发现 传统的 FastMCP 服务器需要在文件之间进行协调。 您的工具文件要么导入服务器以调用 `@server.tool()`,或者您的服务器文件导入所有工具模块。两种方法都创建了一些开发者喜欢避免的组合。 `FileSystemProvider` 每个文件都是自成一体的,它使用独立的装饰器(`@tool`, `@resource`, `@prompt`) 不需要访问服务器实例。 提供者在启动时发现这些文件, 这样您就可以添加新的工具, 而无需修改您的服务器文件 。 这是一些团队喜欢的公约,不一定对所有项目都更好。 - **无协调**: 文件不导入服务器; 服务器不导入文件 - **可预测的命名**: 函数名称成为组件名称( 除非覆盖) - **开发模式**: 可选重扫描每个快速重复请求的文件 ## 快速启动 创建指向您的组件目录的提供者, 然后将其传递到您的服务器。 使用 `Path(__file__).parent` 以创建与服务器文件相对的路径。 ```python from pathlib import Path from fastmcp import FastMCP from fastmcp.server.providers import FileSystemProvider mcp = FastMCP("MyServer", providers=[FileSystemProvider(Path(__file__).parent / "components")]) ``` 在你身边 `components/` 目录,创建带有装饰功能的Python文件. ```python # components/tools/greet.py from fastmcp.tools import tool @tool def greet(name: str) -> str: """Greet someone by name.""" return f"Hello, {name}!" ``` 当服务器启动时, `FileSystemProvider` 扫描目录,导入所有 Python 文件,并登记它找到的任何装饰功能。 ## 装饰者 FastMCP提供独立装饰,标记用于发现的功能: `@tool` 从 `fastmcp.tools`, `@resource` 从 `fastmcp.resources`,以及 `@prompt` 从 `fastmcp.prompts`。这些支持服务器装订的装饰器的完整语法——所有相同的参数都同样有效。 ### @tool 将函数标为工具。 函数名称默认成为工具名称 。 ```python from fastmcp.tools import tool @tool def calculate_sum(a: float, b: float) -> float: """Add two numbers together.""" return a + b ``` 用可选参数自定义工具 。 ```python from fastmcp.tools import tool @tool( name="add-numbers", description="Add two numbers together.", tags={"math", "arithmetic"}, ) def add(a: float, b: float) -> float: return a + b ``` 装饰者支持标准工具选项: `name`, `title`, `description`, `icons`, `tags`, `output_schema`, `annotations`, `meta`, `version`, `timeout`, `auth`, `task`,以及 `run_in_thread`. ### @resource 将函数标为资源 。 不同于 `@tool`,则 `@resource` 装饰者需要URI参数. ```python from fastmcp.resources import resource @resource("config://app") def get_app_config() -> str: """Get application configuration.""" return '{"version": "1.0"}' ``` 带有模板参数的 URI 创建资源模板。 提供者根据 URI 是否包含来自动检测是否注册静态资源或模板 `{parameters}` 或函数有参数。 ```python from fastmcp.resources import resource @resource("users://{user_id}/profile") def get_user_profile(user_id: str) -> str: """Get a user's profile by ID.""" return f'{{"id": "{user_id}", "name": "User"}}' ``` 装饰者支持: `uri` (必须), `name`, `title`, `description`, `icons`, `mime_type`, `tags`, `annotations`, `meta`, `version`, `auth`,以及 `security`. ### @prompt 将函数标为快速模板 。 ```python test="skip" from fastmcp.prompts import prompt @prompt def code_review(code: str, language: str = "python") -> str: """Generate a code review prompt.""" return f"Please review this {language} code:\n\n```{language}\n{code}\n```" ``` ```python from fastmcp.prompts import prompt @prompt(name="explain-concept", tags={"education"}) def explain(topic: str) -> str: """Generate an explanation prompt.""" return f"Explain {topic} using clear examples and analogies." ``` 装饰者支持: `name`, `title`, `description`, `icons`, `tags`, `meta`, `version`,以及 `auth`. ## 目录结构 目录结构纯粹是组织性的,提供者递归扫描所有 `.py` 文档,无论它们属于哪个子目录。 `tools/`, `resources/`,以及 `prompts/` 是帮助您组织代码的可选公约。 ```text components/ ├── tools/ │ ├── greeting.py # @tool functions │ └── calculator.py # @tool functions ├── resources/ │ └── config.py # @resource functions └── prompts/ └── assistant.py # @prompt functions ``` 也可以将所有组件放入一个文件,或者按照特性而不是类型来组织. ```text components/ ├── user_management.py # @tool, @resource, @prompt for users ├── billing.py # @tool, @resource for billing └── analytics.py # @tool for analytics ``` ## 发现规则 提供者在扫描时遵循这些规则: | 规 则 | 行为 | |------|----------| | 文件扩展名 | 仅 `.py` 文件已扫描 | | `__init__.py` | 跳过( 用于包结构, 而非组件) | | `__pycache__` | 跳过 | | 私人名称 | 模块属性从 `_` 被忽略,即使装饰 | | 无装饰器 | 没有文件 `@tool`, `@resource`,或 `@prompt` 默默跳过 | | 多个组件 | 单个文件可以包含任意数量的装饰功能 | ### 软件包导入 如果您的目录包含 `__init__.py` 文件中,提供者导入文件为 Python 软件包的合适成员。这意味着在组件目录中相对导入工作正确。 ```python # components/__init__.py exists # components/tools/greeting.py from fastmcp.tools import tool from ..helpers import format_name # Relative imports work @tool def greet(name: str) -> str: return f"Hello, {format_name(name)}!" ``` 无 `__init__.py`,直接使用 `importlib.util.spec_from_file_location`. ## 重新装入模式 在开发过程中, 您可能希望组件文件的修改不重新启动服务器而生效。 启用重新装入模式, 可以在每次请求时重新扫描目录 。 ```python from pathlib import Path from fastmcp.server.providers import FileSystemProvider provider = FileSystemProvider(Path(__file__).parent / "components", reload=True) ``` 与 `reload=True`,提供者: 1. 在每个请求中重新发现所有 Python 文件 2. 将发现自有模块装入新的命名空间和在同一次扫描中进行的兄弟进口 3. 用任何新的、修改的或移除的组件更新组件登记册 主机应用程序已经导入的模块和发现集外的依赖性都保留了缓存。 重新启动服务器来提取这些模块的更改。 如果您的应用程序在提供者装入后从提供者目录中导入一个模块, 您的参考文献会保留该版本, 同时重新装入新版本, 因此在创建提供者或将其保存在目录之外之前先导入共享的助手 。 重新装入模式会给每个请求增加间接费用。 只在开发过程中使用, 而不是在生产中使用 。 ## 处理错误 当一个文件无法导入或构建其组件(语法错误,缺失依赖性,不支持的工具签名等)时,提供者会记录一个警告,跳过该文件,并继续扫描其他文件. 来自其他文件的组件在启动和重新装入时仍然可用. ```text WARNING - Failed to load /path/to/broken.py: No module named 'missing_dep' ``` 提供者跟踪文件已失败, 并且仅在文件修改时间变化时重新登录警告。 这样可以防止在重新装入模式下重复扫描损坏文件时的日志垃圾邮件 。 检查 `provider.failed_files` 对于最近载入的失败的快照,包括组件注册错误。每个条目都会绘制一个文件路径,以查看其错误消息。您可以使用它来执行更严格的启动政策,而无需再次导入文件。 ## 示例项目 保存库中有一个完整的示例: `examples/filesystem-provider/`结构表明建议的组织。 ```text examples/filesystem-provider/ ├── server.py # Server entry point └── components/ ├── tools/ │ ├── greeting.py # greet, farewell tools │ └── calculator.py # add, multiply tools ├── resources/ │ └── config.py # Static and templated resources └── prompts/ └── assistant.py # code_review, explain prompts ``` 服务器进入点最小 。 ```python from pathlib import Path from fastmcp import FastMCP from fastmcp.server.providers import FileSystemProvider provider = FileSystemProvider( root=Path(__file__).parent / "components", reload=True, ) mcp = FastMCP("FilesystemDemo", providers=[provider]) ``` 运行与 `fastmcp run examples/filesystem-provider/server.py` 或检查与 `fastmcp inspect examples/filesystem-provider/server.py`.
查看原始来源