河南省住房城乡与建设厅网站首页慧聚创新网站建设

张小明 2026/1/11 9:12:57
河南省住房城乡与建设厅网站首页,慧聚创新网站建设,wordpress游戏网站,阿里云备案 网站服务内容一、什么是资源 资源代表 MCP 客户端可以读取的数据或文件#xff0c;而资源模板通过允许客户端基于 URI 中传递的参数请求动态生成的资源#xff0c;扩展了这一概念。 FastMCP 简化了静态和动态资源的定义#xff0c;主要使用 mcp.resource 装饰器。 当客户端请求资源统一资…一、什么是资源资源代表 MCP 客户端可以读取的数据或文件而资源模板通过允许客户端基于 URI 中传递的参数请求动态生成的资源扩展了这一概念。FastMCP 简化了静态和动态资源的定义主要使用 mcp.resource 装饰器。当客户端请求资源统一资源标识符URI时FastMCP 找到相应的资源定义。如果是动态资源由函数定义则执行该函数。将内容文本、JSON、二进制数据返回给客户端。这使得大语言模型LLM能够访问与对话相关的文件、数据库内容、配置或动态生成的信息。最常用定义一个资源的方式就是使用resource注解一个Python函数。importjsonfromfastmcpimportFastMCP mcpFastMCP(nameDataServer)# Basic dynamic resource returning a stringmcp.resource(resource://greeting)defget_greeting()-str:Provides a simple greeting message.returnHello from FastMCP Resources!# Resource returning JSON data (dict is auto-serialized)mcp.resource(data://config)defget_config()-dict:Provides application configuration as JSON.return{theme:dark,version:1.2.0,features:[tools,resources],}核心概念URI : 传给resource的第一个参数就是唯一的URI, 比如resource://greeting懒加载被装饰器装饰的函数get_greeting和get_config只有在客户端请求时才会执行。推断元数据资源名称 取自函数名get_greeting。资源描述 取自函数描述二、资源的参数resource)你可以使用如下的自定义的属性。fromfastmcpimportFastMCP mcpFastMCP(nameDataServer)# Example specifying metadatamcp.resource(uridata://app-status,# Explicit URI (required)nameApplicationStatus,# Custom namedescriptionProvides the current status of the application.,# Custom descriptionmime_typeapplication/json,# Explicit MIME typetags{monitoring,status},# Categorization tagsmeta{version:2.1,team:infrastructure}# Custom metadata)defget_application_status()-dict:Internal function description (ignored if description is provided above).return{status:ok,uptime:12345,version:mcp.settings.version}# Example usage名称类型是否必须描述uristrrequired资源的唯一标识符namestr 或 None一个人类可读懂的名称。如果未提供将默认使用函数名称descriptionstr 或 None资源说明。如果未提供默认使用文档字符串mime_typestr 或 None指定内容类型。FastMCP 通常会推断出默认类型如text/plain或application/json但对于非文本类型明确指定会更好。tagsset[str] 或 None一组用于对资源进行分类的字符串。服务器以及在某些情况下客户端可以使用这些字符串来筛选或分组可用资源。enabledbool 默认值 True一个用于启用或禁用资源的布尔值。iconslist[Icon] 或 None此资源或模板的可选图标表示列表。annotationsAnnotations 或 dict 或 None一个可选的注释对象或字典用于添加有关该资源的额外元数据。metadict[str, Any] 或 None关于资源的可选元信息。这些数据会作为客户端资源对象的_meta 字段传递给 MCP 客户端可用于自定义元数据、版本控制或其他特定于应用程序的用途。Annotations 的属性readOnlyHint类型: bool | None描述: 如果为 true则该资源为只读不会修改其环境。idempotentHint类型: bool | None描述: 如果为真反复读取该资源不会对其环境产生额外影响。三、资源的返回值FastMCP 会自动将您函数的返回值转换为适当的 MCP 资源内容str转为TextResourceContents且mime_typetext/plain by defaultdict,list,pydantic.BaseModel: 自动序列化成json字符串TextResourceContents, 且mime_typeapplication/jsonbytesBase64编码转为BlobResourceContents, 且应该设置合适的mime_type, 如“image/png”, “application/octet-stream”ResourceContent完全控制内容、MIME 类型和元数据。None返回一个空的资源内容列表。3.1 ResourceContentResourceContent完全控制了资源的返回。fromfastmcpimportFastMCPfromfastmcp.resourcesimportResourceContent mcpFastMCP(nameWidgetServer)mcp.resource(widget://my-widget)defget_widget()-ResourceContent:Returns an HTML widget with CSP metadata.returnResourceContent(contenthtmlbodyMy Widget/body/html,mime_typetext/html,meta{csp:script-src self})字段content: 实际的资源内容可以是str类型文本或者byte类型二进制。mime_type: 内容的MIME类型可选的对于文本默认值是text/plain, 对于二进制默认值是application/octet-streammeta: 可选的元数据字典在_meta字段中用于运行时内容安全策略头缓存提示等# Binary content with metadatamcp.resource(images://logo)defget_logo()-ResourceContent:Returns a logo image with caching metadata.withopen(logo.png,rb)asf:image_dataf.read()returnResourceContent(contentimage_data,mime_typeimage/png,meta{cache-control:max-age3600})你仍然可以从资源函数中返回普通的字符串或字节 ——ResourceContent 是可选的仅在你需要包含元数据时使用。四、禁用资源您可以通过启用或禁用资源和模板来控制它们的可见性和可用性。禁用的资源不会出现在可用资源或模板列表中且尝试读取禁用的资源会导致 “未知资源” 错误。默认所有的资源是启用的。mcp.resource(data://secret,enabledFalse)defget_secret_data():This resource is currently disabled.returnSecret data动态的切换mcp.resource(data://config)defget_config():return{version:1}# Disable and re-enable the resourceget_config.disable()get_config.enable()五、访问MCP Context和Tools一样资源和资源模板可以通过 Context 对象访问额外的 MCP 信息和功能。要访问它请在资源函数中添加一个带有 Context 类型注释的参数。fromfastmcpimportFastMCP,Context mcpFastMCP(nameDataServer)mcp.resource(resource://system-status)asyncdefget_system_status(ctx:Context)-dict:Provides system status information.return{status:operational,request_id:ctx.request_id}mcp.resource(resource://{name}/details)asyncdefget_details(name:str,ctx:Context)-dict:Get details for a specific name.return{name:name,accessed_at:ctx.request_id}六、异步资源对于执行 I/O 操作例如从数据库或网络读取数据的资源函数请使用async def以避免阻塞服务器。importaiofilesfromfastmcpimportFastMCP mcpFastMCP(nameDataServer)mcp.resource(file:///app/data/important_log.txt,mime_typetext/plain)asyncdefread_important_log()-str:Reads content from a specific log file asynchronously.try:asyncwithaiofiles.open(/app/data/important_log.txt,moder)asf:contentawaitf.read()returncontentexceptFileNotFoundError:returnLog file not found.七、资源类虽然 mcp.resource 非常适合动态内容但您可以使用 mcp.add_resource () 和具体的 Resource 子类直接注册预定义资源如静态文件或简单文本。frompathlibimportPathfromfastmcpimportFastMCPfromfastmcp.resourcesimportFileResource,TextResource,DirectoryResource mcpFastMCP(nameDataServer)# 1. Exposing a static file directlyreadme_pathPath(./README.md).resolve()ifreadme_path.exists():# Use a file:// URI schemereadme_resourceFileResource(uriffile://{readme_path.as_posix()},pathreadme_path,# Path to the actual filenameREADME File,descriptionThe projects README.,mime_typetext/markdown,tags{documentation})mcp.add_resource(readme_resource)# 2. Exposing simple, predefined textnotice_resourceTextResource(uriresource://notice,nameImportant Notice,textSystem maintenance scheduled for Sunday.,tags{notification})mcp.add_resource(notice_resource)# 3. Using a custom key different from the URIspecial_resourceTextResource(uriresource://common-notice,nameSpecial Notice,textThis is a special notice with a custom storage key.,)mcp.add_resource(special_resource,keyresource://custom-key)# 4. Exposing a directory listingdata_dir_pathPath(./app_data).resolve()ifdata_dir_path.is_dir():data_listing_resourceDirectoryResource(uriresource://data-files,pathdata_dir_path,# Path to the directorynameData Directory Listing,descriptionLists files available in the data directory.,recursiveFalse# Set to True to list subdirectories)mcp.add_resource(data_listing_resource)# Returns JSON list of files7.1 公共资源类TextResource简单字符内容BinaryResource原始二进制内容FileResource读取本地文件HttpResource从HTTPS URL获取内容require httpx)DirectoryResource列举本地目录文件返回 JSON)FunctionResource内部类7.2 自定义资源key使用 mcp.add_resource () 直接添加资源时你可以选择性地提供一个自定义存储键# Creating a resource with standard URI as the keyresourceTextResource(uriresource://data)mcp.add_resource(resource)# Will be stored and accessed using resource://data# Creating a resource with a custom keyspecial_resourceTextResource(uriresource://special-data)mcp.add_resource(special_resource,keyinternal://data-v2)# Will be stored and accessed using internal://data-v2请注意此参数仅在直接使用 add_resource () 时可用而不能通过 resource 装饰器使用因为使用装饰器时会显式提供 URI。八、通知当资源或模板被添加、启用或禁用时FastMCP 会自动向已连接的客户端发送 notifications/resources/list_changednotifications。这使得客户端能够与当前的资源集保持同步而无需手动轮询更改。mcp.resource(data://example)defexample_resource()-str:returnHello!# These operations trigger notifications:mcp.add_resource(example_resource)# Sends resources/list_changed notificationexample_resource.disable()# Sends resources/list_changed notificationexample_resource.enable()# Sends resources/list_changed notification只有当这些操作在活跃的 MCP 请求上下文中发生时例如从工具或其他 MCP 操作中调用时才会发送通知。服务器初始化期间执行的操作不会触发通知。客户端可以使用消息处理器来处理这些通知以自动刷新其资源列表或更新其界面。九、注解FastMCP 允许您通过注解向资源添加专门的元数据。这些注解向客户端应用程序传达资源的行为方式而不会占用大语言模型提示中的令牌上下文。mcp.resource( data://config, annotations{ readOnlyHint: True, idempotentHint: True } ) def get_config() - dict: Get application configuration. return {version: 1.0, debug: False}请记住注释有助于提升用户体验但应被视为指导性提示。它们帮助客户端应用程序呈现合适的用户界面元素并优化访问模式但其本身不会强制实施某种行为。始终要注重让你的注释准确反映你的资源实际能做什么。十、资源模板资源模板允许客户端请求其内容取决于嵌入在 URI 中的参数的资源。使用相同的 mcp.resource 装饰器来定义模板但在 URI 字符串中包含{parameter_name}占位符并在函数签名中添加相应的参数。资源模板与常规资源共享大多数配置选项名称、描述、mime_type、标签、注释但增加了定义映射到函数参数的 URI 参数的功能。资源模板会为每组唯一的参数生成一个新资源这意味着资源可以按需动态创建。例如如果注册了资源模板“user://profile/{name}”MCP 客户端可以请求“user://profile/带有 * args 的函数不支持作为资源模板。不过与工具和提示不同资源模板支持 **kwargs因为 URI 模板定义了特定的参数名称这些参数名称会被收集并作为关键字参数传递。fromfastmcpimportFastMCP mcpFastMCP(nameDataServer)# Template URI includes {city} placeholdermcp.resource(weather://{city}/current)defget_weather(city:str)-dict:Provides weather information for a specific city.# In a real implementation, this would call a weather API# Here were using simplified logic for example purposesreturn{city:city.capitalize(),temperature:22,condition:Sunny,unit:celsius}# Template with multiple parameters and annotationsmcp.resource(repos://{owner}/{repo}/info,annotations{readOnlyHint:True,idempotentHint:True})defget_repo_info(owner:str,repo:str)-dict:Retrieves information about a GitHub repository.# In a real implementation, this would call the GitHub APIreturn{owner:owner,name:repo,full_name:f{owner}/{repo},stars:120,forks:48}十一、通配符参数资源模板支持可匹配多个路径段的通配符参数。标准参数{param}仅匹配单个路径段且不会跨越“/”边界而通配符参数{param*}则可以捕获包括斜杠在内的多个段。通配符会捕获所有后续路径段直到 URI 模板中已定义的部分无论是文字还是另一个参数。这使你能够在单个 URI 模板中使用多个通配符参数。fromfastmcpimportFastMCP mcpFastMCP(nameDataServer)# Standard parameter only matches one segmentmcp.resource(files://{filename})defget_file(filename:str)-str:Retrieves a file by name.# Will only match files://single-segmentreturnfFile content for:{filename}# Wildcard parameter can match multiple segmentsmcp.resource(path://{filepath*})defget_path_content(filepath:str)-str:Retrieves content at a specific path.# Can match path://docs/server/resources.mdxreturnfContent at path:{filepath}# Mixing standard and wildcard parametersmcp.resource(repo://{owner}/{path*}/template.py)defget_template_file(owner:str,path:str)-dict:Retrieves a file from a specific repository and path, but only if the resource ends with template.py# Can match repo://jlowin/fastmcp/src/resources/template.pyreturn{owner:owner,path:path/template.py,content:fFile at{path}/template.py in{owner}s repository}通配符参数在以下情况下很有用处理文件路径或层级数据时创建需要捕获可变长度路径段的 API 时构建类似于 REST API 的类 URL 模式时请注意与常规参数一样每个通配符参数在函数签名中仍必须是命名参数并且所有必需的函数参数都必须出现在 URI 模板中。十二、查询参数查询参数提供了一种简洁的方式可向资源传递可选配置而不会使路径变得杂乱。查询参数必须是可选的函数参数具有默认值而路径参数则对应必填的函数参数。这确保了清晰的区分必需的数据放在路径中可选的配置放在查询参数中。语法格式{?param1,param2}fromfastmcpimportFastMCP mcpFastMCP(nameDataServer)# Basic query parametersmcp.resource(data://{id}{?format})defget_data(id:str,format:strjson)-str:Retrieve data in specified format.ifformatxml:returnfdata id{id} /returnf{{id: {id}}}# Multiple query parameters with type coercionmcp.resource(api://{endpoint}{?version,limit,offset})defcall_api(endpoint:str,version:int1,limit:int10,offset:int0)-dict:Call API endpoint with pagination.return{endpoint:endpoint,version:version,limit:limit,offset:offset,results:fetch_results(endpoint,version,limit,offset)}# Query parameters with wildcardsmcp.resource(files://{path*}{?encoding,lines})defread_file(path:str,encoding:strutf-8,lines:int100)-str:Read file with optional encoding and line limit.returnread_file_content(path,encoding,lines)FastMCP 会根据函数的类型提示int、float、bool、str自动将查询参数的字符串值强制转换为正确的类型。12.1 查询参数的隐藏若要向客户端完全隐藏可选参数始终使用默认值只需从 URI 模板中省略它们即可。# Clients CAN override max_results via query stringmcp.resource(search://{query}{?max_results})defsearch_configurable(query:str,max_results:int10)-dict:return{query:query,limit:max_results}# Clients CANNOT override max_results (not in URI template)mcp.resource(search://{query})defsearch_fixed(query:str,max_results:int10)-dict:return{query:query,limit:max_results}12.3 模版参数规则FastMCP 在创建资源模板时会执行以下验证规则必需的函数参数无默认值必须出现在 URI 路径模板中查询参数用 {?param} 语法指定必须是带有默认值的可选函数参数所有 URI 模板参数路径和查询都必须作为函数参数存在可选函数参数那些带有默认值的可以作为查询参数包含在内{?param}—— 客户端可以通过查询字符串覆盖从 URI 模板中省略 —— 始终使用默认值不向客户端暴露用于替代路径模板 —— 支持通过多种方式访问同一资源一个函数的多个模板通过手动应用装饰器创建多个资源模板以不同的 URI 模式暴露同一个函数fromfastmcpimportFastMCP mcpFastMCP(nameDataServer)# Define a user lookup function that can be accessed by different identifiersdeflookup_user(name:str|NoneNone,email:str|NoneNone)-dict:Look up a user by either name or email.ifemail:returnfind_user_by_email(email)# pseudocodeelifname:returnfind_user_by_name(name)# pseudocodeelse:return{error:No lookup parameters provided}# Manually apply multiple decorators to the same functionmcp.resource(users://email/{email})(lookup_user)mcp.resource(users://name/{name})(lookup_user)十三、错误处理如果你的资源函数遇到错误你可以抛出一个标准的 Python 异常如 ValueError、TypeError、FileNotFoundError、自定义异常等或者一个FastMCP ResourceError。默认情况下所有异常包括其详细信息都会被记录并转换为 MCP 错误响应发送回客户端 LLM。这有助于 LLM 理解故障并做出适当的反应。如果出于安全原因你想隐藏内部错误详情你可以在创建 FastMCP 实例时使用mask_error_detailsTrue参数mcpFastMCP(nameSecureServer,mask_error_detailsTrue)或者fromfastmcpimportFastMCPfromfastmcp.exceptionsimportResourceError mcpFastMCP(nameDataServer)mcp.resource(resource://safe-error)deffail_with_details()-str:This resource provides detailed error information.# ResourceError contents are always sent back to clients,# regardless of mask_error_details settingraiseResourceError(Unable to retrieve data: file not found)mcp.resource(resource://masked-error)deffail_with_masked_details()-str:This resource masks internal error details when mask_error_detailsTrue.# This message would be masked if mask_error_detailsTrueraiseValueError(Sensitive internal file path: /etc/secrets.conf)mcp.resource(data://{id})defget_data_by_id(id:str)-dict:Template resources also support the same error handling pattern.ifidsecure:raiseValueError(Cannot access secure data)elifidmissing:raiseResourceError(Data ID missing not found in database)return{id:id,value:data}当 mask_error_detailsTrue 时只有来自 ResourceError 的错误消息会包含详细信息其他异常将被转换为一条通用消息。十四、重复注册您可以配置 FastMCP 服务器如何处理尝试注册具有相同 URI 的多个资源或模板的情况。在 FastMCP 初始化期间使用on_duplicate_resources设置即可。fromfastmcpimportFastMCP mcpFastMCP(nameResourceServer,on_duplicate_resourceserror# Raise error on duplicates)mcp.resource(data://config)defget_config_v1():return{version:1}# This registration attempt will raise a ValueError because# data://config is already registered and the behavior is error.# mcp.resource(data://config)# def get_config_v2(): return {version: 2}重复行为选项如下“warn”默认记录警告新资源 / 模板会替换旧资源 / 模板。“error”引发 ValueError阻止重复注册。“replace”静默地用新资源 / 模板替换现有资源 / 模板。“ignore”保留原始资源 / 模板忽略新的注册尝试。
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!

