跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

保护 MCP 服务器

最后更新 查看 MarkdownAgent 设置

MCP 服务器与任何 Web 应用一样,都需要受到保护,确保可信用户能够安全使用而不被滥用。MCP 规范使用 OAuth 2.1 在 MCP 客户端和服务器之间进行授权。

本指南介绍如何使用 Workers OAuth Provider ↗ 保护 MCP 服务器时需要注意的事项:授权服务器的同意页面、通过第三方提供方登录用户,以及 MCP 服务器对每个请求执行的检查。请先参阅授权设置授权服务器和 MCP 服务器。

同意页面

每个连接到你服务器的 MCP 客户端都可以自行注册,因此 /authorize 页面必须在调用 completeAuthorization() 前询问用户是否允许该客户端代表自己操作。页面必须显示客户端名称、权限范围,以及令牌将发送到的主机名,并且必须防止页面被嵌入框架或伪造。

Workers OAuth Provider 会处理同意流程的安全性。页面由你的代码负责渲染。

API 作用
describeConsent(request) 返回页面必须展示的信息:clientName、clientDomain(Client ID Metadata Document 客户端经过验证的域名)、redirectHost、redirectIsLoopback 和 scope。
beginConsent(request) 在服务器上存储授权请求,并返回供表单使用的一次性 handle,以及随页面发送的 headers。这些标头会设置绑定到浏览器的 __Host- cookie,并阻止页面被嵌入框架。
approveConsent(request, handle, options?) 使用 cookie 检查 handle,并返回已存储的授权请求。传入用户批准的权限范围作为 scope。
denyConsent(request, handle) 返回将用户重定向回客户端并携带 access_denied 的标头。
isConsentRemembered(request, authRequest, remember) 如果用户已批准此客户端、重定向 URI 和权限范围,则返回 true。将 remember 传给 approveConsent() 以记录该批准。
import {
	AuthorizationError,
	OAuthAuthorizationServer,
} from "@cloudflare/workers-oauth-provider";
import { env, WorkerEntrypoint } from "cloudflare:workers";
import { html } from "hono/html";

const SCOPES = ["mcp:read", "mcp:write"];

const authorizationServer = new OAuthAuthorizationServer({
	issuer: env.ISSUER,
	resources: [env.MCP_SERVER_URL],
	scopesSupported: SCOPES,
	clientIdMetadataDocumentEnabled: true,
});

// Replace with your own sign-in. Return undefined when no one is signed in.
async function getSignedInUser(request) {
	return { id: "user-123" };
}

// hono/html escapes every interpolated value, so client-supplied strings are safe.
function consentPage(details, handle) {
	return html`<!doctype html>
		<h1>Allow ${details.clientName} to access your account?</h1>
		<p>Access will be sent to <strong>${details.redirectHost}</strong>.</p>
		${details.redirectIsLoopback
			? html`<p>This sends access to an app on your computer.</p>`
			: ""}
		<form method="post">
			<input type="hidden" name="handle" value="${handle}" />
			${details.scope.map(
				(scope) =>
					html`<label>
						<input type="checkbox" name="scope" value="${scope}" checked />
						${scope}
					</label>`,
			)}
			<button name="decision" value="approve">Allow</button>
			<button name="decision" value="deny">Deny</button>
		</form>`;
}

async function authorize(request, env) {
	const oauth = authorizationServer.getOAuthApi(env);
	const user = await getSignedInUser(request);
	if (!user)
		return Response.redirect(new URL("/login", request.url).toString(), 302);

	if (request.method === "GET") {
		const authRequest = await oauth.parseAuthRequest(request);
		const details = await oauth.describeConsent(authRequest);
		const consent = await oauth.beginConsent(authRequest);
		consent.headers.set("Content-Type", "text/html; charset=utf-8");
		return new Response(await consentPage(details, consent.handle), {
			headers: consent.headers,
		});
	}

	const form = await request.formData();
	const handle = String(form.get("handle"));
	if (form.get("decision") !== "approve") {
		const denied = await oauth.denyConsent(request, handle);
		return new Response(null, { status: 302, headers: denied.headers });
	}

	const approved = await oauth.approveConsent(request, handle, {
		scope: form.getAll("scope").map(String),
	});
	const { redirectTo } = await oauth.completeAuthorization({
		request: approved.request, // from storage, not from the form
		userId: user.id,
		metadata: {},
		scope: approved.request.scope,
		props: { userId: user.id },
	});
	approved.headers.set("Location", redirectTo);
	return new Response(null, { status: 302, headers: approved.headers });
}

