FastMCP 服务器授权机制

FastMCP 的授权机制通过可调用函数判断已认证用户能对服务器执行哪些操作,多个检查以 AND 逻辑组合。授权依赖 OAuth 令牌,仅在 HTTP 传输下可用,STDIO 模式下所有检查被跳过。

授权控制被认证的用户可以对您的 FastMCP 服务器做什么 。 [认证](<https://github.com/servers/auth/authentication>) 验证身份(您是谁),授权决定访问(您可以做什么). FastMCP提供了一个基于可调用的授权系统,通过中间软件同时在组件级别和全球工作. 授权模式以一个简单的概念为中心:接收当前请求和返回的可调用功能 `True` 允许访问或 `False` 拒绝 。 多个检查与 AND 逻辑结合, 意思是所有检查都必须通过才能获准访问 。 授权依赖于只有HTTP传输(SSE,可流的HTTP)可用的OAuth令牌. 在STDIO模式中,没有OAuth机制,所以. `get_access_token()` 返回时 `None` 并跳过所有认证检查 。 STDIO 访问由本地执行环境控制; 组件认证检查不限制连接在 STDIO 上的进程 。 当一个 `AuthProvider` 配置后, 给 MCP 端点的所有请求都必须带一个有效的代号, 未经认证的请求在进行认证检查之前会在运输级别被拒绝 。 因此, 授权检查要根据授权用户的范围与要求加以区分, 而不是根据认证用户与未经认证用户之间的区分 。 ## 认证检查 认证检查是任何可调用接受 `AuthContext` 并返回布尔。Auth 检查可以是同步的,也可以是同步的,所以需要执行ASync操作(如读取服务器状态或调用外部服务)的检查是自然的。 ```python from fastmcp.server.auth import AuthContext def my_custom_check(ctx: AuthContext) -> bool: # ctx.token is AccessToken | None # ctx.component is the Tool, Resource, or Prompt being accessed return ctx.token is not None and "special" in ctx.token.scopes ``` FastMCP提供3个内置认证检查,覆盖了共同的授权模式: `require_scopes`, `require_roles`,以及 `restrict_tag`. ### require_scopes 基于范围的授权检查, 指针包含所有指定的 OAuth 范围。 当提供多个范围时, 全部必须存在( AND 逻辑) 。 ```python from fastmcp import FastMCP from fastmcp.server.auth import require_scopes mcp = FastMCP("Scoped Server") @mcp.tool(auth=require_scopes("admin")) def admin_operation() -> str: """Requires the 'admin' scope.""" return "Admin action completed" @mcp.tool(auth=require_scopes("read", "write")) def read_write_operation() -> str: """Requires both 'read' AND 'write' scopes.""" return "Read/write action completed" ``` ### require_roles 范围是标准化的,因此 `require_scopes` 角色和团体不是OIDC的一部分,所以每个身份提供者都将其置于不同的主张之下。 `require_roles` 处理比较并使用 `extract` 可调用,它告诉它在哪里看。 ```python from fastmcp import FastMCP from fastmcp.server.auth import require_roles def keycloak_roles(claims: dict) -> list[str]: return claims["realm_access"]["roles"] mcp = FastMCP("Role Server") @mcp.tool(auth=require_roles("admin", extract=keycloak_roles)) def admin_operation() -> str: """Requires the 'admin' role.""" return "Admin action completed" @mcp.tool(auth=require_roles("admin", "auditor", extract=keycloak_roles)) def audited_admin_operation() -> str: """Requires both the 'admin' AND 'auditor' roles.""" return "Audited admin action" ``` 需要多个角色一起,匹配 `require_scopes`。其主张缺乏路径的标志被完全拒绝而不是提起,因此提取器可以直接索引。 将索赔路径保留在呼叫地点是指任何提供者的工程,包括形状不寻常的工程。 | 供应商 | 提取器 | | --- | --- | | 键盘 | `lambda c: c["realm_access"]["roles"]` | | 微软 Entra | `lambda c: c["roles"]` | | AWS 认知 | `lambda c: c["cognito:groups"]` | | 自动 0 | `lambda c: c["permissions"]` | 在依赖它之前,先核实针对自己房客的索赔要求。 Auth0 的名符其实的习惯索赔要求按每个房客进行配置, Entra 发送 `roles` 或 时 间 `groups` 取决于应用表。 `require_roles` 无法表示范围不足, 因为 OAuth 无法请求角色。 角色拒绝会作为一个平面 `AuthorizationError` 而不是一个 `insufficient_scope` A. 报告中提到的挑战 [信号范围不足](#signaling-scope-shortfalls)它抑制了同时出现的任何范围不足——不应告诉被其作用所阻拦的呼叫者去获得一个对他们无益的范围。 `require_roles` 与 `require_scopes` 否则是罚款的:每当角色检查通过时,就会像往常一样报告范围不足的情况。 ### 检查其他索赔 `require_roles` 这是一种方便的普通案件。 `AccessToken.claims` 持有每个标语,所以在其它东西上标注不需要特别的API——只是一个读取它的认证检查. ```python from fastmcp import FastMCP from fastmcp.server.auth import AuthCheck, AuthContext mcp = FastMCP("Claim Server") def require_tenant(tenant_id: str) -> AuthCheck: """Require the token to come from a specific tenant.""" def check(ctx: AuthContext) -> bool: if ctx.token is None: return False return ctx.token.claims.get("tid") == tenant_id return check @mcp.tool(auth=require_tenant("acme")) def tenant_operation() -> str: """Only callable by tokens issued for the acme tenant.""" return "Tenant action completed" ``` 同样的警告也适用:这样的支票是不透明的,因此它抑制了对兄弟姐妹的范围披露. ### restrict_tag 基于标记的限制有条件地适用范围要求。如果一个组件有指定的标记,则符号必须具有所需的范围。没有标记的部件不受影响。 ```python from fastmcp import FastMCP from fastmcp.server.auth import restrict_tag from fastmcp.server.middleware import AuthMiddleware mcp = FastMCP( "Tagged Server", middleware=[ AuthMiddleware(auth=restrict_tag("admin", scopes=["admin"])) ] ) @mcp.tool(tags={"admin"}) def admin_tool() -> str: """Tagged 'admin', so requires 'admin' scope.""" return "Admin only" @mcp.tool(tags={"public"}) def public_tool() -> str: """Not tagged 'admin', so no scope required by the restriction.""" return "Anyone can access" ``` ### 合并检查 多个认证检查可以通过通过列表来合并. 所有检查都必须通过授权才能成功(AND逻辑). ```python from fastmcp import FastMCP from fastmcp.server.auth import require_scopes mcp = FastMCP("Combined Auth Server") @mcp.tool(auth=[require_scopes("admin"), require_scopes("write")]) def secure_admin_action() -> str: """Requires both 'admin' AND 'write' scopes.""" return "Secure admin action" ``` ### 自定义认证检查 任何可调用可接受 `AuthContext` 返回时 `bool` 可用作验证检查。这允许基于符号要求、组件元数据或外部系统的授权逻辑。 ```python from fastmcp import FastMCP from fastmcp.server.auth import AuthCheck, AuthContext mcp = FastMCP("Custom Auth Server") def require_premium_user(ctx: AuthContext) -> bool: """Check for premium user status in token claims.""" if ctx.token is None: return False return ctx.token.claims.get("premium", False) is True def require_access_level(minimum_level: int) -> AuthCheck: """Factory function for level-based authorization.""" def check(ctx: AuthContext) -> bool: if ctx.token is None: return False user_level = ctx.token.claims.get("level", 0) return user_level >= minimum_level return check @mcp.tool(auth=require_premium_user) def premium_feature() -> str: """Only for premium users.""" return "Premium content" @mcp.tool(auth=require_access_level(5)) def advanced_feature() -> str: """Requires access level 5 or higher.""" return "Advanced feature" ``` ### Async Auth检查 认证检查可以是 `async` 函数,当授权决定依赖于同步操作,如读取服务器状态或查询外部服务时,此函数是有用的。 ```python from fastmcp import FastMCP from fastmcp.server.auth import AuthContext mcp = FastMCP("Async Auth Server") async def fetch_user_permissions(user_id: str | None) -> set[str]: """Look up a user's permissions in your own store.""" return set() async def check_user_permissions(ctx: AuthContext) -> bool: """Async auth check that reads server state.""" if ctx.token is None: return False user_id = ctx.token.claims.get("sub") # Async operations work naturally in auth checks permissions = await fetch_user_permissions(user_id) return "admin" in permissions @mcp.tool(auth=check_user_permissions) def admin_tool() -> str: return "Admin action completed" ``` 同步和同步检查可以自由合并在一个列表中——每个检查都按其类型处理. ### 处理错误 认证检查可以提出用自定义信件明确拒绝的例外 : - **`AuthorizationError`**: 以自定义消息传播, 用于解释拒绝访问的原因 - **`InsufficientScopeError`**: 一个子类 `AuthorizationError` 由下列人员提出: `AuthMiddleware` 当否认是缺失的范围时; [指定呼叫者所需的范围](#signaling-scope-shortfalls) - **其他例外情况**:为安全戴面具(内部登记,视为拒绝) ```python from fastmcp.server.auth import AuthContext from fastmcp.exceptions import AuthorizationError def require_verified_email(ctx: AuthContext) -> bool: """Require verified email with explicit denial message.""" if ctx.token is None: raise AuthorizationError("Authentication required") if not ctx.token.claims.get("email_verified"): raise AuthorizationError("Email verification required") return True ``` ## 构成部分一级授权 那个... `auth` 关于装饰器的参数控制单个组件的可见度和访问。当当前请求的验证检查失败时,该组件会被隐藏在列表回复中,直接访问返回未找到。 ```python from fastmcp import FastMCP from fastmcp.server.auth import require_scopes mcp = FastMCP("Component Auth Server") @mcp.tool(auth=require_scopes("write")) def write_tool() -> str: """Only visible to users with 'write' scope.""" return "Written" @mcp.resource("secret://data", auth=require_scopes("read")) def secret_resource() -> str: """Only visible to users with 'read' scope.""" return "Secret data" @mcp.prompt(auth=require_scopes("admin")) def admin_prompt() -> str: """Only visible to users with 'admin' scope.""" return "Admin prompt content" ``` 构成部分一级 `auth` 控制可见度( 列表过滤) 和访问( 直接查询返回未找到的未经授权的请求 ) 。 `AuthMiddleware` 以应用全服务器的授权规则并明确 `AuthorizationError` 对未经授权的行刑企图的反应。 ## 服务器级别授权 用于全服务器的授权执行,使用 `AuthMiddleware`。这一中间软件将认证检查应用于全球所有组件——过滤列表回复和明确阻止未经授权的处决。 `AuthorizationError` 回复。当拒绝是缺失的特定范围时,错误 [指定呼叫者所需的范围](#signaling-scope-shortfalls). ```python from fastmcp import FastMCP from fastmcp.server.auth import require_scopes from fastmcp.server.middleware import AuthMiddleware mcp = FastMCP( "Enforced Auth Server", middleware=[AuthMiddleware(auth=require_scopes("api"))] ) @mcp.tool def any_tool() -> str: """Requires 'api' scope to see AND call.""" return "Protected" ``` ### 组件 Auth + 中间软件 构成部分一级 `auth` 财务报告和财务报告 `AuthMiddleware` 作为互补层一起工作。中间软件对所有组件应用全服务器规则,而组件级认证则增加每个组件的要求。两个层都被检查,所有检查都必须通过。 ```python from fastmcp import FastMCP from fastmcp.server.auth import require_scopes, restrict_tag from fastmcp.server.middleware import AuthMiddleware mcp = FastMCP( "Layered Auth Server", middleware=[ AuthMiddleware(auth=restrict_tag("admin", scopes=["admin"])) ] ) # Requires "write" scope (component-level) # Also requires "admin" scope if tagged "admin" (middleware-level) @mcp.tool(auth=require_scopes("write"), tags={"admin"}) def admin_write() -> str: """Requires both 'write' AND 'admin' scopes.""" return "Admin write" # Requires "write" scope (component-level only) @mcp.tool(auth=require_scopes("write")) def user_write() -> str: """Requires 'write' scope.""" return "User write" ``` ### 基于标签的全球授权 常用图案 `restrict_tag` 与 `AuthMiddleware` 以组件标记为基础适用范围要求。 ```python from fastmcp import FastMCP from fastmcp.server.auth import restrict_tag from fastmcp.server.middleware import AuthMiddleware mcp = FastMCP( "Tag-Based Auth Server", middleware=[ AuthMiddleware(auth=restrict_tag("admin", scopes=["admin"])), AuthMiddleware(auth=restrict_tag("write", scopes=["write"])), ] ) @mcp.tool(tags={"admin"}) def delete_all_data() -> str: """Requires 'admin' scope.""" return "Deleted" @mcp.tool(tags={"write"}) def update_record(id: str, data: str) -> str: """Requires 'write' scope.""" return f"Updated {id}" @mcp.tool def read_record(id: str) -> str: """No tag restrictions, accessible to all.""" return f"Record {id}" ``` ### 信号范围不足 否认,当它说什么可以解决它时,会更有用。 `AuthMiddleware` 因为信使缺少范围,而不是因为其他政策拒绝了它,所以阻止了呼叫。 `InsufficientScopeError`,它带有呼叫者需要的特定范围 `required_scopes` 属性。读取错误的代理人完全知道哪些范围可以重新授权,而不是盲目对不透明的拒绝进行重试。 `InsufficientScopeError` 子类 `AuthorizationError`,因此,现有的处理者抓住 `AuthorizationError` 继续捕捉,关于你的错误处理 无需改变才能接受这个。 只有瞄准镜显示符号 *缺少* 被命名,因此重新授权可累积权限,而不是替换权限。 `read` 这需要 `read` 财务报告和财务报告 `write` 被告知要获得 `write` 独自一人,并保持 `read` 当几个范围要求一次失败时,每个未达到的范围都一起报告——一个呼叫者在一轮中都给予它们,在重试中成功,而不是在获得第一个范围后才发现下一个缺失的范围。 ```python from fastmcp import FastMCP from fastmcp.exceptions import InsufficientScopeError from fastmcp.server.auth import require_scopes from fastmcp.server.middleware import AuthMiddleware mcp = FastMCP( "Step-Up Server", middleware=[AuthMiddleware(auth=require_scopes("read", "write"))], ) @mcp.tool def update_record(id: str) -> str: """Requires both 'read' and 'write'.""" return f"Updated {id}" # A token holding only "read" is denied with: # InsufficientScopeError(required_scopes=["write"]) ``` 这涉及几个方面 `AuthMiddleware` 也有一些例子,不只是其中的几笔检查。 [基于标签的配置](#tag-based-global-authorization) 每一个中间软件都贡献了自己的要求,第一个发现不足的软件会报告其他软件与自己的软件一起的要求——所以一个重新授权涵盖了整个链条而不是一个层. 只有在范围要求是造成拒绝的真正原因时,才报告短缺。 [合并检查](#combining-checks) 并且非范围检查拒绝要求 —— 租户政策,比如说—— 拒绝保留一个普通的。 `AuthorizationError` 取消对调用者无法到达的部件的范围要求会泄露关于他们无权查看的部件的信息。 该规则还约束了被汇总的内容。 合并要求只到达链条下方, 正如请求本身会走得那么远:它停留在第一层,进行自定义检查,因为该层是否在运行之前不会承认被呼叫者,并且提前运行会触发请求尚未达到的授权逻辑。该点内外的要求坐落在一个未经核实的大门后面,被排除在外。 因此,链条早期的自定义检查使得所报集成为局部的,而呼叫者可能需要不止一个回合才能满足所有要求。 当前面的层是仅限范围且保守的时,所报集是完整的:它可能比整个链条要求的命名范围要少,但从不为可能拒绝呼叫者的政策背后命名范围。 此命名错误中缺失的瞄准镜, 而不是释放一个 HTTP `403` 挑战。每个工具的拒绝是 JSON - RPC 内带的错误。 `200` 响应,所以该层没有 HTTP 状态可附加 `WWW-Authenticate` 信头到。 托肯级范围失败 —— 令牌不能满足服务器本身 `required_scopes` ——是运输中间器件处理的一个单独问题,它确实返回了光谱正确性 `403` 带有 `insufficient_scope` 挑战。 ## 访问工具中的托肯 工具可以使用 `get_access_token()` 从 `fastmcp.server.dependencies`。这使得各种工具能够根据用户身份或权限作出决定,而不只是简单的授权检查。 ```python from fastmcp import FastMCP from fastmcp.server.dependencies import get_access_token mcp = FastMCP("Token Access Server") @mcp.tool def personalized_greeting() -> str: """Greet the user based on their token claims.""" token = get_access_token() if token is None: return "Hello, guest!" name = token.claims.get("name", "user") return f"Hello, {name}!" @mcp.tool def user_dashboard() -> dict: """Return user-specific data based on token.""" token = get_access_token() if token is None: return {"error": "Not authenticated"} return { "client_id": token.client_id, "scopes": token.scopes, "claims": token.claims, } ``` ## 参考 ### AccessToken 那个... `AccessToken` 对象包含从 OAuth 符号中提取的信息。 | 财产 | 类型 | 说明 | |----------|------|-------------| | `token` | `str` | 原始符号字符串 | | `client_id` | `str` | OAuth 客户端标识符 | | `scopes` | `list[str]` | 授予 OAuth 范围 | | `expires_at` | `int \| None` | 以秒计的 Unix 时间戳表示过期 | | `claims` | `dict[str, Any]` | 所有 JWT 索赔或自定义令牌数据 | ### AuthContext 那个... `AuthContext` 数据类将传递给所有认证检查函数。 | 财产 | 类型 | 说明 | |----------|------|-------------| | `token` | `AccessToken \| None` | 当前访问符,或 `None` 如果未经认证 | | `component` | `Tool \| Resource \| Prompt` | 正在访问的组件 | 访问组件对象后,可以根据标记、名称或自定义属性等元数据作出授权决定。 ```python from fastmcp.server.auth import AuthContext def require_matching_tag(ctx: AuthContext) -> bool: """Require a scope matching each of the component's tags.""" if ctx.token is None: return False user_scopes = set(ctx.token.scopes) return ctx.component.tags.issubset(user_scopes) ``` ### 进口 ```python from fastmcp.server.auth import ( AccessToken, # Token with .token, .client_id, .scopes, .expires_at, .claims AuthContext, # Context with .token, .component AuthCheck, # Type alias: sync or async Callable[[AuthContext], bool] require_scopes, # Built-in: requires specific scopes require_roles, # Built-in: requires roles read from token claims restrict_tag, # Built-in: tag-based scope requirements run_auth_checks, # Utility: run checks with AND logic ) from fastmcp.exceptions import ( AuthorizationError, # Denial with a custom message InsufficientScopeError, # Subclass of AuthorizationError; has .required_scopes ) from fastmcp.server.middleware import AuthMiddleware ```

查看原始来源