深圳官方网站建设wordpress linode

张小明 2026/1/7 6:26:54
深圳官方网站建设,wordpress linode,东莞++网站建设,udacity 网站开发在MCP中#xff0c;Tools是一个函数#xff0c;它可以被用于执行动作或者访问外部系统。 一、如何创建一个Tools? 最简单的方法就是用mcp.tool注解一个python的函数。 服务端#xff1a; from fastmcp import FastMCPmcp FastMCP(nameCalculatorServer)mcp.to…在MCP中Tools是一个函数它可以被用于执行动作或者访问外部系统。一、如何创建一个Tools?最简单的方法就是用mcp.tool注解一个python的函数。服务端fromfastmcpimportFastMCP mcpFastMCP(nameCalculatorServer)mcp.tooldefadd(a:int,b:int)-int:Adds two integer numbers together.returnabif__name____main__:mcp.run(transporthttp,# 使用HTTP传输host0.0.0.0,# 允许外部访问port8000# 端口)带有 * args 或 **kwargs 的函数不支持作为工具。存在这一限制是因为 FastMCP 需要为 MCP 协议生成完整的参数 schema而这对于可变参数列表来说是无法实现的。客户端importasynciofromfastmcpimportClient clientClient(http://localhost:8000/mcp)asyncdefcall_tool(name:str):asyncwithclient:resultawaitclient.call_tool(name,{a:2,b:3})print(result)asyncio.run(call_tool(add))装饰器参数说明name str | None 设置通过 MCP 暴露的明确工具名称。如果未提供则使用函数名称description str | None 提供通过 MCP 公开的描述。如果设置了此描述那么函数的文档字符串将为此目的而被忽略。tags set[str] | None 一组用于对工具进行分类的字符串。服务器以及在某些情况下的客户端可以使用这些字符串来筛选或分组可用的工具。enabled bool default:“True” 一个用于启用或禁用该工具的布尔值。二、同步与异步FastMCP 是一个优先支持异步的框架它能无缝支持异步async def和同步def函数作为工具。对于 I/O 密集型操作异步工具是更优选择可保持服务器的响应性。虽然同步工具在 FastMCP 中能无缝运行但在执行过程中可能会阻塞事件循环。对于 CPU 密集型或可能存在阻塞的同步操作可考虑其他策略。一种方法是使用 anyioFastMCP 内部已在使用将它们包装为异步函数。同步示例在第一章节已经有了这里举一个异步的例子服务端importasyncioimportanyiofromfastmcpimportFastMCP mcpFastMCP()defcpu_intensive_task(data:str)-str:# Some heavy computation that could block the event loopreturndatamcp.toolasyncdefwrapped_cpu_task(data:str)-str:CPU-intensive task wrapped to prevent blocking.returnawaitanyio.to_thread.run_sync(cpu_intensive_task,data)# 服务启动入口asyncdefmain():# 方式1启动 FastMCP 本地服务默认基于 HTTP 或 WebSocket取决于 FastMCP 版本# 如需自定义端口/地址可传入参数例如host0.0.0.0, port8000awaitmcp.run_http_async(host127.0.0.1,# 绑定本地地址外部访问可改为 0.0.0.0port8000,# 服务端口)if__name____main__:asyncio.run(main())客户端importasynciofromfastmcpimportClient clientClient(http://localhost:8000/mcp)asyncdefcall_tool(name:str):asyncwithclient:resultawaitclient.call_tool(wrapped_cpu_task,{data:name})print(result)if__name____main__:asyncio.run(call_tool(apple))三、类型声明FastMCP 支持多种类型注解包括所有的 Pydantic 类型, 在定义Tool函数的时候建议添加上类型比如name: str [str] 就是类型声明。Type AnnotationExampleDescriptionBasic typesint, float, str, boolSimple scalar valuesBinary databytesBinary content (raw strings, not auto-decoded base64)Date and Timedatetime, date, timedeltaDate and time objects (ISO format strings)Collection typeslist[str], dict[str, int], set[int]Collections of itemsOptional typesfloatNone, Optional[float]Union typesstrint, Union[str, int]Constrained typesLiteral[“A”, “B”], EnumParameters with specific allowed valuesPathsPathFile system paths (auto-converted from strings)UUIDsUUIDUniversally unique identifiers (auto-converted from strings)Pydantic modelsUserDataComplex structured data with validation四、验证模式在LLM调用Tools的时候需要传参默认情况下FastMCP 采用 Pydantic 的灵活验证机制会将兼容的输入强制转换为与类型注解匹配的形式。这提高了与大型语言模型客户端的兼容性这些客户端可能会发送值的字符串表示形式例如对于整数参数发送 “10”。如果需要更严格的验证以拒绝任何类型不匹配的情况您可以启用严格输入验证。严格模式使用 MCP SDK 内置的 JSON 模式验证在将输入传递给函数之前根据精确的模式对其进行验证4.1 宽松的验证Tools定义的类型是int, 在调用的时候传str类型MCP自动转换int类型。服务端fromfastmcpimportFastMCP mcpFastMCP(StrictServer,strict_input_validationFalse)mcp.tooldefadd_numbers(a:int,b:int)-int:Add two numbers.returnabif__name____main__:mcp.run(transporthttp,# 使用HTTP传输host0.0.0.0,# 允许外部访问port8000# 端口)客户端importasynciofromfastmcpimportClient clientClient(http://localhost:8000/mcp)asyncdefcall_tool(name:str):asyncwithclient:resultawaitclient.call_tool(name,{a:2,b:3})print(result)asyncio.run(call_tool(add_numbers))4.2 严格的验证服务端fromfastmcpimportFastMCP mcpFastMCP(StrictServer,strict_input_validationTrue)mcp.tooldefadd_numbers(a:int,b:int)-int:Add two numbers.returnabif__name____main__:mcp.run(transporthttp,# 使用HTTP传输host0.0.0.0,# 允许外部访问port8000# 端口)客户端importasynciofromfastmcpimportClient clientClient(http://localhost:8000/mcp)asyncdefcall_tool(name:str):asyncwithclient:resultawaitclient.call_tool(name,{a:2,b:3})print(result)asyncio.run(call_tool(add_numbers))调用的时候将会报异常Traceback(most recent call last):FileD:\code\mcp-demo\tools\flexible_client.py,line17,inmoduleasyncio.run(call_tool(add_numbers))~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^FileD:\Python\Python313\Lib\asyncio\runners.py,line195,inrunreturnrunner.run(main)~~~~~~~~~~^^^^^^FileD:\Python\Python313\Lib\asyncio\runners.py,line118,inrunreturnself._loop.run_until_complete(task)~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^FileD:\Python\Python313\Lib\asyncio\base_events.py,line725,inrun_until_completereturnfuture.result()~~~~~~~~~~~~~^^FileD:\code\mcp-demo\tools\flexible_client.py,line14,incall_tool resultawaitclient.call_tool(name,{a:2,b:3})^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^FileD:\code\mcp-demo\.venv\Lib\site-packages\fastmcp\client\client.py,line969,incall_toolraiseToolError(msg)fastmcp.exceptions.ToolError:Input validation error:3isnotoftypeinteger五、参数元数据可以通过多种方式提供有关参数的额外元数据5.1 简单字符串描述fromtypingimportAnnotatedmcp.tooldefprocess_image(image_url:Annotated[str,URL of the image to process],resize:Annotated[bool,Whether to resize the image]False,width:Annotated[int,Target width in pixels]800,format:Annotated[str,Output image format]jpeg)-dict:Process an image with optional resizing.# Implementation...5.2 使用Field进行描述方式一 在Annotated中使用FieldfromtypingimportAnnotatedfrompydanticimportFieldmcp.tooldefprocess_image(image_url:Annotated[str,Field(descriptionURL of the image to process)],resize:Annotated[bool,Field(descriptionWhether to resize the image)]False,width:Annotated[int,Field(descriptionTarget width in pixels,ge1,le2000)]800,format:Annotated[Literal[jpeg,png,webp],Field(descriptionOutput image format)]jpeg)-dict:Process an image with optional resizing.# Implementation...方式二将 Field 用作默认值不过更推荐使用 Annotated 方法mcp.tooldefsearch_database(query:strField(descriptionSearch query string),limit:intField(10,descriptionMaximum number of results,ge1,le100))-list:Search the database with the provided query.# Implementation...5.3 对LLM隐藏参数要在运行时注入值而不将其暴露给 LLM例如用户 ID、凭据或数据库连接请使用带有 Depends () 的依赖注入。使用 Depends () 的参数会自动从工具架构中排除fromfastmcpimportFastMCPfromfastmcp.dependenciesimportDepends mcpFastMCP()defget_user_id()-str:returnuser_123# Injected at runtimemcp.tooldefget_user_details(user_id:strDepends(get_user_id))-str:# user_id is injected by the server, not provided by the LLMreturnfDetails for{user_id}六、返回值FastMCP 工具可以以两种互补的格式返回数据传统内容块如文本和图像和结构化输出机器可读取的 JSON。当你添加返回类型注释时FastMCP 会自动生成输出模式来验证结构化数据并使客户端能够将结果反序列化为 Python 对象。6.1 ContentFastMCP 会自动将工具返回值转换为适当的 MCP 内容块返回类型转换后的MCP内容块strSent as TextContentbytesBase64 encoded and sent as BlobResourceContents (within an EmbeddedResource)fastmcp.utilities.types.ImageSent as ImageContentfastmcp.utilities.types.AudioSent as AudioContentfastmcp.utilities.types.FileSent as base64-encoded EmbeddedResource示例fromfastmcp.utilities.typesimportImage,Audio,Filemcp.tooldefget_chart()-Image:Generate a chart image.returnImage(pathchart.png)mcp.tooldefget_multiple_charts()-list[Image]:Return multiple charts.return[Image(pathchart1.png),Image(pathchart2.png)]注意事项以上类型转换的条件直接返回作为List的一部分返回其他情况需要手动转换# ✅ Automatic conversionreturnImage(pathchart.png)return[Image(pathchart1.png),text content]# ❌ Will not be automatically convertedreturn{image:Image(pathchart.png)}# ✅ Manual conversion for nested usereturn{image:Image(pathchart.png).to_image_content()}6.2 结构化输出当你的工具返回具有 JSON 对象表示形式的数据时FastMCP 会自动创建与传统内容并存的结构化输出。这提供了机器可读取的 JSON 数据客户端可以将其反序列化为 Python 对象。自动结构化内容规则类对象结果dict、Pydantic 模型、dataclasses→ 始终成为结构化内容即使没有输出模式非对象结果int、str、list→ 只有存在用于验证 / 序列化它们的输出模式时才会成为结构化内容所有结果 → 为了向后兼容始终成为传统内容块6.2.1 返回类对象dict、Pydantic 模型、dataclasses当你的工具返回字典、数据类或 Pydantic 模型时FastMCP 会自动从中创建结构化内容。这种结构化内容包含实际的对象数据便于客户端反序列化为原生对象。返回mcp.tooldefget_user_data(user_id:str)-dict:Get user data.return{name:Alice,age:30,active:True}结构化返回{content:[{type:text,text:{\n \name\: \Alice\,\n \age\: 30,\n \active\: true\n}}],structuredContent:{name:Alice,age:30,active:true}}6.2.2返回非对象结果int、str、list6.2.2.1 不带类型注解(没有说明函数返回的类型)返回mcp.tooldefcalculate_sum(a:int,b:int):Calculate sum without return annotation.returnab# Returns 8实际结果CallToolResult(content[TextContent(typetext,text5,annotationsNone,metaNone)],structured_contentNone,metaNone,dataNone,is_errorFalse)6.2.2.2 带类型注解(没有说明函数返回的类型)返回mcp.tooldefcalculate_sum(a:int,b:int)-int:Calculate sum without return annotation.returnab# Returns 8实际结果CallToolResult(content[TextContent(typetext,text5,annotationsNone,metaNone)],structured_content{result:5},metaNone,data5,is_errorFalse)
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!