export default class AuthServer extends WorkerEntrypoint {
	async fetch(request) {
		if (new URL(request.url).pathname !== "/authorize") {
			return authorizationServer.fetch(request, this.env, this.ctx);
		}
		try {
			return await authorize(request, this.env);
		} catch (error) {
			if (!(error instanceof AuthorizationError)) throw error;
			// Redirect to the client only when the library validated where to send it.
			if (error.redirectTo) return Response.redirect(error.redirectTo, 302);
			return new Response(error.description, { status: 400 });
		}
	}

	validateToken(resource, token) {
		return authorizationServer.validateToken(resource, token, this.env);
	}
}
import {
    AuthorizationError,
    OAuthAuthorizationServer,
    type ConsentDescription,
} from "@cloudflare/workers-oauth-provider";
import { env, WorkerEntrypoint } from "cloudflare:workers";
import { html } from "hono/html";

const SCOPES = ["mcp:read", "mcp:write"];

const authorizationServer = new OAuthAuthorizationServer<Env>({
    issuer: env.ISSUER,
    resources: [env.MCP_SERVER_URL],
    scopesSupported: SCOPES,
    clientIdMetadataDocumentEnabled: true,
});

// Replace with your own sign-in. Return undefined when no one is signed in.
async function getSignedInUser(
    request: Request,
): Promise<{ id: string } | undefined> {
    return { id: "user-123" };
}

// hono/html escapes every interpolated value, so client-supplied strings are safe.
function consentPage(details: ConsentDescription, handle: string) {
    return html`<!doctype html>
        <h1>Allow ${details.clientName} to access your account?</h1>
        <p>Access will be sent to <strong>${details.redirectHost}</strong>.</p>
        ${
            details.redirectIsLoopback
                ? html`<p>This sends access to an app on your computer.</p>`
                : ""
        }
        <form method="post">
            <input type="hidden" name="handle" value="${handle}" />
            ${details.scope.map(
                (scope) =>
                    html`<label>
                        <input type="checkbox" name="scope" value="${scope}" checked />
                        ${scope}
                    </label>`,
            )}
            <button name="decision" value="approve">Allow</button>
            <button name="decision" value="deny">Deny</button>
        </form>`;
}

async function authorize(request: Request, env: Env): Promise<Response> {
    const oauth = authorizationServer.getOAuthApi(env);
    const user = await getSignedInUser(request);
    if (!user)
        return Response.redirect(new URL("/login", request.url).toString(), 302);

    if (request.method === "GET") {
        const authRequest = await oauth.parseAuthRequest(request);
        const details = await oauth.describeConsent(authRequest);
        const consent = await oauth.beginConsent(authRequest);
        consent.headers.set("Content-Type", "text/html; charset=utf-8");
        return new Response(await consentPage(details, consent.handle), {
            headers: consent.headers,
        });
    }

    const form = await request.formData();
    const handle = String(form.get("handle"));
    if (form.get("decision") !== "approve") {
        const denied = await oauth.denyConsent(request, handle);
        return new Response(null, { status: 302, headers: denied.headers });
    }

    const approved = await oauth.approveConsent(request, handle, {
        scope: form.getAll("scope").map(String),
    });
    const { redirectTo } = await oauth.completeAuthorization({
        request: approved.request, // from storage, not from the form
        userId: user.id,
        metadata: {},
        scope: approved.request.scope,
        props: { userId: user.id },
    });
    approved.headers.set("Location", redirectTo);
    return new Response(null, { status: 302, headers: approved.headers });
}

