将 MCP 流与 MSAL 节点配合使用

生成 模型上下文协议 (MCP) 应用程序时,可以将 MSAL Node 配置为强制实施资源范围的令牌获取和缓存。 启用 MCP 模式后,MSAL 要求每个令牌请求包含一个 resource 参数并缓存该资源密钥的访问令牌。

注释

MCP 流仅适用于公共客户端应用程序。

先决条件

启用 MCP 模式

在创建 PublicClientApplication 时,在 auth 配置中设置 isMcp: true

const config = {
    auth: {
        clientId: "your-client-id",
        authority: "https://login.microsoftonline.com/common",
        isMcp: true,
    },
};

const pca = new msal.PublicClientApplication(config);

包括资源参数

isMcptrue时,每个令牌请求 都必须 包含一个 resource 参数。 省略它会引发错误 resource_parameter_required

const tokenRequest = {
    scopes: ["User.Read"],
    redirectUri: "http://localhost:3000/redirect",
    resource: "https://example.microsoft.com",
    code: authorizationCode,
};

const response = await pca.acquireTokenByCode(tokenRequest);

Important

resource直接在请求对象上设置参数。 请勿同时通过 extraQueryParameters 属性和 resource 属性传递它 — 这样做会引发 misplaced_resource_parameter 错误。

以下示例显示了设置 resource 参数的正确和不正确方法:

// Correct — resource on the request object
const request = {
    scopes: ["User.Read"],
    resource: "https://example.microsoft.com",
};

// Wrong — resource in both locations
const request = {
    scopes: ["User.Read"],
    resource: "https://example.microsoft.com",
    extraQueryParameters: { resource: "https://example.microsoft.com" },
};

资源范围缓存

启用 isMcp 后,访问令牌会连同其关联的资源一起缓存。 这会影响静默令牌获取:

  • 缓存命中:如果缓存中存在具有相同作用域资源的访问令牌,则从缓存中返回该令牌。
  • 缓存未命中:如果请求的资源与任何缓存的令牌都不匹配,MSAL 会回退到网络以获取请求资源的新令牌。
const msalTokenCache = pca.getTokenCache();
const accounts = await msalTokenCache.getAllAccounts();

// First request — acquires token from network
const token1 = await pca.acquireTokenSilent({
    scopes: ["User.Read"],
    resource: "https://resource-a.microsoft.com",
    account: accounts[0],
});

// Same resource — returns cached token
const token2 = await pca.acquireTokenSilent({
    scopes: ["User.Read"],
    resource: "https://resource-a.microsoft.com",
    account: accounts[0],
});

// Different resource — falls back to network
const token3 = await pca.acquireTokenSilent({
    scopes: ["User.Read"],
    resource: "https://resource-b.microsoft.com",
    account: accounts[0],
});

错误处理

两个错误是 MCP 流程特有的:

错误代码 Description
resource_parameter_required isMcptrue ,但请求不包含参数 resource
misplaced_resource_parameter resource 属性和 extraQueryParameters 中都发现了 resource。 只使用一个。

这两个错误都会作为 ClientAuthError 被抛出。 有关详细信息,请参阅 MSAL 节点常见问题解答

Samples

  • MCP 流示例 - 使用授权代码和无提示流演示 MCP 的 Express 应用。

后续步骤