MCP
OAuth MCP
MCP 插件让您的应用充当 MCP 客户端的 OAuth 提供者。它处理认证,并简化了为 MCP 应用颁发和管理访问令牌的过程。
安装
添加插件
将 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
})
]
});此插件没有客户端插件,因此您无需对 authClient 进行任何更改。
生成模式
运行迁移或生成模式,以向数据库添加必要的字段和表。
npx @better-auth/cli migratenpx @better-auth/cli generateMCP 插件使用与 OIDC Provider 插件相同的模式。详情请参阅 OIDC Provider Schema 部分。
使用
OAuth 发现元数据
Better Auth 已自动处理 /api/auth/.well-known/oauth-authorization-server 路由,但某些客户端可能无法解析 WWW-Authenticate 标头,并默认使用 /.well-known/oauth-authorization-server(例如,如果您的 CORS 配置未暴露 WWW-Authenticate)。因此,最好添加一个路由来为 MCP 客户端暴露 OAuth 元数据:
import { oAuthDiscoveryMetadata } from "better-auth/plugins";
import { auth } from "../../../lib/auth";
export const GET = oAuthDiscoveryMetadata(auth);OAuth 受保护资源元数据
Better Auth 已自动处理 /api/auth/.well-known/oauth-protected-resource 路由,但某些客户端可能无法解析 WWW-Authenticate 标头,并默认使用 /.well-known/oauth-protected-resource(例如,如果您的 CORS 配置未暴露 WWW-Authenticate)。因此,最好添加一个路由来为 MCP 客户端暴露 OAuth 元数据:
import { oAuthProtectedResourceMetadata } from "better-auth/plugins";
import { auth } from "@/lib/auth";
export const GET = oAuthProtectedResourceMetadata(auth);MCP 会话处理
您可以使用辅助函数 withMcpAuth 来获取会话并自动处理未认证的调用。
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",
"回显一条消息",
{ message: z.string() },
async ({ message }) => {
return {
content: [{ type: "text", text: `工具回显:${message}` }],
};
},
);
},
{
capabilities: {
tools: {
echo: {
description: "回显一条消息",
},
},
},
},
{
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 客户端发送的访问令牌获取会话:
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",
"回显一条消息",
{ message: z.string() },
async ({ message }) => {
return {
content: [{ type: "text", text: `工具回显:${message}` }],
};
},
);
},
{
capabilities: {
tools: {
echo: {
description: "回显一条消息",
},
},
},
},
{
redisUrl: process.env.REDIS_URL,
basePath: "/api",
verboseLogs: true,
maxDuration: 60,
},
)(req);
}
export { handler as GET, handler as POST, handler as DELETE };配置
MCP 插件接受以下配置选项:
| Prop | Type | Default |
|---|---|---|
loginPage | string | - |
resource? | string | - |
oidcConfig? | object | - |
OIDC 配置
该插件通过 oidcConfig 参数支持额外的 OIDC 配置选项:
| Prop | Type | Default |
|---|---|---|
codeExpiresIn? | number | 600 |
accessTokenExpiresIn? | number | 3600 |
refreshTokenExpiresIn? | number | 604800 |
defaultScope? | string | openid |
scopes? | string[] | ["openid", "profile", "email", "offline_access"] |
模式
MCP 插件使用与 OIDC Provider 插件相同的模式。详情请参阅 OIDC Provider Schema 部分。