专业做互联网招聘的网站跨境电商网站模板

Moonlight安卓串流:3大场景实现手机畅玩PC游戏 【免费下载链接】moonlight-android GameStream client for Android 项目地址: https://gitcode.com/gh_mirrors/mo/moonlight-android Moonlight安卓串流项目通过创新的游戏串流技术,将PC端的3A大作…

张小明 2026/1/2 5:39:29 网站建设

无锡做网站优化多少钱wordpress 目录下拉框

Linly-Talker:中英文双语驱动的数字人交互新范式 在虚拟主播深夜直播带货、AI客服24小时在线应答、跨国会议自动翻译同步进行的今天,人机交互早已不再局限于键盘与屏幕。数字人作为新一代交互界面的核心载体,正以前所未有的速度渗透进商业、教…

张小明 2026/1/4 8:03:47 网站建设

做美食网站的目的特殊字体

深度解析时间序列可视化:从业务痛点到大屏展示的完整方案 【免费下载链接】mermaid 项目地址: https://gitcode.com/gh_mirrors/mer/mermaid 在当今数据驱动的商业环境中,时间序列数据的可视化展示已成为企业决策支持系统不可或缺的一环。无论是…

张小明 2026/1/1 21:13:24 网站建设

想开一个外企的网站怎么超做网络营销推广方式案例分析

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容: 创建一个交互式DockerHub新手教程应用,通过步骤式引导帮助用户完成从注册账号、构建Docker镜像到发布到DockerHub的全过程。包含实时命令行模拟器和常见问题解答。使用V…

张小明 2026/1/2 5:03:06 网站建设

做淘宝客怎么建网站东莞工厂

数据简介:城市二手房均价是指在特定行政区域和统计周期(如月度或年度)内,所有完成产权交易的二手住宅总成交金额与成交套数的算术平均值。数据可以表征供需关系动态为开发商定价策略(如竞品对标)和ZF调控政…

张小明 2026/1/3 7:01:10 网站建设

什么是a站长沙望城区发布最新通告

AutoGPT任务执行风险预警系统设计理念 在生成式AI迈向自主决策的今天,我们正见证一场从“我问你答”到“你替我做”的范式跃迁。以AutoGPT为代表的智能体不再被动响应指令,而是能接收一个模糊目标——比如“帮我准备下周的产品发布会材料”——然后自行拆…

张小明 2026/1/2 3:51:09 网站建设