如何做谷歌优化网站seo 教程

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容: 创建一个GitTortoise新手教学应用,包含:1. 交互式Git基础概念讲解;2. 可视化的工作流演示;3. 带引导的实操练习环境;4. 常…

张小明 2026/1/3 16:42:51 网站建设

最火爆的国际贸易网站网站开发技术题目

智能政策分析系统:从零到一的AI架构演进指南 【免费下载链接】langchain 项目地址: https://gitcode.com/gh_mirrors/lan/langchain 在数字化转型浪潮中,智能政策分析系统正成为政府决策和产业规划的重要支撑。随着AI技术的成熟,构建…

张小明 2026/1/4 15:40:14 网站建设

网站怎么做跳转linux下搭建wordpress

夏普 Zaurus PDA 黑客工具介绍 在网络安全和渗透测试领域,有许多工具可以用于不同的目的,如端口扫描、建立安全隧道、测试防火墙规则等。本文将介绍一些可用于夏普 Zaurus PDA 的工具及其功能、下载地址和使用方法。 1. BING Bing 是一个简单的脚本,可自动执行端口扫描。…

张小明 2026/1/5 0:41:40 网站建设

免费建设网站的画出wordpress新建header

如何三步实现专业级智能瞄准?免费AI自瞄完整方案揭秘 【免费下载链接】RookieAI_yolov8 基于yolov8实现的AI自瞄项目 项目地址: https://gitcode.com/gh_mirrors/ro/RookieAI_yolov8 还在为游戏中的瞄准难题而烦恼吗?面对快速移动的敌人&#xff…

张小明 2026/1/10 18:56:16 网站建设

怎么用百度云做网站空间畜牧业网站模板

实时内核要求与Linux实时实现路径解析 1. 实时内核的常见要求 实时系统旨在及时且恰当地处理内外部事件,这对内核提出了一系列严格要求。 1.1 细粒度可抢占内核 实时内核需能尽快从低优先级任务切换到高优先级任务,此切换时间即抢占粒度,最长等待重新调度时间为最坏情况…

张小明 2026/1/11 3:55:21 网站建设

房产中介网站排名wordpress 页面挂件

1、什么是接口测试?为什么它在软件开发过程中很重要? 接口测试是一种测试方法,用于验证不同软件组件之间的通信和交互是否正常。它在软件开发过程中很重要,因为任何系统都会依赖于多个组件的协同工作。接口测试可以确保这些组件之…

张小明 2026/1/7 16:06:39 网站建设