Skip to content
Cloudflare Docs
非官方翻译 - 此文档为非官方中文翻译版本,仅供参考。如有疑问请以 英文官方文档 为准。

授权

在构建 Model Context Protocol (MCP) 服务器时,您需要一种允许用户登录(身份验证)的方式,以及允许他们授予 MCP 客户端访问其账户资源权限(授权)的方式。

Model Context Protocol 使用 OAuth 2.1 的子集进行授权。OAuth 允许您的用户授予对资源的有限访问权限,而无需共享 API 密钥或其他凭据。

Cloudflare 提供了一个 OAuth Provider Library,它实现了 OAuth 2.1 协议的提供方,让您可以轻松地为 MCP 服务器添加授权功能。

您可以通过三种方式使用 OAuth Provider Library:

  1. 您的 Worker 自己处理授权。 您的 MCP 服务器在 Cloudflare 上运行,处理完整的 OAuth 流程。(示例
  2. 直接与第三方 OAuth 提供方集成,如 GitHub 或 Google。
  3. 与您自己的 OAuth 提供方集成,包括您可能已经依赖的授权即服务提供商,如 Stytch、Auth0 或 WorkOS。

以下部分描述了这些选项中的每一个,并链接到每个的可运行代码示例。

授权选项

(1) 您的 MCP 服务器自己处理授权和身份验证

您的 MCP 服务器使用 OAuth Provider Library,可以处理完整的 OAuth 授权流程,无需任何第三方参与。

Workers OAuth Provider Library 是一个 Cloudflare Worker,它实现了一个 fetch() 处理程序,并处理传入的 MCP 服务器请求。

您为您的 MCP 服务器的 API、身份验证和授权逻辑以及 OAuth 端点的 URI 路径提供您自己的处理程序,如下所示:

export default new OAuthProvider({
apiRoute: "/mcp",
// 您的 MCP 服务器:
apiHandler: MyMCPServer.Router,
// 您的身份验证和授权处理程序:
defaultHandler: MyAuthHandler,
authorizeEndpoint: "/authorize",
tokenEndpoint: "/token",
clientRegistrationEndpoint: "/register",
});

参考入门示例以获取 OAuthProvider 的完整使用示例,包含模拟身份验证流程。

在这种情况下,授权流程的工作方式如下:

sequenceDiagram
    participant B as User-Agent (Browser)
    participant C as MCP Client
    participant M as MCP Server (your Worker)

    C->>M: MCP Request
    M->>C: HTTP 401 Unauthorized
    Note over C: Generate code_verifier and code_challenge
    C->>B: Open browser with authorization URL + code_challenge
    B->>M: GET /authorize
    Note over M: User logs in and authorizes
    M->>B: Redirect to callback URL with auth code
    B->>C: Callback with authorization code
    C->>M: Token Request with code + code_verifier
    M->>C: Access Token (+ Refresh Token)
    C->>M: MCP Request with Access Token
    Note over C,M: Begin standard MCP message exchange

请记住 — 身份验证与授权是不同的。您的 MCP 服务器可以自己处理授权,同时仍然依赖外部身份验证服务来首先验证用户身份。入门指南中的示例提供了一个模拟身份验证流程。您需要实现自己的身份验证处理程序 — 要么自己处理身份验证,要么使用外部身份验证服务。

(2) 第三方 OAuth 提供方

The OAuth Provider Library can be configured to use a third-party OAuth provider, such as GitHub or Google. You can see a complete example of this in the GitHub example.

When you use a third-party OAuth provider, you must provide a handler to the OAuthProvider that implements the OAuth flow for the third-party provider.

import MyAuthHandler from "./auth-handler";
export default new OAuthProvider({
apiRoute: "/mcp",
// Your MCP server:
apiHandler: MyMCPServer.Router,
// Replace this handler with your own handler for authentication and authorization with the third-party provider:
defaultHandler: MyAuthHandler,
authorizeEndpoint: "/authorize",
tokenEndpoint: "/token",
clientRegistrationEndpoint: "/register",
});

Note that as defined in the Model Context Protocol specification when you use a third-party OAuth provider, the MCP Server (your Worker) generates and issues its own token to the MCP client:

sequenceDiagram
    participant B as User-Agent (Browser)
    participant C as MCP Client
    participant M as MCP Server (your Worker)
    participant T as Third-Party Auth Server

    C->>M: Initial OAuth Request
    M->>B: Redirect to Third-Party /authorize
    B->>T: Authorization Request
    Note over T: User authorizes
    T->>B: Redirect to MCP Server callback
    B->>M: Authorization code
    M->>T: Exchange code for token
    T->>M: Third-party access token
    Note over M: Generate bound MCP token
    M->>B: Redirect to MCP Client callback
    B->>C: MCP authorization code
    C->>M: Exchange code for token
    M->>C: MCP access token

Read the docs for the Workers oAuth Provider Library for more details.

(3) Bring your own OAuth Provider

If your application already implements an OAuth Provider itself, or you use Stytch, Auth0, WorkOS, or authorization-as-a-service provider, you can use this in the same way that you would use a third-party OAuth provider, described above in (2).

You can use the auth provider to:

  • Allow users to authenticate to your MCP server through email, social logins, SSO (single sign-on), and MFA (multi-factor authentication).
  • Define scopes and permissions that directly map to your MCP tools.
  • Present users with a consent page corresponding with the requested permissions.
  • Enforce the permissions so that agents can only invoke permitted tools.

Stytch

Get started with a remote MCP server that uses Stytch to allow users to sign in with email, Google login or enterprise SSO and authorize their AI agent to view and manage their company's OKRs on their behalf. Stytch will handle restricting the scopes granted to the AI agent based on the user's role and permissions within their organization. When authorizing the MCP Client, each user will see a consent page that outlines the permissions that the agent is requesting that they are able to grant based on their role.

Deploy to Cloudflare

For more consumer use cases, deploy a remote MCP server for a To Do app that uses Stytch for authentication and MCP client authorization. Users can sign in with email and immediately access the To Do lists associated with their account, and grant access to any AI assistant to help them manage their tasks.

Deploy to Cloudflare

Auth0

Get started with a remote MCP server that uses Auth0 to authenticate users through email, social logins, or enterprise SSO to interact with their todos and personal data through AI agents. The MCP server securely connects to API endpoints on behalf of users, showing exactly which resources the agent will be able to access once it gets consent from the user. In this implementation, access tokens are automatically refreshed during long running interactions.

To set it up, first deploy the protected API endpoint:

Deploy to Cloudflare

Then, deploy the MCP server that handles authentication through Auth0 and securely connects AI agents to your API endpoint.

Deploy to Cloudflare

WorkOS

Get started with a remote MCP server that uses WorkOS's AuthKit to authenticate users and manage the permissions granted to AI agents. In this example, the MCP server dynamically exposes tools based on the user's role and access rights. All authenticated users get access to the add tool, but only users who have been assigned the image_generation permission in WorkOS can grant the AI agent access to the image generation tool. This showcases how MCP servers can conditionally expose capabilities to AI agents based on the authenticated user's role and permission.

Deploy to Cloudflare

Using Authentication Context in Your MCP Server

When a user authenticates to your MCP server through Cloudflare's OAuth Provider, their identity information and tokens are made available through the props parameter.

export class MyMCP extends McpAgent<Env, unknown, AuthContext> {
async init() {
this.server.tool("userInfo", "Get user information", {}, async () => ({
content: [{ type: "text", text: `Hello, ${this.props.claims.name || "user"}!` }],
}));
}
}

The authentication context can be used for:

  • Accessing user-specific data by using the user ID (this.props.claims.sub) as a key
  • Checking user permissions before performing operations
  • Customizing responses based on user preferences or attributes
  • Using authentication tokens to make requests to external services on behalf of the user
  • Ensuring consistency when users interact with your application through different interfaces (dashboard, API, MCP server)

Implementing Permission-Based Access for MCP Tools

You can implement fine-grained authorization controls for your MCP tools based on user permissions. This allows you to restrict access to certain tools based on the user's role or specific permissions.

// Create a wrapper function to check permissions
function requirePermission(permission, handler) {
return async (request, context) => {
// Check if user has the required permission
const userPermissions = context.props.permissions || [];
if (!userPermissions.includes(permission)) {
return {
content: [{ type: "text", text: `Permission denied: requires ${permission}` }],
status: 403
};
}
// If permission check passes, execute the handler
return handler(request, context);
};
}
// Use the wrapper with your MCP tools
async init() {
// Basic tools available to all authenticated users
this.server.tool("basicTool", "Available to all users", {}, async () => {
// Implementation for all users
});
// Protected tool using the permission wrapper
this.server.tool(
"adminAction",
"Administrative action requiring special permission",
{ /* parameters */ },
requirePermission("admin", async (req) => {
// Only executes if user has "admin" permission
return {
content: [{ type: "text", text: "Admin action completed" }]
};
})
);
// Conditionally register tools based on user permissions
if (this.props.permissions?.includes("special_feature")) {
this.server.tool("specialTool", "Special feature", {}, async () => {
// This tool only appears for users with the special_feature permission
});
}
}

Benefits:

  • Authorization check at the tool level ensures proper access control
  • Allows you to define permission checks once and reuse them across tools
  • Provides clear feedback to users when permission is denied
  • Can choose to only present tools that the agent is able to call

Next steps