export default class AuthServer extends WorkerEntrypoint<Env> {
    async fetch(request: Request) {
        if (new URL(request.url).pathname !== "/authorize") {
            return authorizationServer.fetch(request, this.env, this.ctx);
        }
        try {
            return await authorize(request, this.env);
        } catch (error) {
            if (!(error instanceof AuthorizationError)) throw error;
            // Redirect to the client only when the library validated where to send it.
            if (error.redirectTo) return Response.redirect(error.redirectTo, 302);
            return new Response(error.description, { status: 400 });
        }
    }

    validateToken(resource: string, token: string) {
        return authorizationServer.validateToken(resource, token, this.env);
    }
}

表单只携带 handle。授权请求保留在服务器上,因此伪造的表单无法批准其他客户端或重定向 URI。

describeConsent() 会返回这些值,但不会渲染 HTML;其中每个字符串都可能来自客户端。请使用会转义输出的模板或 JSX 库(例如 Hono 的 JSX)渲染这些值。

完整页面以及哪些错误应重定向回客户端、哪些应在页面上显示,请参阅构建同意页面 ↗。

通过第三方提供方登录

如果服务器使用 GitHub、Google 或其他提供方为用户登录,那么每个 MCP 客户端都会通过你的同一个 OAuth 应用访问该提供方。这就是混淆代理问题 ↗:如果没有针对每个客户端的同意,攻击者的客户端就可能借用用户此前在该提供方的授权。

先请求用户同意,再将用户转到提供方:

API 作用
beginUpstream(authRequest, options) 在 approveConsent() 后调用。它会存储授权请求和你的 data(例如 PKCE verifier),并返回用于重定向到提供方的 state 值;该值通过 __Host- cookie 与用户浏览器绑定。
finishUpstream(request) 在回调中调用。它会根据 cookie 检查 state,并返回原始授权请求和你的 data。在另一个浏览器中重放提供方代码会被拒绝。
tokenExchangeCallback 一个 OAuthAuthorizationServer 选项,会在刷新令牌时运行。在此处刷新提供方的令牌;如果提供方已撤销访问权限,则抛出 OAuthError("invalid_grant")。
import {
	AuthorizationError,
	OAuthAuthorizationServer,
} from "@cloudflare/workers-oauth-provider";
import { env, WorkerEntrypoint } from "cloudflare:workers";
import { html } from "hono/html";

const authorizationServer = new OAuthAuthorizationServer({
	issuer: env.ISSUER,
	resources: [env.MCP_SERVER_URL],
	scopesSupported: ["mcp:read"],
	clientIdMetadataDocumentEnabled: true,
});

// hono/html escapes every interpolated value, so client-supplied strings are safe.
function consentPage(details, handle) {
	return html`<!doctype html>
		<h1>Allow ${details.clientName} to use your GitHub account?</h1>
		<p>Access will be sent to <strong>${details.redirectHost}</strong>.</p>
		<form method="post">
			<input type="hidden" name="handle" value="${handle}" />
			<button name="decision" value="approve">Continue to GitHub</button>
			<button name="decision" value="deny">Deny</button>
		</form>`;
}

