FastMCP客户端Bearer令牌认证配置方式
FastMCP的Bearer Token认证仅适用于HTTP传输。客户端可将令牌字符串交给auth参数自动格式化,也可显式使用BearerAuth类,或在传输实例上自定义请求头以适配非标准认证方案。
Bearer Token认证仅与基于HTTP的运输相关. 您可以配置要使用的 FastMCP 客户端 **无记名认证** 。这最适合服务账户、长寿的 API 密钥、 CI / CD 、 单独管理认证的应用程序, 或其他非交互认证方法。 无记名符号授权给任何呈现它的人。 它通常是一个 JSON Web Token( JWT) , 但是它可以是服务器接受的任何不透明字符串。 客户端发送到 `Authorization` 每个 HTTP 请求的页眉,使用 `Bearer` 计划 : ```http Authorization: Bearer <token> ``` ## 客户端使用 最直截了当的方式是使用先前存在的熊鼠标志 把它作为串子提供给 `auth` 参数 `fastmcp.Client` 或运输实例。FastMCP将自动为 `Authorization` 头和无记名计划。 如果您使用字符串符号, 请不要包括 `Bearer` 前缀。 FastMCP 将为您添加它。 ```python {5} from fastmcp import Client async with Client( "https://your-server.fastmcp.app/mcp", auth="<your-token>", ) as client: await client.list_tools() ``` 您也可以为运输实例提供一个比勒令牌,例如: `StreamableHttpTransport` 或 时 间 `SSETransport`: ```python {6} from fastmcp import Client from fastmcp.client.transports import StreamableHttpTransport transport = StreamableHttpTransport( "https://your-server.fastmcp.app/mcp", auth="<your-token>", ) async with Client(transport) as client: await client.list_tools() ``` ## `BearerAuth` 帮助者 如果您更喜欢更加明确,而不依赖FastMCP来转换您的字符串符号,您可以使用 `BearerAuth` 学习自己, 执行 `httpx2.Auth` 接口。 ```python {6} from fastmcp import Client from fastmcp.client.auth import BearerAuth async with Client( "https://your-server.fastmcp.app/mcp", auth=BearerAuth(token="<your-token>"), ) as client: await client.list_tools() ``` ## 自定义信头 如果 MCP 服务器需要自定义头条或令牌方案, 您可以手动设置客户端的 `headers` 而不是使用 `auth` 参数 : ```python {7} from fastmcp import Client from fastmcp.client.transports import StreamableHttpTransport async with Client( transport=StreamableHttpTransport( "https://your-server.fastmcp.app/mcp", headers={"X-API-Key": "<your-token>"}, ), ) as client: await client.list_tools() ```
查看原始来源