MCP
OAuth MCP
此插件将很快被弃用,建议使用 OAuth 提供者插件。
MCP 插件允许你的应用作为 MCP 客户端的 OAuth 提供者。它处理身份验证,并使发放和管理 MCP 应用的访问令牌变得简单。
【The MCP plugin lets your app act as an OAuth provider for MCP clients. It handles authentication and makes it easy to issue and manage access tokens for MCP applications.】
此插件基于 OIDC Provider 插件。目前尚未准备好用于生产环境。我们正在开发中,准备就绪后会更新此文档。
安装
【Installation】
添加插件
将 MCP 插件添加到你的身份验证配置中,并指定登录页面路径。
import { betterAuth } from "better-auth";
import { mcp } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [
mcp({
loginPage: "/sign-in" // path to your login page
})
]
});This doesn't have a client plugin, so you don't need to make any changes to your authClient.
生成模式
运行迁移或生成架构,以向数据库添加必要的字段和表。
npx @better-auth/cli migratenpx @better-auth/cli generateThe MCP plugin uses the same schema as the OIDC Provider plugin. See the OIDC Provider Schema section for details.
用法
【Usage】
OAuth 探索元数据
【OAuth Discovery Metadata】
Better Auth 已经自动处理了 /api/auth/.well-known/oauth-authorization-server 路由,但一些客户端可能无法解析 WWW-Authenticate 头,并默认使用 /.well-known/oauth-authorization-server(例如,如果你的 CORS 配置没有暴露 WWW-Authenticate,就可能发生这种情况)。因此,最好添加一个路由来为 MCP 客户端公开 OAuth 元数据:
【Better Auth already handles the /api/auth/.well-known/oauth-authorization-server route automatically but some client may fail to parse the WWW-Authenticate header and default to /.well-known/oauth-authorization-server (this can happen, for example, if your CORS configuration doesn't expose the WWW-Authenticate). For this reason it's better to add a route to expose OAuth metadata for MCP clients:】
import { oAuthDiscoveryMetadata } from "better-auth/plugins";
import { auth } from "../../../lib/auth";
export const GET = oAuthDiscoveryMetadata(auth);OAuth 受保护的资源元数据
【OAuth Protected Resource Metadata】
Better Auth 已经自动处理了 /api/auth/.well-known/oauth-protected-resource 路由,但一些客户端可能无法解析 WWW-Authenticate 头,并默认使用 /.well-known/oauth-protected-resource(例如,如果你的 CORS 配置没有暴露 WWW-Authenticate,就可能发生这种情况)。因此,最好添加一个路由来为 MCP 客户端公开 OAuth 元数据:
【Better Auth already handles the /api/auth/.well-known/oauth-protected-resource route automatically but some client may fail to parse the WWW-Authenticate header and default to /.well-known/oauth-protected-resource (this can happen, for example, if your CORS configuration doesn't expose the WWW-Authenticate). For this reason it's better to add a route to expose OAuth metadata for MCP clients:】
import { oAuthProtectedResourceMetadata } from "better-auth/plugins";
import { auth } from "@/lib/auth";
export const GET = oAuthProtectedResourceMetadata(auth);MCP 会话处理
【MCP Session Handling】
你可以使用辅助函数 withMcpAuth 来获取会话并自动处理未认证的调用。
【You can use the helper function withMcpAuth to get the session and handle unauthenticated calls automatically.】
import { auth } from "@/lib/auth";
import { createMcpHandler } from "@vercel/mcp-adapter";
import { withMcpAuth } from "better-auth/plugins";
import { z } from "zod";
const handler = withMcpAuth(auth, (req, session) => {
// session contains the access token record with scopes and user ID
return createMcpHandler(
(server) => {
server.tool(
"echo",
"Echo a message",
{ message: z.string() },
async ({ message }) => {
return {
content: [{ type: "text", text: `Tool echo: ${message}` }],
};
},
);
},
{
capabilities: {
tools: {
echo: {
description: "Echo a message",
},
},
},
},
{
redisUrl: process.env.REDIS_URL,
basePath: "/api",
verboseLogs: true,
maxDuration: 60,
},
)(req);
});
export { handler as GET, handler as POST, handler as DELETE };你也可以使用 auth.api.getMcpSession 来使用从 MCP 客户端发送的访问令牌获取会话:
【You can also use auth.api.getMcpSession to get the session using the access token sent from the MCP client:】
import { auth } from "@/lib/auth";
import { createMcpHandler } from "@vercel/mcp-adapter";
import { z } from "zod";
const handler = async (req: Request) => {
// session contains the access token record with scopes and user ID
const session = await auth.api.getMcpSession({
headers: req.headers
})
if(!session){
//this is important and you must return 401
return new Response(null, {
status: 401
})
}
return createMcpHandler(
(server) => {
server.tool(
"echo",
"Echo a message",
{ message: z.string() },
async ({ message }) => {
return {
content: [{ type: "text", text: `Tool echo: ${message}` }],
};
},
);
},
{
capabilities: {
tools: {
echo: {
description: "Echo a message",
},
},
},
},
{
redisUrl: process.env.REDIS_URL,
basePath: "/api",
verboseLogs: true,
maxDuration: 60,
},
)(req);
}
export { handler as GET, handler as POST, handler as DELETE };配置
【Configuration】
MCP 插件接受以下配置选项:
【The MCP plugin accepts the following configuration options:】
Prop
Type
OIDC 配置
【OIDC Configuration】
该插件通过 oidcConfig 参数支持额外的 OIDC 配置选项:
【The plugin supports additional OIDC configuration options through the oidcConfig parameter:】
Prop
Type
架构
【Schema】
MCP 插件使用与 OIDC Provider 插件相同的模式。有关详细信息,请参阅 OIDC Provider 模式 部分。
【The MCP plugin uses the same schema as the OIDC Provider plugin. See the OIDC Provider Schema section for details.】