async function sha256(value) {
	const digest = await crypto.subtle.digest(
		"SHA-256",
		new TextEncoder().encode(value),
	);
	return btoa(String.fromCharCode(...new Uint8Array(digest)))
		.replace(/\+/g, "-")
		.replace(/\//g, "_")
		.replace(/=+$/, "");
}

async function authorize(request, env) {
	const oauth = authorizationServer.getOAuthApi(env);

	// GET /authorize: ask for consent before sending the user to GitHub.
	if (request.method === "GET") {
		const authRequest = await oauth.parseAuthRequest(request);
		const details = await oauth.describeConsent(authRequest);
		const consent = await oauth.beginConsent(authRequest);
		consent.headers.set("Content-Type", "text/html; charset=utf-8");
		return new Response(await consentPage(details, consent.handle), {
			headers: consent.headers,
		});
	}

	// POST /authorize: the user decided.
	const form = await request.formData();
	const handle = String(form.get("handle"));
	if (form.get("decision") !== "approve") {
		const denied = await oauth.denyConsent(request, handle);
		return new Response(null, { status: 302, headers: denied.headers });
	}
	const approved = await oauth.approveConsent(request, handle);

	const verifier = crypto.randomUUID() + crypto.randomUUID();
	const { state, headers } = await oauth.beginUpstream(approved.request, {
		data: { verifier }, // returned at the callback, never sent to GitHub
		headers: approved.headers,
	});

	const github = new URL("https://github.com/login/oauth/authorize");
	github.searchParams.set("client_id", env.GITHUB_CLIENT_ID);
	github.searchParams.set(
		"redirect_uri",
		new URL("/callback", request.url).toString(),
	);
	github.searchParams.set("scope", "read:user");
	github.searchParams.set("state", state);
	github.searchParams.set("code_challenge", await sha256(verifier));
	github.searchParams.set("code_challenge_method", "S256");
	headers.set("Location", github.toString());
	return new Response(null, { status: 302, headers });
}

async function callback(request, env) {
	const oauth = authorizationServer.getOAuthApi(env);
	const {
		request: original,
		data,
		headers,
	} = await oauth.finishUpstream(request);

	const code = new URL(request.url).searchParams.get("code");
	if (!code)
		return new Response("GitHub did not return a code", { status: 400 });

	const tokenResponse = await fetch(
		"https://github.com/login/oauth/access_token",
		{
			method: "POST",
			headers: {
				Accept: "application/json",
				"Content-Type": "application/json",
			},
			body: JSON.stringify({
				client_id: env.GITHUB_CLIENT_ID,
				client_secret: env.GITHUB_CLIENT_SECRET,
				code,
				code_verifier: data.verifier,
			}),
		},
	);
	const { access_token } = await tokenResponse.json();

	const userResponse = await fetch("https://api.github.com/user", {
		headers: {
			Authorization: `Bearer ${access_token}`,
			"User-Agent": "my-mcp-server",
		},
	});
	const user = await userResponse.json();

	const { redirectTo } = await oauth.completeAuthorization({
		request: original,
		userId: String(user.id),
		metadata: {},
		scope: original.scope,
		props: { login: user.login, githubToken: access_token }, // encrypted at rest
	});
	headers.set("Location", redirectTo);
	return new Response(null, { status: 302, headers });
}

export default class AuthServer extends WorkerEntrypoint {
	async fetch(request) {
		const { pathname } = new URL(request.url);
		try {
			if (pathname === "/authorize") return await authorize(request, this.env);
			if (pathname === "/callback") return await callback(request, this.env);
		} catch (error) {
			if (!(error instanceof AuthorizationError)) throw error;
			if (error.redirectTo) return Response.redirect(error.redirectTo, 302);
			return new Response(error.description, { status: 400 });
		}
		return authorizationServer.fetch(request, this.env, this.ctx);
	}

	validateToken(resource, token) {
		return authorizationServer.validateToken(resource, token, this.env);
	}
}
import {
    AuthorizationError,
    OAuthAuthorizationServer,
    type ConsentDescription,
} from "@cloudflare/workers-oauth-provider";
import { env, WorkerEntrypoint } from "cloudflare:workers";
import { html } from "hono/html";

const authorizationServer = new OAuthAuthorizationServer<Env>({
    issuer: env.ISSUER,
    resources: [env.MCP_SERVER_URL],
    scopesSupported: ["mcp:read"],
    clientIdMetadataDocumentEnabled: true,
});

// hono/html escapes every interpolated value, so client-supplied strings are safe.
function consentPage(details: ConsentDescription, handle: string) {
    return html`<!doctype html>
        <h1>Allow ${details.clientName} to use your GitHub account?</h1>
        <p>Access will be sent to <strong>${details.redirectHost}</strong>.</p>
        <form method="post">
            <input type="hidden" name="handle" value="${handle}" />
            <button name="decision" value="approve">Continue to GitHub</button>
            <button name="decision" value="deny">Deny</button>
        </form>`;
}

async function sha256(value: string): Promise<string> {
    const digest = await crypto.subtle.digest(
        "SHA-256",
        new TextEncoder().encode(value),
    );
    return btoa(String.fromCharCode(...new Uint8Array(digest)))
        .replace(/\+/g, "-")
        .replace(/\//g, "_")
        .replace(/=+$/, "");
}

async function authorize(request: Request, env: Env): Promise<Response> {
    const oauth = authorizationServer.getOAuthApi(env);

    // GET /authorize: ask for consent before sending the user to GitHub.
    if (request.method === "GET") {
        const authRequest = await oauth.parseAuthRequest(request);
        const details = await oauth.describeConsent(authRequest);
        const consent = await oauth.beginConsent(authRequest);
        consent.headers.set("Content-Type", "text/html; charset=utf-8");
        return new Response(await consentPage(details, consent.handle), {
            headers: consent.headers,
        });
    }

    // POST /authorize: the user decided.
    const form = await request.formData();
    const handle = String(form.get("handle"));
    if (form.get("decision") !== "approve") {
        const denied = await oauth.denyConsent(request, handle);
        return new Response(null, { status: 302, headers: denied.headers });
    }
    const approved = await oauth.approveConsent(request, handle);

    const verifier = crypto.randomUUID() + crypto.randomUUID();
    const { state, headers } = await oauth.beginUpstream(approved.request, {
        data: { verifier }, // returned at the callback, never sent to GitHub
        headers: approved.headers,
    });

    const github = new URL("https://github.com/login/oauth/authorize");
    github.searchParams.set("client_id", env.GITHUB_CLIENT_ID);
    github.searchParams.set(
        "redirect_uri",
        new URL("/callback", request.url).toString(),
    );
    github.searchParams.set("scope", "read:user");
    github.searchParams.set("state", state);
    github.searchParams.set("code_challenge", await sha256(verifier));
    github.searchParams.set("code_challenge_method", "S256");
    headers.set("Location", github.toString());
    return new Response(null, { status: 302, headers });
}

async function callback(request: Request, env: Env): Promise<Response> {
    const oauth = authorizationServer.getOAuthApi(env);
    const {
        request: original,
        data,
        headers,
    } = await oauth.finishUpstream<{ verifier: string }>(request);

    const code = new URL(request.url).searchParams.get("code");
    if (!code)
        return new Response("GitHub did not return a code", { status: 400 });

    const tokenResponse = await fetch(
        "https://github.com/login/oauth/access_token",
        {
            method: "POST",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                client_id: env.GITHUB_CLIENT_ID,
                client_secret: env.GITHUB_CLIENT_SECRET,
                code,
                code_verifier: data.verifier,
            }),
        },
    );
    const { access_token } = await tokenResponse.json<{ access_token: string }>();

    const userResponse = await fetch("https://api.github.com/user", {
        headers: {
            Authorization: `Bearer ${access_token}`,
            "User-Agent": "my-mcp-server",
        },
    });
    const user = await userResponse.json<{ id: number; login: string }>();

    const { redirectTo } = await oauth.completeAuthorization({
        request: original,
        userId: String(user.id),
        metadata: {},
        scope: original.scope,
        props: { login: user.login, githubToken: access_token }, // encrypted at rest
    });
    headers.set("Location", redirectTo);
    return new Response(null, { status: 302, headers });
}

