FastMCP调用工具时Context日志无法在控制台显示的问题
FastMCP Context日志不显示问题
问题描述
按照FastMCP文档使用Context对象在工具中记录日志,工具调用正常,但服务器端仅能看到API访问日志,工具内通过ctx.debug()/ctx.info()等输出的日志完全不显示。使用版本:FastMCP 2.2.10。
工具代码:
from fastmcp import FastMCP, Context from typing import Dict, Any, Optional server = FastMCP("Demo") @server.tool() async def analyze_data(data: list[float], ctx: Context) -> dict: """Analyze numerical data with logging.""" await ctx.debug("Starting analysis of numerical data") await ctx.info(f"Analyzing {len(data)} data points") try: result = sum(data) / len(data) await ctx.info(f"Analysis complete, average: {result}") return {"average": result, "count": len(data)} except ZeroDivisionError: await ctx.warning("Empty data list provided") return {"error": "Empty data list"} except Exception as e: await ctx.error(f"Analysis failed: {str(e)}") raise
客户端调用日志显示工具已成功执行:
{ 'messages': [ HumanMessage(content='Analyse this data 1.0, 2.01', additional_kwargs={}, response_metadata={}, id='45085e8f-2e39-4ef2-83a8-3958309bd92d'), AIMessage(content="I'll analyze the numerical data you've provided: 1.0 and 2.01. Let me do that for you.", additional_kwargs={'tool_calls': [{'id': 'toolu_bdrk_01URHoQ8iZ3BF5xsvB9osB6Z', 'function': {'arguments': '{"data":[1.0,2.01]}', 'name': 'analyze_data'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 91, 'prompt_tokens': 2398, 'total_tokens': 2489, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'us.anthropic.claude-3-7-sonnet-20250219-v1:0', 'system_fingerprint': None, 'id': 'msg_bdrk_01G3NGwkfV5KEMD71DU9iTTX', 'service_tier': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run--d75ffdcb-0dc1-479d-acb8-5f19fac793a8-0', tool_calls=[{'name': 'analyze_data', 'args': {'data': [1.0, 2.01]}, 'id': 'toolu_bdrk_01URHoQ8iZ3BF5xsvB9osB6Z', 'type': 'tool_call'}], usage_metadata={'input_tokens': 2398, 'output_tokens': 91, 'total_tokens': 2489, 'input_token_details': {}, 'output_token_details': {}}), ToolMessage(content='{\n "average": 1.505,\n "count": 2\n}', name='analyze_data', id='13ce1458-e927-4985-8a8b-71580b0d5791', tool_call_id='toolu_bdrk_01URHoQ8iZ3BF5xsvB9osB6Z'), AIMessage(content="Here's the analysis of the numerical data you provided:\n- Data points: 1.0, 2.01\n- Count: 2 data points\n- Average (mean): 1.505\n\nThis is a simple statistical summary of the two values you provided. If you'd like more detailed analysis, please let me know.", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 95, 'prompt_tokens': 2518, 'total_tokens': 2613, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'us.anthropic.claude-3-7-sonnet-20250219-v1:0', 'system_fingerprint': None, 'id': 'msg_bdrk_01R4j4Bycdz3SkeoG2rGySfL', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--ec20a5ac-5626-4938-9954-b9ef9dd29d73-0', usage_metadata={'input_tokens': 2518, 'output_tokens': 95, 'total_tokens': 2613, 'input_token_details': {}, 'output_token_details': {}})] }
解决方法
1. 调整全局日志级别
FastMCP默认日志级别可能高于你使用的级别(比如默认是INFO,DEBUG日志会被过滤),需要显式设置全局日志级别:
import logging from fastmcp import FastMCP, Context # 全局设置日志级别为DEBUG,确保所有级别的日志都能输出 logging.basicConfig(level=logging.DEBUG) server = FastMCP("Demo") # 工具代码保持不变 @server.tool() async def analyze_data(data: list[float], ctx: Context) -> dict: # ... 原有代码 ...
2. 检查ASGI服务器日志配置
如果用uvicorn等ASGI服务器启动FastMCP,需要确保服务器本身的日志级别也配置正确,避免日志被二次过滤。启动时加上--log-level debug参数:
uvicorn your_server_module:app --log-level debug
3. 排查Context日志转发问题
可以先在工具中直接使用标准logging模块打印日志,验证基础日志功能是否正常:
@server.tool() async def analyze_data(data: list[float], ctx: Context) -> dict: logging.debug("Direct debug log from standard logging") await ctx.debug("Starting analysis of numerical data") # ... 原有代码 ...
如果标准日志能显示但Context日志不能,说明FastMCP的Context日志转发存在问题,建议:
- 升级FastMCP到最新版本,修复可能存在的版本bug
- 查看FastMCP源码确认Context日志的实现逻辑,是否需要额外配置
4. 确认FastMCP初始化时的日志参数
检查FastMCP初始化是否支持日志相关参数,部分版本可能需要显式传入日志配置:
server = FastMCP("Demo", log_level=logging.DEBUG)
内容的提问来源于stack exchange,提问作者mano_ksp
相关产品推荐
相关产品推荐

