调用FastMCP Server提示缺失会话ID,如何解决?
解决FastMCP服务请求中"Missing session ID"错误
问题场景
服务端代码
from fastmcp import FastMCP, Context mcp = FastMCP("Demo 🚀") @mcp.tool def add(a: int, b: int) -> int: """Add two numbers""" return a + b @mcp.tool def hello(ctx: Context): ctx.info("in Hello!") return {"Respone": "Hello!"} # Static resource @mcp.resource("config://version") def get_version(ctx: Context): ctx.info("Sono in get_version!") return "2.0.1" if __name__ == "__main__": mcp.run(transport='streamable-http')
测试用curl命令
curl --request POST \ --url http://localhost:8000/mcp/tool/hello \ --header 'accept: application/json, text/event-stream' \ --header 'content-type: application/json' \ --header 'x-session-id: my-test-session-123' \ --data '{ "jsonrpc": "2.0", "method": "hello", "id": 1 }'
错误响应
{ "jsonrpc": "2.0", "id": "server-error", "error": { "code": -32600, "message": "Bad Request: Missing session ID" } }
解决方案
方案1:修改请求体,在params中传入session ID
FastMCP的streamable-http传输模式默认要求session ID放在请求体的params字段中,而非HTTP请求头。修改后的curl命令如下:
curl --request POST \ --url http://localhost:8000/mcp/tool/hello \ --header 'accept: application/json, text/event-stream' \ --header 'content-type: application/json' \ --data '{ "jsonrpc": "2.0", "method": "hello", "id": 1, "params": { "sess_id": "my-test-session-123" } }'
方案2:修改服务端配置,允许从HTTP头获取session ID
如果希望保留通过x-session-id头传递session ID的方式,只需在初始化FastMCP实例时开启session_from_header参数:
mcp = FastMCP("Demo 🚀", session_from_header=True)
修改后原curl命令即可正常工作,无需调整请求体。
内容的提问来源于stack exchange,提问作者Stefano G.
相关产品推荐
相关产品推荐