export default class AuthServer extends WorkerEntrypoint<Env> {
    async fetch(request: Request) {
        const { pathname } = new URL(request.url);
        try {
            if (pathname === "/authorize") return await authorize(request, this.env);
            if (pathname === "/callback") return await callback(request, this.env);
        } catch (error) {
            if (!(error instanceof AuthorizationError)) throw error;
            if (error.redirectTo) return Response.redirect(error.redirectTo, 302);
            return new Response(error.description, { status: 400 });
        }
        return authorizationServer.fetch(request, this.env, this.ctx);
    }

    validateToken(resource: string, token: string) {
        return authorizationServer.validateToken(resource, token, this.env);
    }
}

包括刷新和撤销提供方令牌在内的完整流程,请参阅通过其他提供方登录 ↗。

MCP 服务器上的检查

OAuthResourceServer 只接受为其自身 resourceMetadata.resource 签发的令牌,因此即使另一个服务器的令牌由同一授权服务器签发,也会被拒绝。请确保该 URL 与客户端连接的 URL 完全一致。

requiredScopes 会向客户端公布,但不会强制执行。请在处理程序中检查权限范围;若缺少某项范围,则返回 insufficientScope(),以便客户端向用户请求该范围:

import {
	OAuthResourceServer,
	insufficientScope,
} from "@cloudflare/workers-oauth-provider";
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler, getMcpAuthContext } from "agents/mcp/server";
import { env } from "cloudflare:workers";

function createServer() {
	const server = new McpServer({ name: "my-mcp-server", version: "1.0.0" });
	const props = getMcpAuthContext()?.props;

	server.registerTool(
		"whoami",
		{ description: "Return the signed-in user" },
		async () => ({
			content: [{ type: "text", text: props.userId }],
		}),
	);

	return server;
}

const mcpHandler = createMcpHandler(createServer);

export default new OAuthResourceServer({
	resourceMetadata: {
		resource: env.MCP_SERVER_URL, // tokens for any other resource are rejected
		authorization_servers: [env.AUTH_SERVER_URL],
	},
	requiredScopes: ["mcp:read"],
	validateToken: (env) => env.AUTH_SERVER.validateToken,
	handler: {
		fetch(request, env, ctx) {
			// requiredScopes is advertised, not enforced: check it here.
			if (!ctx.auth.scope.includes("mcp:read")) {
				return insufficientScope(ctx.auth, ["mcp:read"]);
			}
			return mcpHandler(request, env, ctx);
		},
	},
});
import {
    OAuthResourceServer,
    insufficientScope,
    type AuthorizationServerBinding,
} from "@cloudflare/workers-oauth-provider";
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler, getMcpAuthContext } from "agents/mcp/server";
import { env } from "cloudflare:workers";

type AuthProps = { userId: string };

interface Env {
    AUTH_SERVER: AuthorizationServerBinding<AuthProps>;
}

function createServer() {
    const server = new McpServer({ name: "my-mcp-server", version: "1.0.0" });
    const props = getMcpAuthContext()?.props as AuthProps;

    server.registerTool(
        "whoami",
        { description: "Return the signed-in user" },
        async () => ({
            content: [{ type: "text", text: props.userId }],
        }),
    );

    return server;
}

const mcpHandler = createMcpHandler(createServer);

export default new OAuthResourceServer<Env, AuthProps>({
    resourceMetadata: {
        resource: env.MCP_SERVER_URL, // tokens for any other resource are rejected
        authorization_servers: [env.AUTH_SERVER_URL],
    },
    requiredScopes: ["mcp:read"],
    validateToken: (env) => env.AUTH_SERVER.validateToken,
    handler: {
        fetch(request, env, ctx) {
            // requiredScopes is advertised, not enforced: check it here.
            if (!ctx.auth.scope.includes("mcp:read")) {
                return insufficientScope(ctx.auth, ["mcp:read"]);
            }
            return mcpHandler(request, env, ctx);
        },
    },
});

Props 可能包含上游访问令牌。请勿记录这些令牌,也不要通过工具返回它们。

安全清单

保护措施 由以下部分提供
在调用 completeAuthorization() 前征求每个客户端的同意 beginConsent(), approveConsent()
防止同意表单被嵌入框架或伪造 beginConsent() 标头和一次性 handle
在同意页面转义客户端元数据 你的页面模板
与浏览器绑定的提供方 state beginUpstream(), finishUpstream()
只接受发给此 MCP 服务器的令牌 OAuthResourceServer
针对每项操作检查权限范围 使用 insufficientScope() 的处理程序

后续步骤

这篇文档对您有帮助吗?