diff --git a/docs/README.mdx b/docs/README.mdx index 26f530e..1c1a3e4 100644 --- a/docs/README.mdx +++ b/docs/README.mdx @@ -8,6 +8,11 @@ import Tabs from '@theme/Tabs'; # Get started +:::info MCP authorization specification support +This version supports the [MCP authorization specification (version 2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization). +::: + + ## Choose a compatible OAuth 2.1 or OpenID Connect provider \{#choose-a-compatible-oauth-2-1-or-openid-connect-provider} MCP specification has [specific requirements](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#standards-compliance) for authorization. The authorization mechanism is based on established specifications, implementing a selected subset of their features to ensure security and interoperability while maintaining simplicity: diff --git a/docs/references/js/README.md b/docs/references/js/README.md index da3e1a5..2a6f065 100644 --- a/docs/references/js/README.md +++ b/docs/references/js/README.md @@ -4,7 +4,7 @@ sidebar_label: Node.js SDK # MCP Auth Node.js SDK reference -## Classes +## Classes {#classes} - [MCPAuth](/references/js/classes/MCPAuth.md) - [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) @@ -13,7 +13,7 @@ sidebar_label: Node.js SDK - [MCPAuthError](/references/js/classes/MCPAuthError.md) - [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) -## Type Aliases +## Type Aliases {#type-aliases} - [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) - [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) @@ -38,7 +38,7 @@ sidebar_label: Node.js SDK - [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) - [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) -## Variables +## Variables {#variables} - [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) - [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) @@ -51,7 +51,7 @@ sidebar_label: Node.js SDK - [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) - [validateServerConfig](/references/js/variables/validateServerConfig.md) -## Functions +## Functions {#functions} - [createVerifyJwt](/references/js/functions/createVerifyJwt.md) - [fetchServerConfig](/references/js/functions/fetchServerConfig.md) diff --git a/docs/references/js/classes/MCPAuth.md b/docs/references/js/classes/MCPAuth.md index fd84c38..84be260 100644 --- a/docs/references/js/classes/MCPAuth.md +++ b/docs/references/js/classes/MCPAuth.md @@ -10,9 +10,9 @@ authentication policies for your protected resources. It is initialized with your server configurations and provides a `bearerAuth` method to generate Express middleware for token-based authentication. -## Example +## Example {#example} -### Usage in `resource server` mode +### Usage in `resource server` mode {#usage-in-resource-server-mode} This is the recommended approach for new applications. @@ -56,7 +56,7 @@ app.get( ); ``` -### Legacy Usage in `authorization server` mode (Deprecated) +### Legacy Usage in `authorization server` mode (Deprecated) {#legacy-usage-in-authorization-server-mode-deprecated} This approach is supported for backward compatibility. @@ -86,9 +86,9 @@ app.get( ); ``` -## Constructors +## Constructors {#constructors} -### Constructor +### Constructor {#constructor} ```ts new MCPAuth(config: MCPAuthConfig): MCPAuth; @@ -97,21 +97,21 @@ new MCPAuth(config: MCPAuthConfig): MCPAuth; Creates an instance of MCPAuth. It validates the entire configuration upfront to fail fast on errors. -#### Parameters +#### Parameters {#parameters} -##### config +##### config {#config} [`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) The authentication configuration. -#### Returns +#### Returns {#returns} `MCPAuth` -## Properties +## Properties {#properties} -### config +### config {#config} ```ts readonly config: MCPAuthConfig; @@ -119,11 +119,11 @@ readonly config: MCPAuthConfig; The authentication configuration. -## Methods +## Methods {#methods} -### bearerAuth() +### bearerAuth() {#bearerauth} -#### Call Signature +#### Call Signature {#call-signature} ```ts bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; @@ -132,9 +132,9 @@ bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit @@ -158,19 +158,19 @@ Optional configuration for the Bearer auth handler. [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) for the available configuration options (excluding `verifyAccessToken` and `issuer`). -##### Returns +##### Returns {#returns} `RequestHandler` An Express middleware function that verifies the access token and adds the verification result to the request object (`req.auth`). -##### See +##### See {#see} [handleBearerAuth](/references/js/functions/handleBearerAuth.md) for the implementation details and the extended types of the `req.auth` (`AuthInfo`) object. -#### Call Signature +#### Call Signature {#call-signature} ```ts bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; @@ -182,9 +182,9 @@ Creates a Bearer auth handler (Express middleware) that verifies the access toke In the `'jwt'` mode, the handler will create a JWT verification function using the JWK Set from the authorization server's JWKS URI. -##### Parameters +##### Parameters {#parameters} -###### mode +###### mode {#mode} `"jwt"` @@ -194,7 +194,7 @@ The mode of verification for the access token. Currently, only 'jwt' is supporte [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) for the available modes. -###### config? +###### config? {#config} `Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` @@ -208,26 +208,26 @@ verification. - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) for the available configuration options (excluding `verifyAccessToken` and `issuer`). -##### Returns +##### Returns {#returns} `RequestHandler` An Express middleware function that verifies the access token and adds the verification result to the request object (`req.auth`). -##### See +##### See {#see} [handleBearerAuth](/references/js/functions/handleBearerAuth.md) for the implementation details and the extended types of the `req.auth` (`AuthInfo`) object. -##### Throws +##### Throws {#throws} if the JWKS URI is not provided in the server metadata when using the `'jwt'` mode. *** -### ~~delegatedRouter()~~ +### ~~delegatedRouter()~~ {#delegatedrouter} ```ts delegatedRouter(): Router; @@ -236,18 +236,18 @@ delegatedRouter(): Router; Creates a delegated router for serving legacy OAuth 2.0 Authorization Server Metadata endpoint (`/.well-known/oauth-authorization-server`) with the metadata provided to the instance. -#### Returns +#### Returns {#returns} `Router` A router that serves the OAuth 2.0 Authorization Server Metadata endpoint with the metadata provided to the instance. -#### Deprecated +#### Deprecated {#deprecated} Use [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) instead. -#### Example +#### Example {#example} ```ts import express from 'express'; @@ -258,13 +258,13 @@ const mcpAuth: MCPAuth; // Assume this is initialized app.use(mcpAuth.delegatedRouter()); ``` -#### Throws +#### Throws {#throws} If called in `resource server` mode. *** -### protectedResourceMetadataRouter() +### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} ```ts protectedResourceMetadataRouter(): Router; @@ -276,17 +276,17 @@ for all configured resources. This router automatically creates the correct `.well-known` endpoints for each resource identifier provided in your configuration. -#### Returns +#### Returns {#returns} `Router` A router that serves the OAuth 2.0 Protected Resource Metadata endpoint. -#### Throws +#### Throws {#throws} If called in `authorization server` mode. -#### Example +#### Example {#example} ```ts import express from 'express'; diff --git a/docs/references/js/classes/MCPAuthAuthServerError.md b/docs/references/js/classes/MCPAuthAuthServerError.md index 7ad8692..f76f24c 100644 --- a/docs/references/js/classes/MCPAuthAuthServerError.md +++ b/docs/references/js/classes/MCPAuthAuthServerError.md @@ -6,51 +6,51 @@ sidebar_label: MCPAuthAuthServerError Error thrown when there is an issue with the remote authorization server. -## Extends +## Extends {#extends} - [`MCPAuthError`](/references/js/classes/MCPAuthError.md) -## Constructors +## Constructors {#constructors} -### Constructor +### Constructor {#constructor} ```ts new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; ``` -#### Parameters +#### Parameters {#parameters} -##### code +##### code {#code} [`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) -##### cause? +##### cause? {#cause} `unknown` -#### Returns +#### Returns {#returns} `MCPAuthAuthServerError` -#### Overrides +#### Overrides {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) -## Properties +## Properties {#properties} -### cause? +### cause? {#cause} ```ts readonly optional cause: unknown; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) *** -### code +### code {#code} ```ts readonly code: AuthServerErrorCode; @@ -58,49 +58,49 @@ readonly code: AuthServerErrorCode; The error code in snake_case format. -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) *** -### message +### message {#message} ```ts message: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) *** -### name +### name {#name} ```ts name: string = 'MCPAuthAuthServerError'; ``` -#### Overrides +#### Overrides {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) *** -### stack? +### stack? {#stack} ```ts optional stack: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) *** -### stackTraceLimit +### stackTraceLimit {#stacktracelimit} ```ts static stackTraceLimit: number; @@ -116,13 +116,13 @@ will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) -## Methods +## Methods {#methods} -### toJson() +### toJson() {#tojson} ```ts toJson(showCause: boolean): Record; @@ -130,26 +130,26 @@ toJson(showCause: boolean): Record; Converts the error to a HTTP response friendly JSON format. -#### Parameters +#### Parameters {#parameters} -##### showCause +##### showCause {#showcause} `boolean` = `false` Whether to include the cause of the error in the JSON response. Defaults to `false`. -#### Returns +#### Returns {#returns} `Record`\<`string`, `unknown`\> -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) *** -### captureStackTrace() +### captureStackTrace() {#capturestacktrace} ```ts static captureStackTrace(targetObject: object, constructorOpt?: Function): void; @@ -199,50 +199,50 @@ function c() { a(); ``` -#### Parameters +#### Parameters {#parameters} -##### targetObject +##### targetObject {#targetobject} `object` -##### constructorOpt? +##### constructorOpt? {#constructoropt} `Function` -#### Returns +#### Returns {#returns} `void` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) *** -### prepareStackTrace() +### prepareStackTrace() {#preparestacktrace} ```ts static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; ``` -#### Parameters +#### Parameters {#parameters} -##### err +##### err {#err} `Error` -##### stackTraces +##### stackTraces {#stacktraces} `CallSite`[] -#### Returns +#### Returns {#returns} `any` -#### See +#### See {#see} https://v8.dev/docs/stack-trace-api#customizing-stack-traces -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/docs/references/js/classes/MCPAuthBearerAuthError.md b/docs/references/js/classes/MCPAuthBearerAuthError.md index 78c13de..9a5b9c6 100644 --- a/docs/references/js/classes/MCPAuthBearerAuthError.md +++ b/docs/references/js/classes/MCPAuthBearerAuthError.md @@ -6,51 +6,51 @@ sidebar_label: MCPAuthBearerAuthError Error thrown when there is an issue when authenticating with Bearer tokens. -## Extends +## Extends {#extends} - [`MCPAuthError`](/references/js/classes/MCPAuthError.md) -## Constructors +## Constructors {#constructors} -### Constructor +### Constructor {#constructor} ```ts new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; ``` -#### Parameters +#### Parameters {#parameters} -##### code +##### code {#code} [`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) -##### cause? +##### cause? {#cause} [`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -#### Returns +#### Returns {#returns} `MCPAuthBearerAuthError` -#### Overrides +#### Overrides {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) -## Properties +## Properties {#properties} -### cause? +### cause? {#cause} ```ts readonly optional cause: MCPAuthBearerAuthErrorDetails; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) *** -### code +### code {#code} ```ts readonly code: BearerAuthErrorCode; @@ -58,49 +58,49 @@ readonly code: BearerAuthErrorCode; The error code in snake_case format. -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) *** -### message +### message {#message} ```ts message: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) *** -### name +### name {#name} ```ts name: string = 'MCPAuthBearerAuthError'; ``` -#### Overrides +#### Overrides {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) *** -### stack? +### stack? {#stack} ```ts optional stack: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) *** -### stackTraceLimit +### stackTraceLimit {#stacktracelimit} ```ts static stackTraceLimit: number; @@ -116,13 +116,13 @@ will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) -## Methods +## Methods {#methods} -### toJson() +### toJson() {#tojson} ```ts toJson(showCause: boolean): Record; @@ -130,26 +130,26 @@ toJson(showCause: boolean): Record; Converts the error to a HTTP response friendly JSON format. -#### Parameters +#### Parameters {#parameters} -##### showCause +##### showCause {#showcause} `boolean` = `false` Whether to include the cause of the error in the JSON response. Defaults to `false`. -#### Returns +#### Returns {#returns} `Record`\<`string`, `unknown`\> -#### Overrides +#### Overrides {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) *** -### captureStackTrace() +### captureStackTrace() {#capturestacktrace} ```ts static captureStackTrace(targetObject: object, constructorOpt?: Function): void; @@ -199,50 +199,50 @@ function c() { a(); ``` -#### Parameters +#### Parameters {#parameters} -##### targetObject +##### targetObject {#targetobject} `object` -##### constructorOpt? +##### constructorOpt? {#constructoropt} `Function` -#### Returns +#### Returns {#returns} `void` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) *** -### prepareStackTrace() +### prepareStackTrace() {#preparestacktrace} ```ts static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; ``` -#### Parameters +#### Parameters {#parameters} -##### err +##### err {#err} `Error` -##### stackTraces +##### stackTraces {#stacktraces} `CallSite`[] -#### Returns +#### Returns {#returns} `any` -#### See +#### See {#see} https://v8.dev/docs/stack-trace-api#customizing-stack-traces -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/docs/references/js/classes/MCPAuthConfigError.md b/docs/references/js/classes/MCPAuthConfigError.md index 2740f34..78a4dba 100644 --- a/docs/references/js/classes/MCPAuthConfigError.md +++ b/docs/references/js/classes/MCPAuthConfigError.md @@ -6,55 +6,55 @@ sidebar_label: MCPAuthConfigError Error thrown when there is a configuration issue with mcp-auth. -## Extends +## Extends {#extends} - [`MCPAuthError`](/references/js/classes/MCPAuthError.md) -## Constructors +## Constructors {#constructors} -### Constructor +### Constructor {#constructor} ```ts new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; ``` -#### Parameters +#### Parameters {#parameters} -##### code +##### code {#code} `string` The error code in snake_case format. -##### message +##### message {#message} `string` A human-readable description of the error. -#### Returns +#### Returns {#returns} `MCPAuthConfigError` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) -## Properties +## Properties {#properties} -### cause? +### cause? {#cause} ```ts optional cause: unknown; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) *** -### code +### code {#code} ```ts readonly code: string; @@ -62,49 +62,49 @@ readonly code: string; The error code in snake_case format. -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) *** -### message +### message {#message} ```ts message: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) *** -### name +### name {#name} ```ts name: string = 'MCPAuthConfigError'; ``` -#### Overrides +#### Overrides {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) *** -### stack? +### stack? {#stack} ```ts optional stack: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) *** -### stackTraceLimit +### stackTraceLimit {#stacktracelimit} ```ts static stackTraceLimit: number; @@ -120,13 +120,13 @@ will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) -## Methods +## Methods {#methods} -### toJson() +### toJson() {#tojson} ```ts toJson(showCause: boolean): Record; @@ -134,26 +134,26 @@ toJson(showCause: boolean): Record; Converts the error to a HTTP response friendly JSON format. -#### Parameters +#### Parameters {#parameters} -##### showCause +##### showCause {#showcause} `boolean` = `false` Whether to include the cause of the error in the JSON response. Defaults to `false`. -#### Returns +#### Returns {#returns} `Record`\<`string`, `unknown`\> -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) *** -### captureStackTrace() +### captureStackTrace() {#capturestacktrace} ```ts static captureStackTrace(targetObject: object, constructorOpt?: Function): void; @@ -203,50 +203,50 @@ function c() { a(); ``` -#### Parameters +#### Parameters {#parameters} -##### targetObject +##### targetObject {#targetobject} `object` -##### constructorOpt? +##### constructorOpt? {#constructoropt} `Function` -#### Returns +#### Returns {#returns} `void` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) *** -### prepareStackTrace() +### prepareStackTrace() {#preparestacktrace} ```ts static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; ``` -#### Parameters +#### Parameters {#parameters} -##### err +##### err {#err} `Error` -##### stackTraces +##### stackTraces {#stacktraces} `CallSite`[] -#### Returns +#### Returns {#returns} `any` -#### See +#### See {#see} https://v8.dev/docs/stack-trace-api#customizing-stack-traces -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/docs/references/js/classes/MCPAuthError.md b/docs/references/js/classes/MCPAuthError.md index 80a58ff..40d6dda 100644 --- a/docs/references/js/classes/MCPAuthError.md +++ b/docs/references/js/classes/MCPAuthError.md @@ -8,58 +8,58 @@ Base class for all mcp-auth errors. It provides a standardized way to handle errors related to MCP authentication and authorization. -## Extends +## Extends {#extends} - `Error` -## Extended by +## Extended by {#extended-by} - [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) - [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) - [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) - [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) -## Constructors +## Constructors {#constructors} -### Constructor +### Constructor {#constructor} ```ts new MCPAuthError(code: string, message: string): MCPAuthError; ``` -#### Parameters +#### Parameters {#parameters} -##### code +##### code {#code} `string` The error code in snake_case format. -##### message +##### message {#message} `string` A human-readable description of the error. -#### Returns +#### Returns {#returns} `MCPAuthError` -#### Overrides +#### Overrides {#overrides} ```ts Error.constructor ``` -## Properties +## Properties {#properties} -### cause? +### cause? {#cause} ```ts optional cause: unknown; ``` -#### Inherited from +#### Inherited from {#inherited-from} ```ts Error.cause @@ -67,7 +67,7 @@ Error.cause *** -### code +### code {#code} ```ts readonly code: string; @@ -77,13 +77,13 @@ The error code in snake_case format. *** -### message +### message {#message} ```ts message: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} ```ts Error.message @@ -91,13 +91,13 @@ Error.message *** -### name +### name {#name} ```ts name: string = 'MCPAuthError'; ``` -#### Overrides +#### Overrides {#overrides} ```ts Error.name @@ -105,13 +105,13 @@ Error.name *** -### stack? +### stack? {#stack} ```ts optional stack: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} ```ts Error.stack @@ -119,7 +119,7 @@ Error.stack *** -### stackTraceLimit +### stackTraceLimit {#stacktracelimit} ```ts static stackTraceLimit: number; @@ -135,15 +135,15 @@ will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. -#### Inherited from +#### Inherited from {#inherited-from} ```ts Error.stackTraceLimit ``` -## Methods +## Methods {#methods} -### toJson() +### toJson() {#tojson} ```ts toJson(showCause: boolean): Record; @@ -151,22 +151,22 @@ toJson(showCause: boolean): Record; Converts the error to a HTTP response friendly JSON format. -#### Parameters +#### Parameters {#parameters} -##### showCause +##### showCause {#showcause} `boolean` = `false` Whether to include the cause of the error in the JSON response. Defaults to `false`. -#### Returns +#### Returns {#returns} `Record`\<`string`, `unknown`\> *** -### captureStackTrace() +### captureStackTrace() {#capturestacktrace} ```ts static captureStackTrace(targetObject: object, constructorOpt?: Function): void; @@ -216,21 +216,21 @@ function c() { a(); ``` -#### Parameters +#### Parameters {#parameters} -##### targetObject +##### targetObject {#targetobject} `object` -##### constructorOpt? +##### constructorOpt? {#constructoropt} `Function` -#### Returns +#### Returns {#returns} `void` -#### Inherited from +#### Inherited from {#inherited-from} ```ts Error.captureStackTrace @@ -238,31 +238,31 @@ Error.captureStackTrace *** -### prepareStackTrace() +### prepareStackTrace() {#preparestacktrace} ```ts static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; ``` -#### Parameters +#### Parameters {#parameters} -##### err +##### err {#err} `Error` -##### stackTraces +##### stackTraces {#stacktraces} `CallSite`[] -#### Returns +#### Returns {#returns} `any` -#### See +#### See {#see} https://v8.dev/docs/stack-trace-api#customizing-stack-traces -#### Inherited from +#### Inherited from {#inherited-from} ```ts Error.prepareStackTrace diff --git a/docs/references/js/classes/MCPAuthTokenVerificationError.md b/docs/references/js/classes/MCPAuthTokenVerificationError.md index 8fb2936..b24e77d 100644 --- a/docs/references/js/classes/MCPAuthTokenVerificationError.md +++ b/docs/references/js/classes/MCPAuthTokenVerificationError.md @@ -6,51 +6,51 @@ sidebar_label: MCPAuthTokenVerificationError Error thrown when there is an issue when verifying tokens. -## Extends +## Extends {#extends} - [`MCPAuthError`](/references/js/classes/MCPAuthError.md) -## Constructors +## Constructors {#constructors} -### Constructor +### Constructor {#constructor} ```ts new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; ``` -#### Parameters +#### Parameters {#parameters} -##### code +##### code {#code} [`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -##### cause? +##### cause? {#cause} `unknown` -#### Returns +#### Returns {#returns} `MCPAuthTokenVerificationError` -#### Overrides +#### Overrides {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) -## Properties +## Properties {#properties} -### cause? +### cause? {#cause} ```ts readonly optional cause: unknown; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) *** -### code +### code {#code} ```ts readonly code: MCPAuthTokenVerificationErrorCode; @@ -58,49 +58,49 @@ readonly code: MCPAuthTokenVerificationErrorCode; The error code in snake_case format. -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) *** -### message +### message {#message} ```ts message: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) *** -### name +### name {#name} ```ts name: string = 'MCPAuthTokenVerificationError'; ``` -#### Overrides +#### Overrides {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) *** -### stack? +### stack? {#stack} ```ts optional stack: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) *** -### stackTraceLimit +### stackTraceLimit {#stacktracelimit} ```ts static stackTraceLimit: number; @@ -116,13 +116,13 @@ will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) -## Methods +## Methods {#methods} -### toJson() +### toJson() {#tojson} ```ts toJson(showCause: boolean): Record; @@ -130,26 +130,26 @@ toJson(showCause: boolean): Record; Converts the error to a HTTP response friendly JSON format. -#### Parameters +#### Parameters {#parameters} -##### showCause +##### showCause {#showcause} `boolean` = `false` Whether to include the cause of the error in the JSON response. Defaults to `false`. -#### Returns +#### Returns {#returns} `Record`\<`string`, `unknown`\> -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) *** -### captureStackTrace() +### captureStackTrace() {#capturestacktrace} ```ts static captureStackTrace(targetObject: object, constructorOpt?: Function): void; @@ -199,50 +199,50 @@ function c() { a(); ``` -#### Parameters +#### Parameters {#parameters} -##### targetObject +##### targetObject {#targetobject} `object` -##### constructorOpt? +##### constructorOpt? {#constructoropt} `Function` -#### Returns +#### Returns {#returns} `void` -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) *** -### prepareStackTrace() +### prepareStackTrace() {#preparestacktrace} ```ts static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; ``` -#### Parameters +#### Parameters {#parameters} -##### err +##### err {#err} `Error` -##### stackTraces +##### stackTraces {#stacktraces} `CallSite`[] -#### Returns +#### Returns {#returns} `any` -#### See +#### See {#see} https://v8.dev/docs/stack-trace-api#customizing-stack-traces -#### Inherited from +#### Inherited from {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/docs/references/js/functions/createVerifyJwt.md b/docs/references/js/functions/createVerifyJwt.md index 1746416..c7126e8 100644 --- a/docs/references/js/functions/createVerifyJwt.md +++ b/docs/references/js/functions/createVerifyJwt.md @@ -11,9 +11,9 @@ function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): V Creates a function to verify JWT access tokens using the provided key retrieval function and options. -## Parameters +## Parameters {#parameters} -### getKey +### getKey {#getkey} `JWTVerifyGetKey` @@ -23,7 +23,7 @@ The function to retrieve the key used to verify the JWT. JWTVerifyGetKey for the type definition of the key retrieval function. -### options? +### options? {#options} `JWTVerifyOptions` @@ -33,7 +33,7 @@ Optional JWT verification options. JWTVerifyOptions for the type definition of the options. -## Returns +## Returns {#returns} [`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) @@ -42,6 +42,6 @@ the token is valid. It requires the JWT to contain the fields `iss`, `client_id` its payload, and it can optionally contain `scope` or `scopes` fields. The function uses the `jose` library under the hood to perform the JWT verification. -## See +## See {#see} [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) for the type definition of the returned function. diff --git a/docs/references/js/functions/fetchServerConfig.md b/docs/references/js/functions/fetchServerConfig.md index aeb7c25..2c9f186 100644 --- a/docs/references/js/functions/fetchServerConfig.md +++ b/docs/references/js/functions/fetchServerConfig.md @@ -13,27 +13,27 @@ Fetches the server configuration according to the issuer and authorization serve This function automatically determines the well-known URL based on the server type, as OAuth and OpenID Connect servers have different conventions for their metadata endpoints. -## Parameters +## Parameters {#parameters} -### issuer +### issuer {#issuer} `string` The issuer URL of the authorization server. -### config +### config {#config} `ServerMetadataConfig` The configuration object containing the server type and optional transpile function. -## Returns +## Returns {#returns} `Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> A promise that resolves to the server configuration. -## See +## See {#see} - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) for the underlying implementation. - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) for the OAuth 2.0 Authorization Server Metadata @@ -41,7 +41,7 @@ specification. - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) for the OpenID Connect Discovery specification. -## Example +## Example {#example} ```ts import { fetchServerConfig } from 'mcp-auth'; @@ -54,11 +54,11 @@ const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { typ const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); ``` -## Throws +## Throws {#throws} if the fetch operation fails. -## Throws +## Throws {#throws} if the server metadata is invalid or does not match the MCP specification. diff --git a/docs/references/js/functions/fetchServerConfigByWellKnownUrl.md b/docs/references/js/functions/fetchServerConfigByWellKnownUrl.md index 92b6902..7ab45db 100644 --- a/docs/references/js/functions/fetchServerConfigByWellKnownUrl.md +++ b/docs/references/js/functions/fetchServerConfigByWellKnownUrl.md @@ -15,32 +15,32 @@ If the server metadata does not conform to the expected schema, but you are sure compatible, you can define a `transpileData` function to transform the metadata into the expected format. -## Parameters +## Parameters {#parameters} -### wellKnownUrl +### wellKnownUrl {#wellknownurl} The well-known URL to fetch the server configuration from. This can be a string or a URL object. `string` | `URL` -### config +### config {#config} `ServerMetadataConfig` The configuration object containing the server type and optional transpile function. -## Returns +## Returns {#returns} `Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> A promise that resolves to the server configuration. -## Throws +## Throws {#throws} if the fetch operation fails. -## Throws +## Throws {#throws} if the server metadata is invalid or does not match the MCP specification. diff --git a/docs/references/js/functions/handleBearerAuth.md b/docs/references/js/functions/handleBearerAuth.md index 1b1e42c..ddb403e 100644 --- a/docs/references/js/functions/handleBearerAuth.md +++ b/docs/references/js/functions/handleBearerAuth.md @@ -23,20 +23,20 @@ if not, it responds with an appropriate error message. AuthInfo interface defined in the `@modelcontextprotocol/sdk` module. See the extended interface in this file for details. -## Parameters +## Parameters {#parameters} -### param0 +### param0 {#param0} [`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) Configuration for the Bearer auth handler. -## Returns +## Returns {#returns} `RequestHandler` A middleware function for Express that handles Bearer auth. -## See +## See {#see} [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) for the configuration options. diff --git a/docs/references/js/type-aliases/AuthServerConfig.md b/docs/references/js/type-aliases/AuthServerConfig.md index 8402def..8166bf3 100644 --- a/docs/references/js/type-aliases/AuthServerConfig.md +++ b/docs/references/js/type-aliases/AuthServerConfig.md @@ -13,9 +13,9 @@ type AuthServerConfig = { Configuration for the remote authorization server integrated with the MCP server. -## Properties +## Properties {#properties} -### metadata +### metadata {#metadata} ```ts metadata: CamelCaseAuthorizationServerMetadata; @@ -31,14 +31,14 @@ directly in the configuration if the server does not support such endpoints. **Note:** The metadata should be in camelCase format as per preferred by the mcp-auth library. -#### See +#### See {#see} - [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) *** -### type +### type {#type} ```ts type: AuthServerType; @@ -46,6 +46,6 @@ type: AuthServerType; The type of the authorization server. -#### See +#### See {#see} [AuthServerType](/references/js/type-aliases/AuthServerType.md) for the possible values. diff --git a/docs/references/js/type-aliases/AuthServerConfigError.md b/docs/references/js/type-aliases/AuthServerConfigError.md index 926e985..05371c1 100644 --- a/docs/references/js/type-aliases/AuthServerConfigError.md +++ b/docs/references/js/type-aliases/AuthServerConfigError.md @@ -14,9 +14,9 @@ type AuthServerConfigError = { Represents an error that occurs during the validation of the authorization server metadata. -## Properties +## Properties {#properties} -### cause? +### cause? {#cause} ```ts optional cause: Error; @@ -26,7 +26,7 @@ An optional cause of the error, typically an instance of `Error` that provides m *** -### code +### code {#code} ```ts code: AuthServerConfigErrorCode; @@ -36,7 +36,7 @@ The code representing the specific validation error. *** -### description +### description {#description} ```ts description: string; diff --git a/docs/references/js/type-aliases/AuthServerConfigWarning.md b/docs/references/js/type-aliases/AuthServerConfigWarning.md index 42a33f7..f093e35 100644 --- a/docs/references/js/type-aliases/AuthServerConfigWarning.md +++ b/docs/references/js/type-aliases/AuthServerConfigWarning.md @@ -13,9 +13,9 @@ type AuthServerConfigWarning = { Represents a warning that occurs during the validation of the authorization server metadata. -## Properties +## Properties {#properties} -### code +### code {#code} ```ts code: AuthServerConfigWarningCode; @@ -25,7 +25,7 @@ The code representing the specific validation warning. *** -### description +### description {#description} ```ts description: string; diff --git a/docs/references/js/type-aliases/AuthServerModeConfig.md b/docs/references/js/type-aliases/AuthServerModeConfig.md index 6cb5594..da4c827 100644 --- a/docs/references/js/type-aliases/AuthServerModeConfig.md +++ b/docs/references/js/type-aliases/AuthServerModeConfig.md @@ -12,13 +12,13 @@ type AuthServerModeConfig = { Configuration for the legacy, MCP server as authorization server mode. -## Deprecated +## Deprecated {#deprecated} Use `ResourceServerModeConfig` config instead. -## Properties +## Properties {#properties} -### ~~server~~ +### ~~server~~ {#server} ```ts server: AuthServerConfig; @@ -26,6 +26,6 @@ server: AuthServerConfig; The single authorization server configuration. -#### Deprecated +#### Deprecated {#deprecated} Use `protectedResources` config instead. diff --git a/docs/references/js/type-aliases/AuthorizationServerMetadata.md b/docs/references/js/type-aliases/AuthorizationServerMetadata.md index 1bbf982..b07bdc2 100644 --- a/docs/references/js/type-aliases/AuthorizationServerMetadata.md +++ b/docs/references/js/type-aliases/AuthorizationServerMetadata.md @@ -34,9 +34,9 @@ type AuthorizationServerMetadata = { Schema for OAuth 2.0 Authorization Server Metadata as defined in RFC 8414. -## Type declaration +## Type declaration {#type-declaration} -### authorization\_endpoint +### authorization\_endpoint {#authorization-endpoint} ```ts authorization_endpoint: string; @@ -45,11 +45,11 @@ authorization_endpoint: string; URL of the authorization server's authorization endpoint [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. This is REQUIRED unless no grant types are supported that use the authorization endpoint. -#### See +#### See {#see} https://rfc-editor.org/rfc/rfc6749#section-3.1 -### code\_challenge\_methods\_supported? +### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} ```ts optional code_challenge_methods_supported: string[]; @@ -59,7 +59,7 @@ JSON array containing a list of Proof Key for Code Exchange (PKCE) [[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] code challenge methods supported by this authorization server. -### grant\_types\_supported? +### grant\_types\_supported? {#grant-types-supported} ```ts optional grant_types_supported: string[]; @@ -70,7 +70,7 @@ supports. The array values used are the same as those used with the `grant_types defined by "OAuth 2.0 Dynamic Client Registration Protocol" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. If omitted, the default value is `["authorization_code", "implicit"]`. -### introspection\_endpoint? +### introspection\_endpoint? {#introspection-endpoint} ```ts optional introspection_endpoint: string; @@ -79,19 +79,19 @@ optional introspection_endpoint: string; URL of the authorization server's OAuth 2.0 introspection endpoint [[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. -### introspection\_endpoint\_auth\_methods\_supported? +### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} ```ts optional introspection_endpoint_auth_methods_supported: string[]; ``` -### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? +### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} ```ts optional introspection_endpoint_auth_signing_alg_values_supported: string[]; ``` -### issuer +### issuer {#issuer} ```ts issuer: string; @@ -100,7 +100,7 @@ issuer: string; The authorization server's issuer identifier, which is a URL that uses the `https` scheme and has no query or fragment components. -### jwks\_uri? +### jwks\_uri? {#jwks-uri} ```ts optional jwks_uri: string; @@ -110,19 +110,19 @@ URL of the authorization server's JWK Set [[JWK](https://www.rfc-editor.org/rfc/ document. The referenced document contains the signing key(s) the client uses to validate signatures from the authorization server. This URL MUST use the `https` scheme. -### op\_policy\_uri? +### op\_policy\_uri? {#op-policy-uri} ```ts optional op_policy_uri: string; ``` -### op\_tos\_uri? +### op\_tos\_uri? {#op-tos-uri} ```ts optional op_tos_uri: string; ``` -### registration\_endpoint? +### registration\_endpoint? {#registration-endpoint} ```ts optional registration_endpoint: string; @@ -131,7 +131,7 @@ optional registration_endpoint: string; URL of the authorization server's OAuth 2.0 Dynamic Client Registration endpoint [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. -### response\_modes\_supported? +### response\_modes\_supported? {#response-modes-supported} ```ts optional response_modes_supported: string[]; @@ -146,7 +146,7 @@ If omitted, the default is `["query", "fragment"]`. The response mode value `"fo also defined in "OAuth 2.0 Form Post Response Mode" [[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]. -### response\_types\_supported +### response\_types\_supported {#response-types-supported} ```ts response_types_supported: string[]; @@ -157,7 +157,7 @@ server supports. The array values used are the same as those used with the `resp parameter defined by "OAuth 2.0 Dynamic Client Registration Protocol" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. -### revocation\_endpoint? +### revocation\_endpoint? {#revocation-endpoint} ```ts optional revocation_endpoint: string; @@ -166,19 +166,19 @@ optional revocation_endpoint: string; URL of the authorization server's OAuth 2.0 revocation endpoint [[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. -### revocation\_endpoint\_auth\_methods\_supported? +### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} ```ts optional revocation_endpoint_auth_methods_supported: string[]; ``` -### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? +### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} ```ts optional revocation_endpoint_auth_signing_alg_values_supported: string[]; ``` -### scopes\_supported? +### scopes\_supported? {#scopes-supported} ```ts optional scopes_supported: string[]; @@ -188,13 +188,13 @@ JSON array containing a list of the OAuth 2.0 `scope` values that this authoriza supports. [[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] -### service\_documentation? +### service\_documentation? {#service-documentation} ```ts optional service_documentation: string; ``` -### token\_endpoint +### token\_endpoint {#token-endpoint} ```ts token_endpoint: string; @@ -203,29 +203,29 @@ token_endpoint: string; URL of the authorization server's token endpoint [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. This is REQUIRED unless only the implicit grant type is supported. -#### See +#### See {#see} https://rfc-editor.org/rfc/rfc6749#section-3.2 -### token\_endpoint\_auth\_methods\_supported? +### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} ```ts optional token_endpoint_auth_methods_supported: string[]; ``` -### token\_endpoint\_auth\_signing\_alg\_values\_supported? +### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} ```ts optional token_endpoint_auth_signing_alg_values_supported: string[]; ``` -### ui\_locales\_supported? +### ui\_locales\_supported? {#ui-locales-supported} ```ts optional ui_locales_supported: string[]; ``` -### userinfo\_endpoint? +### userinfo\_endpoint? {#userinfo-endpoint} ```ts optional userinfo_endpoint: string; @@ -234,6 +234,6 @@ optional userinfo_endpoint: string; URL of the OpenID Connect [userinfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo). This endpoint is used to retrieve information about the authenticated user. -## See +## See {#see} https://datatracker.ietf.org/doc/html/rfc8414 diff --git a/docs/references/js/type-aliases/BearerAuthConfig.md b/docs/references/js/type-aliases/BearerAuthConfig.md index 82bb23e..cfb0f36 100644 --- a/docs/references/js/type-aliases/BearerAuthConfig.md +++ b/docs/references/js/type-aliases/BearerAuthConfig.md @@ -16,9 +16,9 @@ type BearerAuthConfig = { }; ``` -## Properties +## Properties {#properties} -### audience? +### audience? {#audience} ```ts optional audience: string; @@ -30,13 +30,13 @@ The expected audience of the access token (`aud` claim). This is typically the r **Note:** If your authorization server does not support Resource Indicators (RFC 8707), you can omit this field since the audience may not be relevant. -#### See +#### See {#see} https://datatracker.ietf.org/doc/html/rfc8707 *** -### issuer +### issuer {#issuer} ```ts issuer: @@ -51,13 +51,13 @@ If a string is provided, it will be used as the expected issuer value for direct If a function is provided, it should validate the issuer according to the rules in [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md). -#### See +#### See {#see} [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) for more details about the validation function. *** -### requiredScopes? +### requiredScopes? {#requiredscopes} ```ts optional requiredScopes: string[]; @@ -73,7 +73,7 @@ if available. *** -### resource? +### resource? {#resource} ```ts optional resource: string; @@ -85,7 +85,7 @@ It's required when using the handler with a `protectedResources` configuration. *** -### showErrorDetails? +### showErrorDetails? {#showerrordetails} ```ts optional showErrorDetails: boolean; @@ -95,7 +95,7 @@ Whether to show detailed error information in the response. This is useful for d during development, but should be disabled in production to avoid leaking sensitive information. -#### Default +#### Default {#default} ```ts false @@ -103,7 +103,7 @@ false *** -### verifyAccessToken +### verifyAccessToken {#verifyaccesstoken} ```ts verifyAccessToken: VerifyAccessTokenFunction; @@ -114,6 +114,6 @@ Function type for verifying an access token. This function should throw an [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) if the token is invalid, or return an AuthInfo object if the token is valid. -#### See +#### See {#see} [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) for more details. diff --git a/docs/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/docs/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md index 630f7dd..b2d0efa 100644 --- a/docs/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md +++ b/docs/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md @@ -34,146 +34,146 @@ type CamelCaseAuthorizationServerMetadata = { The camelCase version of the OAuth 2.0 Authorization Server Metadata type. -## Type declaration +## Type declaration {#type-declaration} -### authorizationEndpoint +### authorizationEndpoint {#authorizationendpoint} ```ts authorizationEndpoint: string; ``` -### codeChallengeMethodsSupported? +### codeChallengeMethodsSupported? {#codechallengemethodssupported} ```ts optional codeChallengeMethodsSupported: string[]; ``` -### grantTypesSupported? +### grantTypesSupported? {#granttypessupported} ```ts optional grantTypesSupported: string[]; ``` -### introspectionEndpoint? +### introspectionEndpoint? {#introspectionendpoint} ```ts optional introspectionEndpoint: string; ``` -### introspectionEndpointAuthMethodsSupported? +### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} ```ts optional introspectionEndpointAuthMethodsSupported: string[]; ``` -### introspectionEndpointAuthSigningAlgValuesSupported? +### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} ```ts optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; ``` -### issuer +### issuer {#issuer} ```ts issuer: string; ``` -### jwksUri? +### jwksUri? {#jwksuri} ```ts optional jwksUri: string; ``` -### opPolicyUri? +### opPolicyUri? {#oppolicyuri} ```ts optional opPolicyUri: string; ``` -### opTosUri? +### opTosUri? {#optosuri} ```ts optional opTosUri: string; ``` -### registrationEndpoint? +### registrationEndpoint? {#registrationendpoint} ```ts optional registrationEndpoint: string; ``` -### responseModesSupported? +### responseModesSupported? {#responsemodessupported} ```ts optional responseModesSupported: string[]; ``` -### responseTypesSupported +### responseTypesSupported {#responsetypessupported} ```ts responseTypesSupported: string[]; ``` -### revocationEndpoint? +### revocationEndpoint? {#revocationendpoint} ```ts optional revocationEndpoint: string; ``` -### revocationEndpointAuthMethodsSupported? +### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} ```ts optional revocationEndpointAuthMethodsSupported: string[]; ``` -### revocationEndpointAuthSigningAlgValuesSupported? +### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} ```ts optional revocationEndpointAuthSigningAlgValuesSupported: string[]; ``` -### scopesSupported? +### scopesSupported? {#scopessupported} ```ts optional scopesSupported: string[]; ``` -### serviceDocumentation? +### serviceDocumentation? {#servicedocumentation} ```ts optional serviceDocumentation: string; ``` -### tokenEndpoint +### tokenEndpoint {#tokenendpoint} ```ts tokenEndpoint: string; ``` -### tokenEndpointAuthMethodsSupported? +### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} ```ts optional tokenEndpointAuthMethodsSupported: string[]; ``` -### tokenEndpointAuthSigningAlgValuesSupported? +### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} ```ts optional tokenEndpointAuthSigningAlgValuesSupported: string[]; ``` -### uiLocalesSupported? +### uiLocalesSupported? {#uilocalessupported} ```ts optional uiLocalesSupported: string[]; ``` -### userinfoEndpoint? +### userinfoEndpoint? {#userinfoendpoint} ```ts optional userinfoEndpoint: string; ``` -## See +## See {#see} [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) for the original type and field information. diff --git a/docs/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/docs/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md index f12fabb..390e9de 100644 --- a/docs/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md +++ b/docs/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md @@ -26,98 +26,98 @@ type CamelCaseProtectedResourceMetadata = { The camelCase version of the OAuth 2.0 Protected Resource Metadata type. -## Type declaration +## Type declaration {#type-declaration} -### authorizationDetailsTypesSupported? +### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} ```ts optional authorizationDetailsTypesSupported: string[]; ``` -### authorizationServers? +### authorizationServers? {#authorizationservers} ```ts optional authorizationServers: string[]; ``` -### bearerMethodsSupported? +### bearerMethodsSupported? {#bearermethodssupported} ```ts optional bearerMethodsSupported: string[]; ``` -### dpopBoundAccessTokensRequired? +### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} ```ts optional dpopBoundAccessTokensRequired: boolean; ``` -### dpopSigningAlgValuesSupported? +### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} ```ts optional dpopSigningAlgValuesSupported: string[]; ``` -### jwksUri? +### jwksUri? {#jwksuri} ```ts optional jwksUri: string; ``` -### resource +### resource {#resource} ```ts resource: string; ``` -### resourceDocumentation? +### resourceDocumentation? {#resourcedocumentation} ```ts optional resourceDocumentation: string; ``` -### resourceName? +### resourceName? {#resourcename} ```ts optional resourceName: string; ``` -### resourcePolicyUri? +### resourcePolicyUri? {#resourcepolicyuri} ```ts optional resourcePolicyUri: string; ``` -### resourceSigningAlgValuesSupported? +### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} ```ts optional resourceSigningAlgValuesSupported: string[]; ``` -### resourceTosUri? +### resourceTosUri? {#resourcetosuri} ```ts optional resourceTosUri: string; ``` -### scopesSupported? +### scopesSupported? {#scopessupported} ```ts optional scopesSupported: string[]; ``` -### signedMetadata? +### signedMetadata? {#signedmetadata} ```ts optional signedMetadata: string; ``` -### tlsClientCertificateBoundAccessTokens? +### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} ```ts optional tlsClientCertificateBoundAccessTokens: boolean; ``` -## See +## See {#see} [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) for the original type and field information. diff --git a/docs/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/docs/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md index d3ae27f..9961d48 100644 --- a/docs/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md +++ b/docs/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md @@ -14,9 +14,9 @@ type MCPAuthBearerAuthErrorDetails = { }; ``` -## Properties +## Properties {#properties} -### actual? +### actual? {#actual} ```ts optional actual: unknown; @@ -24,7 +24,7 @@ optional actual: unknown; *** -### cause? +### cause? {#cause} ```ts optional cause: unknown; @@ -32,7 +32,7 @@ optional cause: unknown; *** -### expected? +### expected? {#expected} ```ts optional expected: unknown; @@ -40,7 +40,7 @@ optional expected: unknown; *** -### missingScopes? +### missingScopes? {#missingscopes} ```ts optional missingScopes: string[]; @@ -48,7 +48,7 @@ optional missingScopes: string[]; *** -### uri? +### uri? {#uri} ```ts optional uri: URL; diff --git a/docs/references/js/type-aliases/ProtectedResourceMetadata.md b/docs/references/js/type-aliases/ProtectedResourceMetadata.md index 6e13cb4..fd705f7 100644 --- a/docs/references/js/type-aliases/ProtectedResourceMetadata.md +++ b/docs/references/js/type-aliases/ProtectedResourceMetadata.md @@ -26,9 +26,9 @@ type ProtectedResourceMetadata = { Schema for OAuth 2.0 Protected Resource Metadata. -## Type declaration +## Type declaration {#type-declaration} -### authorization\_details\_types\_supported? +### authorization\_details\_types\_supported? {#authorization-details-types-supported} ```ts optional authorization_details_types_supported: string[]; @@ -36,7 +36,7 @@ optional authorization_details_types_supported: string[]; Authorization details type values supported when using the authorization_details request parameter. -### authorization\_servers? +### authorization\_servers? {#authorization-servers} ```ts optional authorization_servers: string[]; @@ -44,7 +44,7 @@ optional authorization_servers: string[]; List of OAuth authorization server issuer identifiers that can be used with this protected resource. -### bearer\_methods\_supported? +### bearer\_methods\_supported? {#bearer-methods-supported} ```ts optional bearer_methods_supported: string[]; @@ -52,7 +52,7 @@ optional bearer_methods_supported: string[]; Supported methods for sending OAuth 2.0 bearer tokens. Values: ["header", "body", "query"]. -### dpop\_bound\_access\_tokens\_required? +### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} ```ts optional dpop_bound_access_tokens_required: boolean; @@ -60,7 +60,7 @@ optional dpop_bound_access_tokens_required: boolean; Whether the protected resource always requires DPoP-bound access tokens. -### dpop\_signing\_alg\_values\_supported? +### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} ```ts optional dpop_signing_alg_values_supported: string[]; @@ -68,7 +68,7 @@ optional dpop_signing_alg_values_supported: string[]; JWS algorithms supported for validating DPoP proof JWTs. -### jwks\_uri? +### jwks\_uri? {#jwks-uri} ```ts optional jwks_uri: string; @@ -80,7 +80,7 @@ This differs from the authorization server's jwks_uri which is used for token va resource signs its responses, clients can fetch these public keys to verify the authenticity and integrity of the received data. -### resource +### resource {#resource} ```ts resource: string; @@ -88,7 +88,7 @@ resource: string; The protected resource's resource identifier. -### resource\_documentation? +### resource\_documentation? {#resource-documentation} ```ts optional resource_documentation: string; @@ -96,7 +96,7 @@ optional resource_documentation: string; URL containing developer documentation for using the protected resource. -### resource\_name? +### resource\_name? {#resource-name} ```ts optional resource_name: string; @@ -104,7 +104,7 @@ optional resource_name: string; Human-readable name of the protected resource for display to end users. -### resource\_policy\_uri? +### resource\_policy\_uri? {#resource-policy-uri} ```ts optional resource_policy_uri: string; @@ -112,7 +112,7 @@ optional resource_policy_uri: string; URL containing information about the protected resource's data usage requirements. -### resource\_signing\_alg\_values\_supported? +### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} ```ts optional resource_signing_alg_values_supported: string[]; @@ -120,7 +120,7 @@ optional resource_signing_alg_values_supported: string[]; JWS signing algorithms supported by the protected resource for signing resource responses. -### resource\_tos\_uri? +### resource\_tos\_uri? {#resource-tos-uri} ```ts optional resource_tos_uri: string; @@ -128,7 +128,7 @@ optional resource_tos_uri: string; URL containing the protected resource's terms of service. -### scopes\_supported? +### scopes\_supported? {#scopes-supported} ```ts optional scopes_supported: string[]; @@ -136,7 +136,7 @@ optional scopes_supported: string[]; List of scope values used in authorization requests to access this protected resource. -### signed\_metadata? +### signed\_metadata? {#signed-metadata} ```ts optional signed_metadata: string; @@ -148,7 +148,7 @@ itself. The signature can be verified using the public keys available at the `jw When present, the values in this signed metadata take precedence over the corresponding plain JSON values in this metadata document. This helps prevent tampering with the resource metadata. -### tls\_client\_certificate\_bound\_access\_tokens? +### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} ```ts optional tls_client_certificate_bound_access_tokens: boolean; diff --git a/docs/references/js/type-aliases/ResourceServerModeConfig.md b/docs/references/js/type-aliases/ResourceServerModeConfig.md index 465d870..a87ce1b 100644 --- a/docs/references/js/type-aliases/ResourceServerModeConfig.md +++ b/docs/references/js/type-aliases/ResourceServerModeConfig.md @@ -12,9 +12,9 @@ type ResourceServerModeConfig = { Configuration for the MCP server as resource server mode. -## Properties +## Properties {#properties} -### protectedResources +### protectedResources {#protectedresources} ```ts protectedResources: ResourceServerConfig | ResourceServerConfig[]; diff --git a/docs/references/js/type-aliases/ValidateIssuerFunction.md b/docs/references/js/type-aliases/ValidateIssuerFunction.md index 8f84991..b6f1d9f 100644 --- a/docs/references/js/type-aliases/ValidateIssuerFunction.md +++ b/docs/references/js/type-aliases/ValidateIssuerFunction.md @@ -16,16 +16,16 @@ is not valid. The issuer should be validated against: 1. The authorization servers configured in MCP-Auth's auth server metadata 2. The authorization servers listed in the protected resource's metadata -## Parameters +## Parameters {#parameters} -### tokenIssuer +### tokenIssuer {#tokenissuer} `string` -## Returns +## Returns {#returns} `void` -## Throws +## Throws {#throws} When the issuer is not recognized or invalid. diff --git a/docs/references/js/type-aliases/VerifyAccessTokenFunction.md b/docs/references/js/type-aliases/VerifyAccessTokenFunction.md index 625cd96..2bb7325 100644 --- a/docs/references/js/type-aliases/VerifyAccessTokenFunction.md +++ b/docs/references/js/type-aliases/VerifyAccessTokenFunction.md @@ -24,15 +24,15 @@ by the handler: - `aud` (audience) - `scope` (scopes) -## Parameters +## Parameters {#parameters} -### token +### token {#token} `string` The access token string to verify. -## Returns +## Returns {#returns} `MaybePromise`\<`AuthInfo`\> diff --git a/docs/references/js/variables/authorizationServerMetadataSchema.md b/docs/references/js/variables/authorizationServerMetadataSchema.md index 5ce269a..2b10818 100644 --- a/docs/references/js/variables/authorizationServerMetadataSchema.md +++ b/docs/references/js/variables/authorizationServerMetadataSchema.md @@ -10,6 +10,6 @@ const authorizationServerMetadataSchema: ZodObject; Zod schema for OAuth 2.0 Authorization Server Metadata as defined in RFC 8414. -## See +## See {#see} https://datatracker.ietf.org/doc/html/rfc8414 diff --git a/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md index a96a929..daaa358 100644 --- a/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ b/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md @@ -10,6 +10,6 @@ const camelCaseAuthorizationServerMetadataSchema: ZodObject + + +```bash +pip install mcpauth +``` + +Oder ein anderer Paketmanager deiner Wahl, wie pipenv oder poetry. + + + + +```bash +npm install mcp-auth +``` + +Oder ein anderer Paketmanager deiner Wahl, wie pnpm oder yarn. + + + + +## Initialisiere MCP Auth \{#init-mcp-auth} + +Der erste Schritt ist, deinen Ressourcenbezeichner zu definieren und den Autorisierungsserver zu konfigurieren, dem für die Authentifizierung vertraut wird. MCP Auth arbeitet jetzt im Ressourcenserver-Modus und entspricht der aktualisierten MCP-Spezifikation, die OAuth 2.0 Protected Resource Metadata (RFC 9728) erfordert. + +Wenn dein Anbieter konform ist mit: + +- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +kannst du die eingebaute Funktion nutzen, um die Metadaten abzurufen und die MCP Auth-Instanz zu initialisieren: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType, ResourceServerConfig, ResourceServerMetadata +from mcpauth.utils import fetch_server_config + +# 1. Definiere deinen Ressourcenbezeichner und hole die Konfiguration für den vertrauenswürdigen Autorisierungsserver. +resource_id = "https://api.example.com/notes" +auth_server_config = fetch_server_config("https://auth.logto.io/oidc", AuthServerType.OIDC) + +# 2. Initialisiere MCPAuth im Ressourcenserver-Modus. +# `protected_resources` kann ein einzelnes Objekt oder eine Liste für mehrere Ressourcen sein. +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +// 1. Definiere deinen Ressourcenbezeichner und hole die Konfiguration für den vertrauenswürdigen Autorisierungsserver. +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +// 2. Initialisiere MCPAuth im Ressourcenserver-Modus. +// `protectedResources` kann ein einzelnes Objekt oder ein Array für mehrere Ressourcen sein. +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +Für weitere Möglichkeiten, die Metadaten des Autorisierungsservers zu konfigurieren, einschließlich benutzerdefinierter Metadaten-URLs, Daten-Transpilation oder manueller Metadatenspezifikation, siehe [Weitere Möglichkeiten zur Konfiguration von MCP Auth](./configure-server/mcp-auth.mdx#other-ways). + +## Binde den Endpunkt für die Metadaten der geschützten Ressource ein \{#mount-the-protected-resource-metadata-endpoint} + +Um der aktualisierten MCP-Spezifikation zu entsprechen, bindet MCP Auth den OAuth 2.0 Protected Resource Metadata-Endpunkt (RFC 9728) in deinen MCP-Server ein. Dieser Endpunkt ermöglicht es Clients, zu entdecken: + +- Welche Autorisierungsserver gültige Tokens für deine geschützten Ressourcen ausstellen können +- Welche Berechtigungen (Scopes) für jede Ressource unterstützt werden +- Weitere Metadaten, die für die korrekte Token-Validierung erforderlich sind + +Der Endpunktpfad wird automatisch durch den Pfadbestandteil deines Ressourcenbezeichners bestimmt: + +- **Kein Pfad**: `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **Mit Pfad**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + +Der MCP-Server dient jetzt **als Ressourcenserver**, der Tokens validiert und Metadaten über seine geschützten Ressourcen bereitstellt, während er sich vollständig auf externe Autorisierungsserver für Authentifizierung und Autorisierung verlässt. + +Du kannst die vom SDK bereitgestellte Methode verwenden, um diesen Endpunkt einzubinden: + + + + +```python +from starlette.applications import Starlette + +# Binde den Router ein, um die Protected Resource Metadata bereitzustellen. +# Für Ressource "https://api.example.com" → Endpunkt: /.well-known/oauth-protected-resource +# Für Ressource "https://api.example.com/notes" → Endpunkt: /.well-known/oauth-protected-resource/notes +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// Binde den Router ein, um die Protected Resource Metadata bereitzustellen. +// Für Ressource "https://api.example.com" → Endpunkt: /.well-known/oauth-protected-resource +// Für Ressource "https://api.example.com/notes" → Endpunkt: /.well-known/oauth-protected-resource/notes +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + + +## Verwende das Bearer-Auth-Middleware \{#use-the-bearer-auth-middleware} + +Sobald die MCP Auth-Instanz initialisiert ist, kannst du das Bearer-Auth-Middleware anwenden, um deine MCP-Routen zu schützen. Das Middleware erfordert jetzt die Angabe, zu welcher Ressource der Endpunkt gehört, um eine korrekte Token-Validierung zu ermöglichen: + +:::note Zielgruppenvalidierung (Audience Validation) +Der Parameter `audience` ist **erforderlich** gemäß der OAuth 2.0-Spezifikation für eine sichere Token-Validierung. Er ist jedoch derzeit **optional**, um die Kompatibilität mit Autorisierungsservern zu gewährleisten, die noch keine Ressourcenbezeichner unterstützen. Aus Sicherheitsgründen **bitte immer den audience-Parameter angeben**, wenn möglich. Zukünftige Versionen werden die Zielgruppenvalidierung verpflichtend machen, um die Spezifikation vollständig zu erfüllen. +::: + + + + +```python +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount + +# Erstelle das Middleware, um deinen MCP-Server mit der ressourcenspezifischen Richtlinie zu schützen. +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', + resource=resource_id, + audience=resource_id, # Zielgruppenvalidierung für Sicherheit aktivieren + required_scopes=['read:notes'] +)) + +# Binde den Router ein, um die Protected Resource Metadata bereitzustellen und schütze den MCP-Server. +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # Schütze den MCP-Server mit dem Bearer-Auth-Middleware. + Mount("/", app=mcp.sse_app(), middleware=[bearer_auth]), + ], +) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// Binde den Router ein, um die Protected Resource Metadata bereitzustellen. +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Schütze einen API-Endpunkt mit der ressourcenspezifischen Richtlinie. +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, // Zielgruppenvalidierung für Sicherheit aktivieren + requiredScopes: ['read:notes'], + }), + (req, res) => { + // Wenn das Token gültig ist, wird `req.auth` mit seinen Ansprüchen befüllt. + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); + +app.listen(3000); +``` + + + + +In den obigen Beispielen geben wir den Token-Typ `jwt` und den Ressourcenbezeichner an. Das Middleware validiert das JWT-Token automatisch gegen die für diese Ressource konfigurierten vertrauenswürdigen Autorisierungsserver und befüllt die Informationen des authentifizierten Benutzers. + +:::info +Noch nie von JWT (JSON Web Token) gehört? Keine Sorge, du kannst die Dokumentation einfach weiterlesen – wir erklären es, wenn es nötig ist. Du kannst auch das [Auth Wiki](https://auth.wiki/jwt) für eine kurze Einführung besuchen. +::: + +Weitere Informationen zur Bearer-Auth-Konfiguration findest du unter [Bearer-Auth konfigurieren](./configure-server/bearer-auth.mdx). + +## Auth-Informationen in deiner MCP-Implementierung abrufen \{#retrieve-the-auth-info-in-your-mcp-implementation} + +Sobald das Bearer-Auth-Middleware angewendet ist, kannst du auf die Informationen des authentifizierten Benutzers (oder der Identität) in deiner MCP-Implementierung zugreifen: + + + + +MCP Auth speichert die Informationen des authentifizierten Benutzers nach erfolgreicher Authentifizierung in einer Kontextvariablen, sobald das Bearer-Auth-Middleware angewendet ist. Du kannst darauf in deinen MCP-Tool-Handlern wie folgt zugreifen: + +```python +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP() + +# Initialisiere mit MCP Auth wie in den vorherigen Beispielen gezeigt +# ... + +@mcp.tool() +def add(a: int, b: int): + """ + Ein Tool, das zwei Zahlen addiert. + Die Informationen des authentifizierten Benutzers sind im Kontext verfügbar. + """ + auth_info = mcp_auth.auth_info # Zugriff auf die Auth-Informationen im aktuellen Kontext + if auth_info: + print(f"Authentifizierter Benutzer: {auth_info.claims}") + return a + b +``` + + + + +Das zweite Argument des Tool-Handlers enthält das `authInfo`-Objekt, das die Informationen des authentifizierten Benutzers beinhaltet: + +```ts +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { z } from 'zod'; + +const server = new McpServer(/* ... */); + +// Initialisiere mit MCP Auth wie in den vorherigen Beispielen gezeigt +// ... + +server.tool('add', { a: z.number(), b: z.number() }, async ({ a, b }, { authInfo }) => { + // Jetzt kannst du das `authInfo`-Objekt verwenden, um auf die authentifizierten Informationen zuzugreifen +}); +``` + + + + +## Nächste Schritte \{#next-steps} + +Lies weiter, um ein End-to-End-Beispiel zu erfahren, wie du MCP Auth mit deinem MCP-Server integrierst und wie du den Auth-Flow in MCP-Clients behandelst. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx b/i18n/de/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx new file mode 100644 index 0000000..34c96a5 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx @@ -0,0 +1,280 @@ +--- +sidebar_position: 2 +sidebar_label: Bearer-Authentifizierung +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# Bearer-Authentifizierung im MCP-Server konfigurieren + +Mit der neuesten MCP-Spezifikation agiert dein MCP-Server als **Ressourcenserver**, der Zugangstokens für geschützte Ressourcen validiert. MCP Auth bietet verschiedene Möglichkeiten, die Bearer-Autorisierung zu konfigurieren: + +- [JWT (JSON Web Token)](https://auth.wiki/jwt)-Modus: Eine integrierte Autorisierungsmethode, die JWTs mit Anspruchsüberprüfungen validiert. +- Benutzerdefinierter Modus: Ermöglicht es dir, deine eigene Autorisierungslogik zu implementieren. + +Das Bearer-Auth-Middleware erfordert nun die Angabe, zu welcher Ressource der Endpunkt gehört, um eine korrekte Tokenvalidierung gegenüber den konfigurierten Autorisierungsservern zu ermöglichen. + +## Bearer-Authentifizierung mit JWT-Modus konfigurieren \{#configure-bearer-auth-with-jwt-mode} + +Wenn dein OAuth / OIDC-Anbieter JWTs zur Autorisierung ausstellt, kannst du den integrierten JWT-Modus in MCP Auth verwenden. Er überprüft die JWT-Signatur, das Ablaufdatum und andere von dir angegebene Ansprüche; anschließend werden die Authentifizierungsinformationen im Request-Kontext für die weitere Verarbeitung in deiner MCP-Implementierung bereitgestellt. + +### Berechtigungsprüfung (Scope validation) \{#scope-validation} + +Hier ein Beispiel für die grundlegende Berechtigungsprüfung: + + + + +```python +from mcpauth import MCPAuth +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP("MyMCPServer") +mcp_auth = MCPAuth( + # Initialisiere mit deiner Auth-Server-Konfiguration +) +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", # Gib an, zu welcher Ressource dieser Endpunkt gehört + audience="https://api.example.com", # Aktiviere die Zielgruppenvalidierung für Sicherheit + required_scopes=["read", "write"] # [!code highlight] +) + +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + /* ... */ +}); +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // Gib an, zu welcher Ressource dieser Endpunkt gehört + audience: 'https://api.example.com', // Aktiviere die Zielgruppenvalidierung für Sicherheit + requiredScopes: ['read', 'write'] // [!code highlight] +}); + +app.use('/mcp', bearerAuth, (req, res) => { + // Jetzt enthält `req.auth` die Auth-Informationen + console.log(req.auth); +}); +``` + + + + +Im obigen Beispiel haben wir angegeben, dass das JWT die Berechtigungen `read` und `write` benötigt. Wenn das JWT **keine** dieser Berechtigungen enthält, wird die Anfrage mit einem 403 Forbidden-Fehler abgelehnt. + +### Zielgruppenvalidierung (Audience validation, RFC 8707) \{#audience-validation-rfc-8707} + +Für eine sichere Tokenvalidierung solltest du immer die Zielgruppenvalidierung aktivieren, indem du den Parameter `audience` angibst. Dadurch wird der `aud` (Zielgruppe)-Anspruch im JWT validiert, um sicherzustellen, dass das Token speziell für deine MCP-Server-Ressource ausgestellt wurde. + +:::note Audience Validation +Der Parameter `audience` ist gemäß der OAuth 2.0-Spezifikation für eine sichere Tokenvalidierung **erforderlich**. Er ist jedoch derzeit **optional**, um die Kompatibilität mit Autorisierungsservern zu gewährleisten, die noch keine Ressourcenindikatoren unterstützen. Aus Sicherheitsgründen **bitte immer den Audience-Parameter angeben**, wenn möglich. Zukünftige Versionen werden die Zielgruppenvalidierung verpflichtend machen, um die Spezifikation vollständig zu erfüllen. +::: + +Der Audience-Wert sollte in der Regel mit deinem Ressourcenindikator übereinstimmen: + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", # Gib an, zu welcher Ressource dieser Endpunkt gehört + audience="https://api.example.com", # Aktiviere die Zielgruppenvalidierung für Sicherheit [!code highlight] + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // Gib an, zu welcher Ressource dieser Endpunkt gehört + audience: 'https://api.example.com', // Aktiviere die Zielgruppenvalidierung für Sicherheit [!code highlight] + requiredScopes: ['read', 'write'], +}); +``` + + + + +Im obigen Beispiel validiert MCP Auth **sowohl** den `aud`-Anspruch im JWT als auch die erforderlichen Berechtigungen. + +### Benutzerdefinierte Optionen für die JWT-Überprüfung angeben \{#provide-custom-options-to-the-jwt-verification} + +Du kannst auch benutzerdefinierte Optionen an die zugrunde liegende JWT-Überprüfungsbibliothek übergeben: + + + + +Im Python SDK verwenden wir [PyJWT](https://pyjwt.readthedocs.io/en/stable/) für die JWT-Überprüfung. Du kannst folgende Optionen nutzen: + +- `leeway`: Erlaubt eine gewisse Toleranz bei der Überprüfung der JWT-Ablaufzeit (in Sekunden). Standard ist 60 Sekunden. + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", + audience="https://api.example.com", + required_scopes=["read", "write"], + leeway=10, # Reduziere Zeitabweichungen, indem du 10 Sekunden Toleranz erlaubst [!code highlight] +) +``` + + + + +Im Node.js SDK verwenden wir die [jose](https://github.com/panva/jose)-Bibliothek für die JWT-Überprüfung. Du kannst folgende Optionen angeben: + +- `jwtVerify`: Optionen für den JWT-Überprüfungsprozess (`jwtVerify`-Funktion von `jose`). +- `remoteJwtSet`: Optionen für das Abrufen des Remote-JWT-Sets (`createRemoteJWKSet`-Funktion von `jose`). + +```ts {5-10} +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', + requiredScopes: ['read', 'write'], + jwtVerify: { + clockTolerance: 60, // Erlaube eine Zeitabweichung von 60 Sekunden + }, + remoteJwtSet: { + timeoutDuration: 10 * 1000, // 10 Sekunden Timeout für das Abrufen des Remote-JWT-Sets + }, +}); +``` + + + + +## Bearer-Authentifizierung mit benutzerdefinierter Überprüfung konfigurieren \{#configure-bearer-auth-with-custom-verification} + +Wenn dein OAuth / OIDC-Anbieter keine JWTs ausstellt oder du deine eigene Autorisierungslogik implementieren möchtest, erlaubt dir MCP Auth, eine benutzerdefinierte Überprüfungsfunktion zu erstellen: + +:::info +Da das Bearer-Auth-Middleware den Aussteller (`iss`), die Zielgruppe (`aud`) und die erforderlichen Berechtigungen (`scope`) mit dem Überprüfungsergebnis abgleicht, musst du diese Prüfungen nicht in deiner benutzerdefinierten Überprüfungsfunktion implementieren. Du kannst dich darauf konzentrieren, die Token-Gültigkeit zu überprüfen (z. B. Signatur, Ablauf usw.) und das Auth-Info-Objekt zurückzugeben. +::: + + + + +```python +from mcpauth.exceptions import MCPAuthJwtVerificationException, MCPAuthJwtVerificationExceptionCode +from mcpauth.types import AuthInfo + +async def custom_verification(token: str) -> AuthInfo: + # Implementiere hier deine benutzerdefinierte Überprüfungslogik + info = await verify_token(token) + if not info: + raise MCPAuthJwtVerificationException( + MCPAuthJwtVerificationExceptionCode.JWT_VERIFICATION_FAILED + ) + return info # Gib das Auth-Info-Objekt zurück + +bearer_auth = mcp_auth.bearer_auth_middleware( + custom_verification, + resource="https://api.example.com", + audience="https://api.example.com", # Aktiviere die Zielgruppenvalidierung für Sicherheit + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth( + async (token) => { + // Implementiere hier deine benutzerdefinierte Überprüfungslogik + const info = await verifyToken(token); + if (!info) { + throw new MCPAuthJwtVerificationError('jwt_verification_failed'); + } + return info; // Gib das Auth-Info-Objekt zurück + }, + { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // Aktiviere die Zielgruppenvalidierung für Sicherheit + requiredScopes: ['read', 'write'] + } +); +``` + + + + +## Bearer-Authentifizierung in deinem MCP-Server anwenden \{#apply-bearer-auth-in-your-mcp-server} + +Um deinen MCP-Server mit Bearer-Authentifizierung zu schützen, musst du das Bearer-Auth-Middleware auf deine MCP-Server-Instanz anwenden. + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", + audience="https://api.example.com", # Aktiviere die Zielgruppenvalidierung für Sicherheit + required_scopes=["read", "write"] +) +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```js +const app = express(); +app.use(mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // Aktiviere die Zielgruppenvalidierung für Sicherheit + requiredScopes: ['read', 'write'] +})); +``` + + + + +Dadurch wird sichergestellt, dass alle eingehenden Anfragen gemäß den konfigurierten Bearer-Auth-Einstellungen authentifiziert und autorisiert werden und die Auth-Informationen im Request-Kontext verfügbar sind. + +Du kannst die Informationen dann in deiner MCP-Server-Implementierung abrufen: + + + + +```python +@mcp.tool() +async def whoami() -> dict: + # `mcp_auth.auth_info` ist das Kontextobjekt für die aktuelle Anfrage + auth_info = mcp_auth.auth_info + print(f"Authentifizierter Benutzer: {auth_info.subject}") + return {"subject": auth_info.subject} +``` + + + + +```js +// `authInfo` wird aus dem `req.auth`-Objekt übernommen +server.tool('whoami', ({ authInfo }) => { + console.log(`Authentifizierter Benutzer: ${authInfo.subject}`); + return { subject: authInfo.subject }; +}); +``` + + + diff --git a/i18n/de/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx b/i18n/de/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx new file mode 100644 index 0000000..6d77e15 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx @@ -0,0 +1,290 @@ +--- +sidebar_position: 1 +sidebar_label: MCP Auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# MCP Auth im MCP-Server konfigurieren + +Mit der neuesten [MCP-Spezifikation (2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18) agiert dein MCP-Server als **Ressourcenserver**, der Zugangstokens (Zugangstoken (Access token)) validiert, die von externen Autorisierungsservern ausgestellt wurden. + +Um MCP Auth zu konfigurieren, sind zwei Hauptschritte erforderlich: +1. **Autorisierungsserver-Metadaten konfigurieren** – Definiere, welche Autorisierungsserver gültige Tokens für deinen MCP-Server ausstellen dürfen und leite MCP-Clients an, wo sie Zugangstokens (Zugangstoken (Access token)) erhalten können. +2. **Metadaten der geschützten Ressource konfigurieren** – Definiere deinen MCP-Server als geschützte Ressource mit unterstützten Berechtigungen (Scopes). + +## Schritt 1: Autorisierungsserver-Metadaten konfigurieren \{#configure-authorization-server-metadata} + +### Automatisches Abrufen von Metadaten \{#automatic-metadata-fetching} + +Der einfachste Weg, Autorisierungsserver-Metadaten zu konfigurieren, ist die Verwendung der eingebauten Funktionen, die die Metadaten von bekannten URLs abrufen. Wenn dein Anbieter einem der folgenden Standards entspricht: + +- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +Kannst du `fetchServerConfig` verwenden, um die Metadaten automatisch abzurufen, indem du die `issuer`-URL angibst: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +# Autorisierungsserver-Metadaten abrufen +auth_server_config = fetch_server_config( + "https://auth.logto.io/oidc", + AuthServerType.OIDC # oder AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +// Autorisierungsserver-Metadaten abrufen +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); // oder 'oauth' +``` + + + + +Wenn dein Aussteller (Issuer) einen Pfad enthält, unterscheidet sich das Verhalten leicht zwischen OAuth 2.0 und OpenID Connect: + +- **OAuth 2.0**: Die Well-known-URL wird an die **Domain** des Ausstellers angehängt. Zum Beispiel, wenn dein Aussteller `https://my-project.logto.app/oauth` ist, wird die Well-known-URL `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` sein. +- **OpenID Connect**: Die Well-known-URL wird direkt an den **Issuer** angehängt. Zum Beispiel, wenn dein Aussteller `https://my-project.logto.app/oidc` ist, wird die Well-known-URL `https://auth.logto.io/oidc/.well-known/openid-configuration` sein. + +### Weitere Möglichkeiten zur Konfiguration der Autorisierungsserver-Metadaten \{#other-ways} + +#### Eigene Daten-Transpilation \{#custom-data-transpilation} + +In manchen Fällen entsprechen die vom Anbieter zurückgegebenen Metadaten nicht dem erwarteten Format. Wenn du sicher bist, dass der Anbieter konform ist, kannst du die Option `transpile_data` verwenden, um die Metadaten vor der Verwendung zu modifizieren: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +auth_server_config = fetch_server_config( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfig('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +Dies ermöglicht es dir, das Metadatenobjekt zu modifizieren, bevor es von MCP Auth verwendet wird. Du kannst zum Beispiel Felder hinzufügen oder entfernen, deren Werte ändern oder sie in ein anderes Format umwandeln. + +#### Metadaten von einer bestimmten URL abrufen \{#fetch-metadata-from-a-specific-url} + +Wenn dein Anbieter eine spezifische Metadaten-URL statt der Standard-URLs hat, kannst du diese ähnlich verwenden: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC # oder AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfigByWellKnownUrl } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { type: 'oidc' }); // oder 'oauth' +``` + + + + +#### Metadaten von einer bestimmten URL mit eigener Daten-Transpilation abrufen \{#fetch-metadata-from-a-specific-url-with-custom-data-transpilation} + +In manchen Fällen kann die Antwort des Anbieters fehlerhaft oder nicht konform zum erwarteten Metadatenformat sein. Wenn du sicher bist, dass der Anbieter konform ist, kannst du die Metadaten über die Konfigurationsoption transpiliert bereitstellen: + + + + +```python +from mcpauth.config import AuthServerType, fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +#### Metadaten manuell bereitstellen \{#manually-provide-metadata} + +Wenn dein Anbieter kein Metadaten-Abrufen unterstützt, kannst du das Metadatenobjekt manuell bereitstellen: + + + + +```python +from mcpauth.config import AuthServerConfig, AuthServerType, AuthorizationServerMetadata + +auth_server_config = AuthServerConfig( + type=AuthServerType.OIDC, # oder AuthServerType.OAUTH + metadata=AuthorizationServerMetadata( + issuer='', + authorization_endpoint='', + # ... weitere Metadatenfelder + ), +) +``` + + + + +```ts +const authServerConfig = { + metadata: { + issuer: '', + // Metadatenfelder sollten camelCase sein + authorizationEndpoint: '', + // ... weitere Metadatenfelder + }, + type: 'oidc', // oder 'oauth' +}; +``` + + + + +## Schritt 2: Metadaten der geschützten Ressource konfigurieren \{#configure-protected-resource-metadata} + +Nachdem du die Autorisierungsserver-Metadaten konfiguriert hast, musst du MCPAuth als Ressourcenserver initialisieren, indem du die Metadaten deiner geschützten Ressourcen definierst. + +Dieser Schritt folgt der [RFC 9728 (OAuth 2.0 Protected Resource Metadata)](https://datatracker.ietf.org/doc/html/rfc9728) Spezifikation, um deinen MCP-Server als geschützte Ressource zu beschreiben: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import ResourceServerConfig, ResourceServerMetadata + +# Definiere deinen Ressourcen-Identifier +resource_id = "https://api.example.com/notes" + +# Initialisiere MCPAuth im Ressourcenserver-Modus +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], # Verwende die Konfiguration aus Schritt 1 + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth } from 'mcp-auth'; + +// Definiere deinen Ressourcen-Identifier +const resourceIdentifier = 'https://api.example.com/notes'; + +// Initialisiere MCPAuth im Ressourcenserver-Modus +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], // Verwende die Konfiguration aus Schritt 1 + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +Für mehrere Ressourcen kannst du ein Array von geschützten Ressourcen bereitstellen, jeweils mit eigener Metadatenkonfiguration. + +Die oben gezeigte Konfiguration deckt die grundlegende Einrichtung ab. Für weiterführende Metadaten-Parameter siehe [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata). + +## Schritt 3: Endpunkt für die Metadaten der geschützten Ressource bereitstellen \{#mount-the-protected-resource-metadata-endpoint} + +Binde den Router ein, um den Endpunkt für die Metadaten der geschützten Ressource bereitzustellen. Der Endpunktpfad wird automatisch durch den Pfadbestandteil deines Ressourcen-Identifiers bestimmt: + +- **Kein Pfad**: `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **Mit Pfad**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + + + + +```python +from starlette.applications import Starlette +from mcpauth import MCPAuth + +mcp_auth = MCPAuth({/* ... */}) + +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +const mcpAuth = new MCPAuth({/* ... */}); + +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/README.md new file mode 100644 index 0000000..7fca7ea --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/README.md @@ -0,0 +1,59 @@ +--- +sidebar_label: Node.js SDK +--- + +# MCP Auth Node.js SDK Referenz + +## Klassen {#classes} + +- [MCPAuth](/references/js/classes/MCPAuth.md) +- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) +- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) +- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) +- [MCPAuthError](/references/js/classes/MCPAuthError.md) +- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) + +## Typalias {#type-aliases} + +- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) +- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) +- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) +- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) +- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) +- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) +- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) +- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) +- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) +- [AuthServerType](/references/js/type-aliases/AuthServerType.md) +- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) +- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) +- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) +- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) +- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) +- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) +- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) +- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) +- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) +- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) +- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) +- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) + +## Variablen {#variables} + +- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) +- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) +- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) +- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) +- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) +- [defaultValues](/references/js/variables/defaultValues.md) +- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) +- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) +- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) +- [validateServerConfig](/references/js/variables/validateServerConfig.md) + +## Funktionen {#functions} + +- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) +- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) +- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) +- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md new file mode 100644 index 0000000..9cfb817 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md @@ -0,0 +1,300 @@ +--- +sidebar_label: MCPAuth +--- + +# Klasse: MCPAuth + +Die Hauptklasse für die mcp-auth-Bibliothek. Sie fungiert als Factory und Registry zur Erstellung von Authentifizierungsrichtlinien für deine geschützten Ressourcen. + +Sie wird mit deinen Serverkonfigurationen initialisiert und stellt eine `bearerAuth`-Methode bereit, um Express-Middleware für tokenbasierte Authentifizierung zu generieren. + +## Beispiel {#example} + +### Verwendung im `Resource Server`-Modus {#usage-in-resource-server-mode} + +Dies ist der empfohlene Ansatz für neue Anwendungen. + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); + +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +const mcpAuth = new MCPAuth({ + // `protectedResources` kann ein einzelnes Konfigurationsobjekt oder ein Array davon sein. + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); + +// Router für Protected Resource Metadata einbinden +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Einen API-Endpunkt für die konfigurierte Ressource schützen +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, // Gibt an, zu welcher Ressource dieser Endpunkt gehört + audience: resourceIdentifier, // Optional: Überprüfe den 'aud'-Anspruch + requiredScopes: ['read:notes'], + }), + (req, res) => { + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); +``` + +### Legacy-Verwendung im `Authorization Server`-Modus (Veraltet) {#legacy-usage-in-authorization-server-mode-deprecated} + +Dieser Ansatz wird aus Gründen der Abwärtskompatibilität unterstützt. + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + server: await fetchServerConfig( + 'https://auth.logto.io/oidc', + { type: 'oidc' } + ), +}); + +// Router für Legacy Authorization Server Metadata einbinden +app.use(mcpAuth.delegatedRouter()); + +// Einen Endpunkt mit der Standardrichtlinie schützen +app.get( + '/mcp', + mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), + (req, res) => { + console.log('Auth info:', req.auth); + // Bearbeite hier die MCP-Anfrage + }, +); +``` + +## Konstruktoren {#constructors} + +### Konstruktor {#constructor} + +```ts +new MCPAuth(config: MCPAuthConfig): MCPAuth; +``` + +Erstellt eine Instanz von MCPAuth. +Die gesamte Konfiguration wird im Voraus validiert, um Fehler frühzeitig zu erkennen. + +#### Parameter {#parameters} + +##### config {#config} + +[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) + +Die Authentifizierungskonfiguration. + +#### Rückgabewert {#returns} + +`MCPAuth` + +## Eigenschaften {#properties} + +### config {#config} + +```ts +readonly config: MCPAuthConfig; +``` + +Die Authentifizierungskonfiguration. + +## Methoden {#methods} + +### bearerAuth() {#bearerauth} + +#### Aufrufsignatur {#call-signature} + +```ts +bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; +``` + +Erstellt einen Bearer-Auth-Handler (Express-Middleware), der das Zugangstoken (Access token) im +`Authorization`-Header der Anfrage überprüft. + +##### Parameter {#parameters} + +###### verifyAccessToken {#verifyaccesstoken} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +Eine Funktion, die das Zugangstoken (Access token) überprüft. Sie sollte das +Zugangstoken als String akzeptieren und ein Promise (oder einen Wert) zurückgeben, das/die das +Überprüfungsergebnis liefert. + +**Siehe** + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) für die Typdefinition der +`verifyAccessToken`-Funktion. + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> + +Optionale Konfiguration für den Bearer-Auth-Handler. + +**Siehe** + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) für die verfügbaren Konfigurationsoptionen (außer +`verifyAccessToken` und `issuer`). + +##### Rückgabewert {#returns} + +`RequestHandler` + +Eine Express-Middleware-Funktion, die das Zugangstoken (Access token) überprüft und das +Überprüfungsergebnis dem Request-Objekt (`req.auth`) hinzufügt. + +##### Siehe {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) für Details zur Implementierung und die erweiterten Typen des +`req.auth` (`AuthInfo`)-Objekts. + +#### Aufrufsignatur {#call-signature} + +```ts +bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; +``` + +Erstellt einen Bearer-Auth-Handler (Express-Middleware), der das Zugangstoken (Access token) im +`Authorization`-Header der Anfrage mit einem vordefinierten Verifizierungsmodus überprüft. + +Im `'jwt'`-Modus erstellt der Handler eine JWT-Überprüfungsfunktion unter Verwendung des JWK-Sets +von der JWKS-URI des Autorisierungsservers. + +##### Parameter {#parameters} + +###### mode {#mode} + +`"jwt"` + +Der Verifizierungsmodus für das Zugangstoken (Access token). Aktuell wird nur 'jwt' unterstützt. + +**Siehe** + +[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) für die verfügbaren Modi. + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` + +Optionale Konfiguration für den Bearer-Auth-Handler, einschließlich JWT-Überprüfungsoptionen und +Remote-JWK-Set-Optionen. + +**Siehe** + + - VerifyJwtConfig für die verfügbaren Konfigurationsoptionen für die JWT- +Überprüfung. + - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) für die verfügbaren Konfigurationsoptionen (außer +`verifyAccessToken` und `issuer`). + +##### Rückgabewert {#returns} + +`RequestHandler` + +Eine Express-Middleware-Funktion, die das Zugangstoken (Access token) überprüft und das +Überprüfungsergebnis dem Request-Objekt (`req.auth`) hinzufügt. + +##### Siehe {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) für Details zur Implementierung und die erweiterten Typen des +`req.auth` (`AuthInfo`)-Objekts. + +##### Fehler {#throws} + +wenn die JWKS-URI nicht in den Server-Metadaten angegeben ist, wenn +der `'jwt'`-Modus verwendet wird. + +*** + +### ~~delegatedRouter()~~ {#delegatedrouter} + +```ts +delegatedRouter(): Router; +``` + +Erstellt einen Delegated Router zum Bereitstellen des veralteten OAuth 2.0 Authorization Server Metadata Endpunkts +(`/.well-known/oauth-authorization-server`) mit den der Instanz bereitgestellten Metadaten. + +#### Rückgabewert {#returns} + +`Router` + +Ein Router, der den OAuth 2.0 Authorization Server Metadata Endpunkt mit den +bereitgestellten Metadaten der Instanz bedient. + +#### Veraltet {#deprecated} + +Verwende stattdessen [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter). + +#### Beispiel {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth: MCPAuth; // Angenommen, dies ist initialisiert +app.use(mcpAuth.delegatedRouter()); +``` + +#### Fehler {#throws} + +Wenn im `Resource Server`-Modus aufgerufen. + +*** + +### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} + +```ts +protectedResourceMetadataRouter(): Router; +``` + +Erstellt einen Router, der den OAuth 2.0 Protected Resource Metadata Endpunkt +für alle konfigurierten Ressourcen bereitstellt. + +Dieser Router erstellt automatisch die korrekten `.well-known`-Endpunkte für jede +Ressourcenkennung, die in deiner Konfiguration angegeben ist. + +#### Rückgabewert {#returns} + +`Router` + +Ein Router, der den OAuth 2.0 Protected Resource Metadata Endpunkt bereitstellt. + +#### Fehler {#throws} + +Wenn im `Authorization Server`-Modus aufgerufen. + +#### Beispiel {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +// Angenommen, mcpAuth ist mit einer oder mehreren `protectedResources`-Konfigurationen initialisiert +const mcpAuth: MCPAuth; +const app = express(); + +// Dies stellt Metadaten unter `/.well-known/oauth-protected-resource/...` bereit +// basierend auf deinen Ressourcenkennungen. +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md new file mode 100644 index 0000000..5ae6512 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthAuthServerError +--- + +# Klasse: MCPAuthAuthServerError + +Fehler, der ausgelöst wird, wenn ein Problem mit dem entfernten Autorisierungsserver auftritt. + +## Erbt von {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Konstruktoren {#constructors} + +### Konstruktor {#constructor} + +```ts +new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; +``` + +#### Parameter {#parameters} + +##### code {#code} + +[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### Rückgabewert {#returns} + +`MCPAuthAuthServerError` + +#### Überschreibt {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Eigenschaften {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: AuthServerErrorCode; +``` + +Der Fehlercode im snake_case-Format. + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthAuthServerError'; +``` + +#### Überschreibt {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +Die Eigenschaft `Error.stackTraceLimit` gibt die Anzahl der Stack-Frames an, +die von einem Stack-Trace gesammelt werden (egal ob durch `new Error().stack` oder +`Error.captureStackTrace(obj)` erzeugt). + +Der Standardwert ist `10`, kann aber auf jede gültige JavaScript-Zahl gesetzt werden. Änderungen +wirken sich auf jeden Stack-Trace aus, der _nachdem_ der Wert geändert wurde, erfasst wird. + +Wenn ein ungültiger Wert oder eine negative Zahl gesetzt wird, werden keine Stack-Frames +im Stack-Trace erfasst. + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Methoden {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. + +#### Parameter {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Gibt an, ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. +Standardmäßig `false`. + +#### Rückgabewert {#returns} + +`Record`\<`string`, `unknown`\> + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Erstellt eine `.stack`-Eigenschaft auf `targetObject`, die beim Zugriff +einen String zurückgibt, der den Ort im Code repräsentiert, an dem +`Error.captureStackTrace()` aufgerufen wurde. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Ähnlich wie `new Error().stack` +``` + +Die erste Zeile des Traces wird mit +`${myObject.name}: ${myObject.message}` vorangestellt. + +Das optionale Argument `constructorOpt` akzeptiert eine Funktion. Wenn angegeben, werden alle Frames +oberhalb von `constructorOpt`, einschließlich `constructorOpt`, aus dem +generierten Stack-Trace ausgelassen. + +Das Argument `constructorOpt` ist nützlich, um Implementierungsdetails +der Fehlererzeugung vor dem Benutzer zu verbergen. Zum Beispiel: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Erzeuge einen Fehler ohne Stack-Trace, um die Berechnung des Stack-Traces zweimal zu vermeiden. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Erfasse den Stack-Trace oberhalb der Funktion b + Error.captureStackTrace(error, b); // Weder Funktion c noch b sind im Stack-Trace enthalten + throw error; +} + +a(); +``` + +#### Parameter {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Rückgabewert {#returns} + +`void` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parameter {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Rückgabewert {#returns} + +`any` + +#### Siehe {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md new file mode 100644 index 0000000..8bcaa4e --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthBearerAuthError +--- + +# Klasse: MCPAuthBearerAuthError + +Fehler, der ausgelöst wird, wenn es ein Problem bei der Authentifizierung mit Bearer-Tokens gibt. + +## Erbt von {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Konstruktoren {#constructors} + +### Konstruktor {#constructor} + +```ts +new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; +``` + +#### Parameter {#parameters} + +##### code {#code} + +[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) + +##### cause? {#cause} + +[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) + +#### Rückgabewert {#returns} + +`MCPAuthBearerAuthError` + +#### Überschreibt {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Eigenschaften {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: MCPAuthBearerAuthErrorDetails; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: BearerAuthErrorCode; +``` + +Der Fehlercode im snake_case-Format. + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthBearerAuthError'; +``` + +#### Überschreibt {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +Die Eigenschaft `Error.stackTraceLimit` gibt die Anzahl der Stack-Frames an, +die von einem Stack-Trace gesammelt werden (egal ob durch `new Error().stack` oder +`Error.captureStackTrace(obj)` erzeugt). + +Der Standardwert ist `10`, kann aber auf jede gültige JavaScript-Zahl gesetzt werden. Änderungen +wirken sich auf jeden Stack-Trace aus, der _nachdem_ der Wert geändert wurde, erfasst wird. + +Wenn ein ungültiger Wert oder eine negative Zahl gesetzt wird, werden keine Stack-Frames +erfasst. + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Methoden {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. + +#### Parameter {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Gibt an, ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. +Standard ist `false`. + +#### Rückgabewert {#returns} + +`Record`\<`string`, `unknown`\> + +#### Überschreibt {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Erstellt eine `.stack`-Eigenschaft auf `targetObject`, die beim Zugriff +einen String zurückgibt, der den Ort im Code darstellt, an dem +`Error.captureStackTrace()` aufgerufen wurde. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Ähnlich wie `new Error().stack` +``` + +Die erste Zeile des Traces wird mit +`${myObject.name}: ${myObject.message}` vorangestellt. + +Das optionale Argument `constructorOpt` akzeptiert eine Funktion. Falls angegeben, werden alle Frames +oberhalb von `constructorOpt`, einschließlich `constructorOpt`, aus dem +generierten Stack-Trace ausgelassen. + +Das Argument `constructorOpt` ist nützlich, um Implementierungsdetails +der Fehlererzeugung vor dem Benutzer zu verbergen. Zum Beispiel: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Erzeuge einen Fehler ohne Stack-Trace, um die Berechnung des Stack-Traces zweimal zu vermeiden. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Erfasse den Stack-Trace oberhalb der Funktion b + Error.captureStackTrace(error, b); // Weder Funktion c noch b sind im Stack-Trace enthalten + throw error; +} + +a(); +``` + +#### Parameter {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Rückgabewert {#returns} + +`void` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parameter {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Rückgabewert {#returns} + +`any` + +#### Siehe {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md new file mode 100644 index 0000000..7a8480f --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md @@ -0,0 +1,243 @@ +--- +sidebar_label: MCPAuthConfigError +--- + +# Klasse: MCPAuthConfigError + +Fehler, der ausgelöst wird, wenn es ein Konfigurationsproblem mit mcp-auth gibt. + +## Erbt von {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Konstruktoren {#constructors} + +### Konstruktor {#constructor} + +```ts +new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; +``` + +#### Parameter {#parameters} + +##### code {#code} + +`string` + +Der Fehlercode im snake_case-Format. + +##### message {#message} + +`string` + +Eine menschenlesbare Beschreibung des Fehlers. + +#### Rückgabe {#returns} + +`MCPAuthConfigError` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Eigenschaften {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +Der Fehlercode im snake_case-Format. + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthConfigError'; +``` + +#### Überschreibt {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +Die Eigenschaft `Error.stackTraceLimit` gibt die Anzahl der Stack-Frames an, die von einem Stack-Trace gesammelt werden (egal ob durch `new Error().stack` oder `Error.captureStackTrace(obj)` erzeugt). + +Der Standardwert ist `10`, kann aber auf jede gültige JavaScript-Zahl gesetzt werden. Änderungen wirken sich auf alle Stack-Traces aus, die _nach_ der Änderung des Wertes erfasst werden. + +Wenn ein ungültiger Wert (kein Zahlwert) oder ein negativer Wert gesetzt wird, werden keine Stack-Frames erfasst. + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Methoden {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. + +#### Parameter {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. +Standard ist `false`. + +#### Rückgabe {#returns} + +`Record`\<`string`, `unknown`\> + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Erstellt eine `.stack`-Eigenschaft auf `targetObject`, die beim Zugriff einen String zurückgibt, der den Ort im Code darstellt, an dem `Error.captureStackTrace()` aufgerufen wurde. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Ähnlich wie `new Error().stack` +``` + +Die erste Zeile des Traces wird mit +`${myObject.name}: ${myObject.message}` vorangestellt. + +Das optionale Argument `constructorOpt` akzeptiert eine Funktion. Wenn angegeben, werden alle Frames oberhalb von `constructorOpt`, einschließlich `constructorOpt`, aus dem generierten Stack-Trace ausgelassen. + +Das Argument `constructorOpt` ist nützlich, um Implementierungsdetails der Fehlererzeugung vor dem Benutzer zu verbergen. Zum Beispiel: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Erzeuge einen Fehler ohne Stack-Trace, um die Berechnung des Stack-Traces zweimal zu vermeiden. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Erfasse den Stack-Trace oberhalb der Funktion b + Error.captureStackTrace(error, b); // Weder Funktion c noch b sind im Stack-Trace enthalten + throw error; +} + +a(); +``` + +#### Parameter {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Rückgabe {#returns} + +`void` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parameter {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Rückgabe {#returns} + +`any` + +#### Siehe {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md new file mode 100644 index 0000000..4b64268 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md @@ -0,0 +1,267 @@ +--- +sidebar_label: MCPAuthError +--- + +# Klasse: MCPAuthError + +Basisklasse für alle mcp-auth Fehler. + +Sie bietet eine standardisierte Möglichkeit, Fehler im Zusammenhang mit MCP Authentifizierung (Authentication) und Autorisierung (Authorization) zu behandeln. + +## Erweitert {#extends} + +- `Error` + +## Erweitert von {#extended-by} + +- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) +- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) +- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) +- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) + +## Konstruktoren {#constructors} + +### Konstruktor {#constructor} + +```ts +new MCPAuthError(code: string, message: string): MCPAuthError; +``` + +#### Parameter {#parameters} + +##### code {#code} + +`string` + +Der Fehlercode im snake_case-Format. + +##### message {#message} + +`string` + +Eine menschenlesbare Beschreibung des Fehlers. + +#### Rückgabe {#returns} + +`MCPAuthError` + +#### Überschreibt {#overrides} + +```ts +Error.constructor +``` + +## Eigenschaften {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### Geerbt von {#inherited-from} + +```ts +Error.cause +``` + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +Der Fehlercode im snake_case-Format. + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Geerbt von {#inherited-from} + +```ts +Error.message +``` + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthError'; +``` + +#### Überschreibt {#overrides} + +```ts +Error.name +``` + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Geerbt von {#inherited-from} + +```ts +Error.stack +``` + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +Die Eigenschaft `Error.stackTraceLimit` gibt die Anzahl der Stack-Frames an, +die von einem Stack-Trace gesammelt werden (egal ob durch `new Error().stack` oder +`Error.captureStackTrace(obj)` erzeugt). + +Der Standardwert ist `10`, kann aber auf jede gültige JavaScript-Zahl gesetzt werden. Änderungen +wirken sich auf alle Stack-Traces aus, die _nachdem_ der Wert geändert wurde, erfasst werden. + +Wenn auf einen Nicht-Zahlenwert oder auf eine negative Zahl gesetzt, werden keine Frames +im Stack-Trace erfasst. + +#### Geerbt von {#inherited-from} + +```ts +Error.stackTraceLimit +``` + +## Methoden {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. + +#### Parameter {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. +Standardmäßig `false`. + +#### Rückgabe {#returns} + +`Record`\<`string`, `unknown`\> + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Erstellt eine `.stack`-Eigenschaft auf `targetObject`, die beim Zugriff +einen String zurückgibt, der den Ort im Code repräsentiert, an dem +`Error.captureStackTrace()` aufgerufen wurde. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Ähnlich wie `new Error().stack` +``` + +Die erste Zeile des Traces wird mit +`${myObject.name}: ${myObject.message}` vorangestellt. + +Das optionale Argument `constructorOpt` akzeptiert eine Funktion. Falls angegeben, werden alle Frames +oberhalb von `constructorOpt`, einschließlich `constructorOpt`, aus dem generierten Stack-Trace entfernt. + +Das Argument `constructorOpt` ist nützlich, um Implementierungsdetails der Fehlererzeugung vor dem Benutzer zu verbergen. Zum Beispiel: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Erzeuge einen Fehler ohne Stack-Trace, um die Berechnung des Stack-Traces zweimal zu vermeiden. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Erfasse den Stack-Trace oberhalb der Funktion b + Error.captureStackTrace(error, b); // Weder Funktion c noch b sind im Stack-Trace enthalten + throw error; +} + +a(); +``` + +#### Parameter {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Rückgabe {#returns} + +`void` + +#### Geerbt von {#inherited-from} + +```ts +Error.captureStackTrace +``` + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parameter {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Rückgabe {#returns} + +`any` + +#### Siehe {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Geerbt von {#inherited-from} + +```ts +Error.prepareStackTrace +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md new file mode 100644 index 0000000..c715dfd --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md @@ -0,0 +1,239 @@ +--- +sidebar_label: MCPAuthTokenVerificationError +--- + +# Klasse: MCPAuthTokenVerificationError + +Fehler, der ausgelöst wird, wenn beim Überprüfen von Tokens ein Problem auftritt. + +## Erbt von {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Konstruktoren {#constructors} + +### Konstruktor {#constructor} + +```ts +new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; +``` + +#### Parameter {#parameters} + +##### code {#code} + +[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### Rückgabewert {#returns} + +`MCPAuthTokenVerificationError` + +#### Überschreibt {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Eigenschaften {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: MCPAuthTokenVerificationErrorCode; +``` + +Der Fehlercode im snake_case-Format. + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthTokenVerificationError'; +``` + +#### Überschreibt {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +Die Eigenschaft `Error.stackTraceLimit` gibt die Anzahl der Stack-Frames an, die von einem Stack-Trace gesammelt werden (egal ob durch `new Error().stack` oder `Error.captureStackTrace(obj)` generiert). + +Der Standardwert ist `10`, kann aber auf jede gültige JavaScript-Zahl gesetzt werden. Änderungen wirken sich auf alle Stack-Traces aus, die _nachdem_ der Wert geändert wurde, erfasst werden. + +Wenn ein ungültiger Wert (kein Zahlwert oder negativ) gesetzt wird, werden keine Stack-Frames erfasst. + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Methoden {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. + +#### Parameter {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Legt fest, ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. +Standard ist `false`. + +#### Rückgabewert {#returns} + +`Record`\<`string`, `unknown`\> + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Erstellt eine `.stack`-Eigenschaft auf `targetObject`, die beim Zugriff einen String zurückgibt, der den Ort im Code darstellt, an dem `Error.captureStackTrace()` aufgerufen wurde. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Ähnlich wie `new Error().stack` +``` + +Die erste Zeile des Traces wird mit +`${myObject.name}: ${myObject.message}` vorangestellt. + +Das optionale Argument `constructorOpt` akzeptiert eine Funktion. Falls angegeben, werden alle Frames oberhalb von `constructorOpt`, einschließlich `constructorOpt`, aus dem generierten Stack-Trace ausgelassen. + +Das Argument `constructorOpt` ist nützlich, um Implementierungsdetails der Fehlererzeugung vor dem Benutzer zu verbergen. Zum Beispiel: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Erzeuge einen Fehler ohne Stack-Trace, um die Berechnung des Stack-Traces doppelt zu vermeiden. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Erfasse den Stack-Trace oberhalb der Funktion b + Error.captureStackTrace(error, b); // Weder Funktion c noch b sind im Stack-Trace enthalten + throw error; +} + +a(); +``` + +#### Parameter {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Rückgabewert {#returns} + +`void` + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parameter {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Rückgabewert {#returns} + +`any` + +#### Siehe {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Geerbt von {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md new file mode 100644 index 0000000..c7c2e96 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md @@ -0,0 +1,43 @@ +--- +sidebar_label: createVerifyJwt +--- + +# Funktion: createVerifyJwt() + +```ts +function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; +``` + +Erstellt eine Funktion zur Überprüfung von JWT-Zugangstokens (Access tokens), indem die bereitgestellte Schlüsselabruffunktion und Optionen verwendet werden. + +## Parameter {#parameters} + +### getKey {#getkey} + +`JWTVerifyGetKey` + +Die Funktion zum Abrufen des Schlüssels, der zur Überprüfung des JWT verwendet wird. + +**Siehe** + +JWTVerifyGetKey für die Typdefinition der Schlüsselabruf-Funktion. + +### options? {#options} + +`JWTVerifyOptions` + +Optionale Optionen zur JWT-Überprüfung. + +**Siehe** + +JWTVerifyOptions für die Typdefinition der Optionen. + +## Rückgabewert {#returns} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +Eine Funktion, die JWT-Zugangstokens (Access tokens) überprüft und ein AuthInfo-Objekt zurückgibt, wenn das Token gültig ist. Das JWT muss die Felder `iss`, `client_id` und `sub` im Payload enthalten und kann optional die Felder `scope` oder `scopes` enthalten. Die Funktion verwendet intern die `jose`-Bibliothek, um die JWT-Überprüfung durchzuführen. + +## Siehe {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) für die Typdefinition der zurückgegebenen Funktion. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md new file mode 100644 index 0000000..aff6d93 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md @@ -0,0 +1,60 @@ +--- +sidebar_label: fetchServerConfig +--- + +# Funktion: fetchServerConfig() + +```ts +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +``` + +Ruft die Serverkonfiguration entsprechend dem Aussteller (Issuer) und dem Typ des Autorisierungsservers ab. + +Diese Funktion bestimmt automatisch die Well-Known-URL basierend auf dem Servertyp, da OAuth- und OpenID Connect-Server unterschiedliche Konventionen für ihre Metadatenendpunkte haben. + +## Parameter {#parameters} + +### issuer {#issuer} + +`string` + +Die Aussteller-URL (Issuer) des Autorisierungsservers. + +### config {#config} + +`ServerMetadataConfig` + +Das Konfigurationsobjekt, das den Servertyp und eine optionale Transpilierungsfunktion enthält. + +## Rückgabewert {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +Ein Promise, das mit der Serverkonfiguration aufgelöst wird. + +## Siehe auch {#see} + + - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) für die zugrundeliegende Implementierung. + - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) für die OAuth 2.0 Authorization Server Metadata Spezifikation. + - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) für die OpenID Connect Discovery Spezifikation. + +## Beispiel {#example} + +```ts +import { fetchServerConfig } from 'mcp-auth'; +// Abrufen der OAuth-Serverkonfiguration +// Dies ruft die Metadaten von `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` ab +const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); + +// Abrufen der OpenID Connect-Serverkonfiguration +// Dies ruft die Metadaten von `https://auth.logto.io/oidc/.well-known/openid-configuration` ab +const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); +``` + +## Fehlerauslösung {#throws} + +wenn der Abrufvorgang fehlschlägt. + +## Fehlerauslösung {#throws} + +wenn die Servermetadaten ungültig sind oder nicht der MCP-Spezifikation entsprechen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md new file mode 100644 index 0000000..0191ecc --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md @@ -0,0 +1,41 @@ +--- +sidebar_label: fetchServerConfigByWellKnownUrl +--- + +# Funktion: fetchServerConfigByWellKnownUrl() + +```ts +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +``` + +Ruft die Serverkonfiguration von der angegebenen Well-Known-URL ab und validiert sie gegen die MCP-Spezifikation. + +Wenn die Server-Metadaten nicht dem erwarteten Schema entsprechen, du dir aber sicher bist, dass sie kompatibel sind, kannst du eine `transpileData`-Funktion definieren, um die Metadaten in das erwartete Format zu transformieren. + +## Parameter {#parameters} + +### wellKnownUrl {#wellknownurl} + +Die Well-Known-URL, von der die Serverkonfiguration abgerufen werden soll. Dies kann ein String oder ein URL-Objekt sein. + +`string` | `URL` + +### config {#config} + +`ServerMetadataConfig` + +Das Konfigurationsobjekt, das den Servertyp und eine optionale Transpile-Funktion enthält. + +## Rückgabewert {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +Ein Promise, das mit der Serverkonfiguration aufgelöst wird. + +## Löst aus {#throws} + +wenn der Abrufvorgang fehlschlägt. + +## Löst aus {#throws} + +wenn die Server-Metadaten ungültig sind oder nicht der MCP-Spezifikation entsprechen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md new file mode 100644 index 0000000..c6cd79b --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md @@ -0,0 +1,38 @@ +--- +sidebar_label: handleBearerAuth +--- + +# Funktion: handleBearerAuth() + +```ts +function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; +``` + +Erstellt eine Middleware-Funktion zur Behandlung von Bearer-Authentifizierung in einer Express-Anwendung. + +Diese Middleware extrahiert das Bearer-Token aus dem `Authorization`-Header, überprüft es mit der bereitgestellten Funktion `verifyAccessToken` und prüft den Aussteller (Issuer), die Zielgruppe (Audience) und die erforderlichen Berechtigungen (Scopes). + +- Wenn das Token gültig ist, werden die Authentifizierungsinformationen im Feld `request.auth` hinzugefügt; andernfalls wird mit einer entsprechenden Fehlermeldung geantwortet. +- Wenn die Überprüfung des Zugangstokens (Access token) fehlschlägt, wird mit einem 401 Unauthorized-Fehler geantwortet. +- Wenn das Token nicht über die erforderlichen Berechtigungen (Scopes) verfügt, wird mit einem 403 Forbidden-Fehler geantwortet. +- Wenn unerwartete Fehler während des Authentifizierungsprozesses auftreten, werden diese von der Middleware erneut ausgelöst. + +**Hinweis:** Das Objekt `request.auth` enthält erweiterte Felder im Vergleich zur Standard-AuthInfo-Schnittstelle, die im Modul `@modelcontextprotocol/sdk` definiert ist. Siehe die erweiterte Schnittstelle in dieser Datei für Details. + +## Parameter {#parameters} + +### param0 {#param0} + +[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) + +Konfiguration für den Bearer-Authentifizierungs-Handler. + +## Rückgabewert {#returns} + +`RequestHandler` + +Eine Middleware-Funktion für Express, die Bearer-Authentifizierung behandelt. + +## Siehe auch {#see} + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) für die Konfigurationsoptionen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md new file mode 100644 index 0000000..50782b9 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md @@ -0,0 +1,49 @@ +--- +sidebar_label: AuthServerConfig +--- + +# Typalias: AuthServerConfig + +```ts +type AuthServerConfig = { + metadata: CamelCaseAuthorizationServerMetadata; + type: AuthServerType; +}; +``` + +Konfiguration für den entfernten Autorisierungsserver, der mit dem MCP-Server integriert ist. + +## Eigenschaften {#properties} + +### metadata {#metadata} + +```ts +metadata: CamelCaseAuthorizationServerMetadata; +``` + +Die Metadaten des Autorisierungsservers (authorization server), die der MCP-Spezifikation entsprechen sollten +(basierend auf OAuth 2.0 Authorization Server Metadata). + +Diese Metadaten werden typischerweise vom Well-known-Endpunkt des Servers abgerufen (OAuth 2.0 +Authorization Server Metadata oder OpenID Connect Discovery); sie können auch direkt in der Konfiguration bereitgestellt werden, falls der Server solche Endpunkte nicht unterstützt. + +**Hinweis:** Die Metadaten sollten im camelCase-Format vorliegen, wie von der mcp-auth-Bibliothek bevorzugt. + +#### Siehe {#see} + + - [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) + - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +*** + +### type {#type} + +```ts +type: AuthServerType; +``` + +Der Typ des Autorisierungsservers (authorization server). + +#### Siehe {#see} + +[AuthServerType](/references/js/type-aliases/AuthServerType.md) für die möglichen Werte. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md new file mode 100644 index 0000000..23fbbdd --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md @@ -0,0 +1,45 @@ +--- +sidebar_label: AuthServerConfigError +--- + +# Typalias: AuthServerConfigError + +```ts +type AuthServerConfigError = { + cause?: Error; + code: AuthServerConfigErrorCode; + description: string; +}; +``` + +Repräsentiert einen Fehler, der während der Validierung der Metadaten des Autorisierungsservers auftritt. + +## Eigenschaften {#properties} + +### cause? {#cause} + +```ts +optional cause: Error; +``` + +Eine optionale Ursache des Fehlers, typischerweise eine Instanz von `Error`, die mehr Kontext liefert. + +*** + +### code {#code} + +```ts +code: AuthServerConfigErrorCode; +``` + +Der Code, der den spezifischen Validierungsfehler repräsentiert. + +*** + +### description {#description} + +```ts +description: string; +``` + +Eine menschenlesbare Beschreibung des Fehlers. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md new file mode 100644 index 0000000..e942349 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: AuthServerConfigErrorCode +--- + +# Typalias: AuthServerConfigErrorCode + +```ts +type AuthServerConfigErrorCode = + | "invalid_server_metadata" + | "code_response_type_not_supported" + | "authorization_code_grant_not_supported" + | "pkce_not_supported" + | "s256_code_challenge_method_not_supported"; +``` + +Die Codes für Fehler, die beim Validieren der Metadaten des Autorisierungsservers auftreten können. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md new file mode 100644 index 0000000..4c7fa60 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md @@ -0,0 +1,34 @@ +--- +sidebar_label: AuthServerConfigWarning +--- + +# Typalias: AuthServerConfigWarning + +```ts +type AuthServerConfigWarning = { + code: AuthServerConfigWarningCode; + description: string; +}; +``` + +Stellt eine Warnung dar, die während der Validierung der Metadaten des Autorisierungsservers auftritt. + +## Eigenschaften {#properties} + +### code {#code} + +```ts +code: AuthServerConfigWarningCode; +``` + +Der Code, der die spezifische Validierungswarnung repräsentiert. + +*** + +### description {#description} + +```ts +description: string; +``` + +Eine für Menschen lesbare Beschreibung der Warnung. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md new file mode 100644 index 0000000..d6aca4c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerConfigWarningCode +--- + +# Typalias: AuthServerConfigWarningCode + +```ts +type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; +``` + +Die Codes für Warnungen, die beim Validieren der Metadaten des Autorisierungsservers auftreten können. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md new file mode 100644 index 0000000..fe86fa0 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md @@ -0,0 +1,12 @@ +--- +sidebar_label: AuthServerErrorCode +--- + +# Typalias: AuthServerErrorCode + +```ts +type AuthServerErrorCode = + | "invalid_server_metadata" + | "invalid_server_config" + | "missing_jwks_uri"; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md new file mode 100644 index 0000000..6950046 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md @@ -0,0 +1,31 @@ +--- +sidebar_label: AuthServerModeConfig +--- + +# Typalias: ~~AuthServerModeConfig~~ + +```ts +type AuthServerModeConfig = { + server: AuthServerConfig; +}; +``` + +Konfiguration für den veralteten MCP-Server im Autorisierungsserver-Modus. + +## Veraltet {#deprecated} + +Verwende stattdessen die `ResourceServerModeConfig`-Konfiguration. + +## Eigenschaften {#properties} + +### ~~server~~ {#server} + +```ts +server: AuthServerConfig; +``` + +Die einzelne Autorisierungsserver-Konfiguration. + +#### Veraltet {#deprecated} + +Verwende stattdessen die `protectedResources`-Konfiguration. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md new file mode 100644 index 0000000..e20bee1 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md @@ -0,0 +1,17 @@ +--- +sidebar_label: AuthServerSuccessCode +--- + +# Typalias: AuthServerSuccessCode + +```ts +type AuthServerSuccessCode = + | "server_metadata_valid" + | "dynamic_registration_supported" + | "pkce_supported" + | "s256_code_challenge_method_supported" + | "authorization_code_grant_supported" + | "code_response_type_supported"; +``` + +Die Codes für die erfolgreiche Validierung der Metadaten des Autorisierungsservers (authorization server metadata). \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md new file mode 100644 index 0000000..0c9692c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerType +--- + +# Typalias: AuthServerType + +```ts +type AuthServerType = "oauth" | "oidc"; +``` + +Der Typ des Autorisierungsservers. Diese Information sollte durch die Serverkonfiguration bereitgestellt werden und gibt an, ob der Server ein OAuth 2.0- oder OpenID Connect (OIDC)-Autorisierungsserver ist. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md new file mode 100644 index 0000000..3d9694d --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md @@ -0,0 +1,236 @@ +--- +sidebar_label: AuthorizationServerMetadata +--- + +# Typalias: AuthorizationServerMetadata + +```ts +type AuthorizationServerMetadata = { + authorization_endpoint: string; + code_challenge_methods_supported?: string[]; + grant_types_supported?: string[]; + introspection_endpoint?: string; + introspection_endpoint_auth_methods_supported?: string[]; + introspection_endpoint_auth_signing_alg_values_supported?: string[]; + issuer: string; + jwks_uri?: string; + op_policy_uri?: string; + op_tos_uri?: string; + registration_endpoint?: string; + response_modes_supported?: string[]; + response_types_supported: string[]; + revocation_endpoint?: string; + revocation_endpoint_auth_methods_supported?: string[]; + revocation_endpoint_auth_signing_alg_values_supported?: string[]; + scopes_supported?: string[]; + service_documentation?: string; + token_endpoint: string; + token_endpoint_auth_methods_supported?: string[]; + token_endpoint_auth_signing_alg_values_supported?: string[]; + ui_locales_supported?: string[]; + userinfo_endpoint?: string; +}; +``` + +Schema für OAuth 2.0 Authorization Server Metadata wie in RFC 8414 definiert. + +## Typdeklaration {#type-declaration} + +### authorization\_endpoint {#authorization-endpoint} + +```ts +authorization_endpoint: string; +``` + +URL des Authorization Servers für den Authorization Endpoint [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. +Dies ist ERFORDERLICH, es sei denn, es werden keine Grant Types unterstützt, die den Authorization Endpoint verwenden. + +#### Siehe {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.1 + +### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} + +```ts +optional code_challenge_methods_supported: string[]; +``` + +JSON-Array mit einer Liste der Proof Key for Code Exchange (PKCE) +[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] Code-Challenge-Methoden, die von diesem Authorization Server unterstützt werden. + +### grant\_types\_supported? {#grant-types-supported} + +```ts +optional grant_types_supported: string[]; +``` + +JSON-Array mit einer Liste der OAuth 2.0 Grant Type-Werte, die dieser Authorization Server unterstützt. +Die Array-Werte entsprechen denen, die mit dem `grant_types`-Parameter verwendet werden, +wie im "OAuth 2.0 Dynamic Client Registration Protocol" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] definiert. +Wenn weggelassen, ist der Standardwert `["authorization_code", "implicit"]`. + +### introspection\_endpoint? {#introspection-endpoint} + +```ts +optional introspection_endpoint: string; +``` + +URL des OAuth 2.0 Introspection Endpoints des Authorization Servers +[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. + +### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} + +```ts +optional introspection_endpoint_auth_methods_supported: string[]; +``` + +### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} + +```ts +optional introspection_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +Der Issuer-Identifier (Aussteller) des Authorization Servers, eine URL, die das `https`-Schema verwendet und +keine Query- oder Fragment-Komponenten enthält. + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +URL des JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] +Dokuments des Authorization Servers. Das referenzierte Dokument enthält die Signaturschlüssel, die der Client verwendet, +um Signaturen des Authorization Servers zu validieren. Diese URL MUSS das `https`-Schema verwenden. + +### op\_policy\_uri? {#op-policy-uri} + +```ts +optional op_policy_uri: string; +``` + +### op\_tos\_uri? {#op-tos-uri} + +```ts +optional op_tos_uri: string; +``` + +### registration\_endpoint? {#registration-endpoint} + +```ts +optional registration_endpoint: string; +``` + +URL des OAuth 2.0 Dynamic Client Registration Endpoints des Authorization Servers +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. + +### response\_modes\_supported? {#response-modes-supported} + +```ts +optional response_modes_supported: string[]; +``` + +JSON-Array mit einer Liste der OAuth 2.0 `response_mode`-Werte, die dieser Authorization Server unterstützt, +wie in "OAuth 2.0 Multiple Response Type Encoding Practices" spezifiziert +[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]. + +Wenn weggelassen, ist der Standardwert `["query", "fragment"]`. Der Response Mode-Wert `"form_post"` ist +ebenfalls in "OAuth 2.0 Form Post Response Mode" definiert +[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]. + +### response\_types\_supported {#response-types-supported} + +```ts +response_types_supported: string[]; +``` + +JSON-Array mit einer Liste der OAuth 2.0 `response_type`-Werte, die dieser Authorization Server unterstützt. +Die Array-Werte entsprechen denen, die mit dem `response_types`-Parameter verwendet werden, +wie im "OAuth 2.0 Dynamic Client Registration Protocol" +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] definiert. + +### revocation\_endpoint? {#revocation-endpoint} + +```ts +optional revocation_endpoint: string; +``` + +URL des OAuth 2.0 Revocation Endpoints des Authorization Servers +[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. + +### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} + +```ts +optional revocation_endpoint_auth_methods_supported: string[]; +``` + +### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} + +```ts +optional revocation_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +JSON-Array mit einer Liste der OAuth 2.0 `scope`-Werte, die dieser Authorization Server unterstützt. +[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] + +### service\_documentation? {#service-documentation} + +```ts +optional service_documentation: string; +``` + +### token\_endpoint {#token-endpoint} + +```ts +token_endpoint: string; +``` + +URL des Token Endpoints des Authorization Servers [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. +Dies ist ERFORDERLICH, es sei denn, nur der Implicit Grant Type wird unterstützt. + +#### Siehe {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.2 + +### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} + +```ts +optional token_endpoint_auth_methods_supported: string[]; +``` + +### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} + +```ts +optional token_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### ui\_locales\_supported? {#ui-locales-supported} + +```ts +optional ui_locales_supported: string[]; +``` + +### userinfo\_endpoint? {#userinfo-endpoint} + +```ts +optional userinfo_endpoint: string; +``` + +URL des OpenID Connect [userinfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo). +Dieser Endpoint wird verwendet, um Informationen über den authentifizierten Benutzer abzurufen. + +## Siehe {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md new file mode 100644 index 0000000..be62305 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md @@ -0,0 +1,117 @@ +--- +sidebar_label: BearerAuthConfig +--- + +# Typalias: BearerAuthConfig + +```ts +type BearerAuthConfig = { + audience?: string; + issuer: | string + | ValidateIssuerFunction; + requiredScopes?: string[]; + resource?: string; + showErrorDetails?: boolean; + verifyAccessToken: VerifyAccessTokenFunction; +}; +``` + +## Eigenschaften {#properties} + +### audience? {#audience} + +```ts +optional audience: string; +``` + +Die erwartete Zielgruppe (Audience) des Zugangstokens (Zugangstoken (`aud` Anspruch)). Dies ist typischerweise der Ressourcenserver +(API), für den das Token bestimmt ist. Wenn nicht angegeben, wird die Überprüfung der Zielgruppe übersprungen. + +**Hinweis:** Wenn dein Autorisierungsserver keine Ressourcenindikatoren (RFC 8707) unterstützt, +kannst du dieses Feld weglassen, da die Zielgruppe möglicherweise nicht relevant ist. + +#### Siehe {#see} + +https://datatracker.ietf.org/doc/html/rfc8707 + +*** + +### issuer {#issuer} + +```ts +issuer: + | string + | ValidateIssuerFunction; +``` + +Ein String, der einen gültigen Aussteller (Issuer) repräsentiert, oder eine Funktion zur Validierung des Ausstellers des Zugangstokens. + +Wenn ein String angegeben wird, wird dieser als erwarteter Ausstellerwert für den direkten Vergleich verwendet. + +Wenn eine Funktion angegeben wird, sollte sie den Aussteller gemäß den Regeln in +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) validieren. + +#### Siehe {#see} + +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) für weitere Details zur Validierungsfunktion. + +*** + +### requiredScopes? {#requiredscopes} + +```ts +optional requiredScopes: string[]; +``` + +Ein Array der erforderlichen Berechtigungen (Berechtigungen (Scopes)), die das Zugangstoken haben muss. Wenn das Token nicht +alle diese Berechtigungen enthält, wird ein Fehler ausgelöst. + +**Hinweis:** Der Handler prüft den `scope`-Anspruch im Token, der je nach Implementierung des Autorisierungsservers entweder ein durch Leerzeichen getrennter String oder ein Array von Strings sein kann. Wenn der `scope`-Anspruch nicht vorhanden ist, prüft der Handler den `scopes`-Anspruch, +sofern verfügbar. + +*** + +### resource? {#resource} + +```ts +optional resource: string; +``` + +Der Bezeichner der geschützten Ressource. Wenn angegeben, verwendet der Handler die +für diese Ressource konfigurierten Autorisierungsserver, um das empfangene Token zu validieren. +Dies ist erforderlich, wenn der Handler mit einer `protectedResources`-Konfiguration verwendet wird. + +*** + +### showErrorDetails? {#showerrordetails} + +```ts +optional showErrorDetails: boolean; +``` + +Ob detaillierte Fehlerinformationen in der Antwort angezeigt werden sollen. Dies ist während der Entwicklung nützlich +zum Debuggen, sollte aber in der Produktion deaktiviert werden, um das Leaken sensibler +Informationen zu vermeiden. + +#### Standardwert {#default} + +```ts +false +``` + +*** + +### verifyAccessToken {#verifyaccesstoken} + +```ts +verifyAccessToken: VerifyAccessTokenFunction; +``` + +Funktionstyp zur Überprüfung eines Zugangstokens. + +Diese Funktion sollte einen [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) auslösen, wenn das Token ungültig ist, +oder ein AuthInfo-Objekt zurückgeben, wenn das Token gültig ist. + +#### Siehe {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) für weitere Details. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md new file mode 100644 index 0000000..290f126 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: BearerAuthErrorCode +--- + +# Typalias: BearerAuthErrorCode + +```ts +type BearerAuthErrorCode = + | "missing_auth_header" + | "invalid_auth_header_format" + | "missing_bearer_token" + | "invalid_issuer" + | "invalid_audience" + | "missing_required_scopes" + | "invalid_token"; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md new file mode 100644 index 0000000..1c68316 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md @@ -0,0 +1,179 @@ +--- +sidebar_label: CamelCaseAuthorizationServerMetadata +--- + +# Typalias: CamelCaseAuthorizationServerMetadata + +```ts +type CamelCaseAuthorizationServerMetadata = { + authorizationEndpoint: string; + codeChallengeMethodsSupported?: string[]; + grantTypesSupported?: string[]; + introspectionEndpoint?: string; + introspectionEndpointAuthMethodsSupported?: string[]; + introspectionEndpointAuthSigningAlgValuesSupported?: string[]; + issuer: string; + jwksUri?: string; + opPolicyUri?: string; + opTosUri?: string; + registrationEndpoint?: string; + responseModesSupported?: string[]; + responseTypesSupported: string[]; + revocationEndpoint?: string; + revocationEndpointAuthMethodsSupported?: string[]; + revocationEndpointAuthSigningAlgValuesSupported?: string[]; + scopesSupported?: string[]; + serviceDocumentation?: string; + tokenEndpoint: string; + tokenEndpointAuthMethodsSupported?: string[]; + tokenEndpointAuthSigningAlgValuesSupported?: string[]; + uiLocalesSupported?: string[]; + userinfoEndpoint?: string; +}; +``` + +Die camelCase-Version des OAuth 2.0 Authorization Server Metadata-Typs. + +## Typdeklaration {#type-declaration} + +### authorizationEndpoint {#authorizationendpoint} + +```ts +authorizationEndpoint: string; +``` + +### codeChallengeMethodsSupported? {#codechallengemethodssupported} + +```ts +optional codeChallengeMethodsSupported: string[]; +``` + +### grantTypesSupported? {#granttypessupported} + +```ts +optional grantTypesSupported: string[]; +``` + +### introspectionEndpoint? {#introspectionendpoint} + +```ts +optional introspectionEndpoint: string; +``` + +### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} + +```ts +optional introspectionEndpointAuthMethodsSupported: string[]; +``` + +### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} + +```ts +optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### opPolicyUri? {#oppolicyuri} + +```ts +optional opPolicyUri: string; +``` + +### opTosUri? {#optosuri} + +```ts +optional opTosUri: string; +``` + +### registrationEndpoint? {#registrationendpoint} + +```ts +optional registrationEndpoint: string; +``` + +### responseModesSupported? {#responsemodessupported} + +```ts +optional responseModesSupported: string[]; +``` + +### responseTypesSupported {#responsetypessupported} + +```ts +responseTypesSupported: string[]; +``` + +### revocationEndpoint? {#revocationendpoint} + +```ts +optional revocationEndpoint: string; +``` + +### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} + +```ts +optional revocationEndpointAuthMethodsSupported: string[]; +``` + +### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} + +```ts +optional revocationEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### serviceDocumentation? {#servicedocumentation} + +```ts +optional serviceDocumentation: string; +``` + +### tokenEndpoint {#tokenendpoint} + +```ts +tokenEndpoint: string; +``` + +### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} + +```ts +optional tokenEndpointAuthMethodsSupported: string[]; +``` + +### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} + +```ts +optional tokenEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### uiLocalesSupported? {#uilocalessupported} + +```ts +optional uiLocalesSupported: string[]; +``` + +### userinfoEndpoint? {#userinfoendpoint} + +```ts +optional userinfoEndpoint: string; +``` + +## Siehe auch {#see} + +[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) für den Originaltyp und Feldinformationen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md new file mode 100644 index 0000000..dcb545b --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md @@ -0,0 +1,123 @@ +--- +sidebar_label: CamelCaseProtectedResourceMetadata +--- + +# Typalias: CamelCaseProtectedResourceMetadata + +```ts +type CamelCaseProtectedResourceMetadata = { + authorizationDetailsTypesSupported?: string[]; + authorizationServers?: string[]; + bearerMethodsSupported?: string[]; + dpopBoundAccessTokensRequired?: boolean; + dpopSigningAlgValuesSupported?: string[]; + jwksUri?: string; + resource: string; + resourceDocumentation?: string; + resourceName?: string; + resourcePolicyUri?: string; + resourceSigningAlgValuesSupported?: string[]; + resourceTosUri?: string; + scopesSupported?: string[]; + signedMetadata?: string; + tlsClientCertificateBoundAccessTokens?: boolean; +}; +``` + +Die camelCase-Version des OAuth 2.0 Protected Resource Metadata-Typs. + +## Typdeklaration {#type-declaration} + +### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} + +```ts +optional authorizationDetailsTypesSupported: string[]; +``` + +### authorizationServers? {#authorizationservers} + +```ts +optional authorizationServers: string[]; +``` + +### bearerMethodsSupported? {#bearermethodssupported} + +```ts +optional bearerMethodsSupported: string[]; +``` + +### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} + +```ts +optional dpopBoundAccessTokensRequired: boolean; +``` + +### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} + +```ts +optional dpopSigningAlgValuesSupported: string[]; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### resource {#resource} + +```ts +resource: string; +``` + +### resourceDocumentation? {#resourcedocumentation} + +```ts +optional resourceDocumentation: string; +``` + +### resourceName? {#resourcename} + +```ts +optional resourceName: string; +``` + +### resourcePolicyUri? {#resourcepolicyuri} + +```ts +optional resourcePolicyUri: string; +``` + +### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} + +```ts +optional resourceSigningAlgValuesSupported: string[]; +``` + +### resourceTosUri? {#resourcetosuri} + +```ts +optional resourceTosUri: string; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### signedMetadata? {#signedmetadata} + +```ts +optional signedMetadata: string; +``` + +### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} + +```ts +optional tlsClientCertificateBoundAccessTokens: boolean; +``` + +## Siehe auch {#see} + +[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) für den Originaltyp und Feldinformationen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md new file mode 100644 index 0000000..f8be37f --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md @@ -0,0 +1,55 @@ +--- +sidebar_label: MCPAuthBearerAuthErrorDetails +--- + +# Typalias: MCPAuthBearerAuthErrorDetails + +```ts +type MCPAuthBearerAuthErrorDetails = { + actual?: unknown; + cause?: unknown; + expected?: unknown; + missingScopes?: string[]; + uri?: URL; +}; +``` + +## Eigenschaften {#properties} + +### actual? {#actual} + +```ts +optional actual: unknown; +``` + +*** + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +*** + +### expected? {#expected} + +```ts +optional expected: unknown; +``` + +*** + +### missingScopes? {#missingscopes} + +```ts +optional missingScopes: string[]; +``` + +*** + +### uri? {#uri} + +```ts +optional uri: URL; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md new file mode 100644 index 0000000..171b4c5 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md @@ -0,0 +1,13 @@ +--- +sidebar_label: MCPAuthConfig +--- + +# Typalias: MCPAuthConfig + +```ts +type MCPAuthConfig = + | AuthServerModeConfig + | ResourceServerModeConfig; +``` + +Konfiguration für die [MCPAuth](/references/js/classes/MCPAuth.md)-Klasse, die entweder einen einzelnen Legacy-`Autorisierungsserver` oder die `Resource Server`-Konfiguration unterstützt. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md new file mode 100644 index 0000000..d090ace --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md @@ -0,0 +1,9 @@ +--- +sidebar_label: MCPAuthTokenVerificationErrorCode +--- + +# Typalias: MCPAuthTokenVerificationErrorCode + +```ts +type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md new file mode 100644 index 0000000..5e90e15 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md @@ -0,0 +1,157 @@ +--- +sidebar_label: ProtectedResourceMetadata +--- + +# Typalias: ProtectedResourceMetadata + +```ts +type ProtectedResourceMetadata = { + authorization_details_types_supported?: string[]; + authorization_servers?: string[]; + bearer_methods_supported?: string[]; + dpop_bound_access_tokens_required?: boolean; + dpop_signing_alg_values_supported?: string[]; + jwks_uri?: string; + resource: string; + resource_documentation?: string; + resource_name?: string; + resource_policy_uri?: string; + resource_signing_alg_values_supported?: string[]; + resource_tos_uri?: string; + scopes_supported?: string[]; + signed_metadata?: string; + tls_client_certificate_bound_access_tokens?: boolean; +}; +``` + +Schema für OAuth 2.0 Geschützte Ressourcen-Metadaten. + +## Typdeklaration {#type-declaration} + +### authorization\_details\_types\_supported? {#authorization-details-types-supported} + +```ts +optional authorization_details_types_supported: string[]; +``` + +Unterstützte Werte für den Typ der Autorisierungsdetails, wenn der Parameter authorization_details in der Anfrage verwendet wird. + +### authorization\_servers? {#authorization-servers} + +```ts +optional authorization_servers: string[]; +``` + +Liste der OAuth-Autorisierungsserver-Ausstellerkennungen, die mit dieser geschützten Ressource verwendet werden können. + +### bearer\_methods\_supported? {#bearer-methods-supported} + +```ts +optional bearer_methods_supported: string[]; +``` + +Unterstützte Methoden zum Senden von OAuth 2.0 Bearer Tokens. Werte: ["header", "body", "query"]. + +### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} + +```ts +optional dpop_bound_access_tokens_required: boolean; +``` + +Ob die geschützte Ressource immer DPoP-gebundene Zugangstokens (Zugangstoken) erfordert. + +### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} + +```ts +optional dpop_signing_alg_values_supported: string[]; +``` + +Unterstützte JWS-Algorithmen zur Validierung von DPoP-Proof JWTs. + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +URL des JSON Web Key (JWK) Set-Dokuments der geschützten Ressource. Dieses Dokument enthält die öffentlichen Schlüssel, +die zur Überprüfung digitaler Signaturen von Antworten oder Daten verwendet werden können, die von dieser geschützten Ressource zurückgegeben werden. +Dies unterscheidet sich von der jwks_uri des Autorisierungsservers, die für die Token-Validierung verwendet wird. Wenn die geschützte +Ressource ihre Antworten signiert, können Clients diese öffentlichen Schlüssel abrufen, um die Authentizität und Integrität +der empfangenen Daten zu überprüfen. + +### resource {#resource} + +```ts +resource: string; +``` + +Der Ressourcenbezeichner der geschützten Ressource. + +### resource\_documentation? {#resource-documentation} + +```ts +optional resource_documentation: string; +``` + +URL mit Entwicklerdokumentation zur Nutzung der geschützten Ressource. + +### resource\_name? {#resource-name} + +```ts +optional resource_name: string; +``` + +Für Endbenutzer lesbarer Name der geschützten Ressource zur Anzeige. + +### resource\_policy\_uri? {#resource-policy-uri} + +```ts +optional resource_policy_uri: string; +``` + +URL mit Informationen zu den Anforderungen an die Datennutzung der geschützten Ressource. + +### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} + +```ts +optional resource_signing_alg_values_supported: string[]; +``` + +Von der geschützten Ressource unterstützte JWS-Signaturalgorithmen zum Signieren von Ressourcenantworten. + +### resource\_tos\_uri? {#resource-tos-uri} + +```ts +optional resource_tos_uri: string; +``` + +URL mit den Nutzungsbedingungen der geschützten Ressource. + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +Liste der Berechtigungswerte (Scopes), die in Autorisierungsanfragen zum Zugriff auf diese geschützte Ressource verwendet werden. + +### signed\_metadata? {#signed-metadata} + +```ts +optional signed_metadata: string; +``` + +Ein signiertes JWT, das Metadatenparameter als Ansprüche (Claims) enthält. Das JWT muss mit JWS signiert sein und einen 'iss'-Anspruch enthalten. +Dieses Feld bietet eine Möglichkeit, die Authentizität der Metadaten selbst kryptografisch zu überprüfen. +Die Signatur kann mit den öffentlichen Schlüsseln überprüft werden, die am `jwks_uri`-Endpunkt verfügbar sind. +Wenn vorhanden, haben die Werte in diesen signierten Metadaten Vorrang vor den entsprechenden einfachen +JSON-Werten in diesem Metadatendokument. Dies hilft, Manipulationen an den Ressourcenmetadaten zu verhindern. + +### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} + +```ts +optional tls_client_certificate_bound_access_tokens: boolean; +``` + +Ob die geschützte Ressource Mutual-TLS-Clientzertifikat-gebundene Zugangstokens unterstützt. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md new file mode 100644 index 0000000..5d39631 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md @@ -0,0 +1,23 @@ +--- +sidebar_label: ResourceServerModeConfig +--- + +# Typalias: ResourceServerModeConfig + +```ts +type ResourceServerModeConfig = { + protectedResources: ResourceServerConfig | ResourceServerConfig[]; +}; +``` + +Konfiguration für den MCP-Server im Resource-Server-Modus. + +## Eigenschaften {#properties} + +### protectedResources {#protectedresources} + +```ts +protectedResources: ResourceServerConfig | ResourceServerConfig[]; +``` + +Eine einzelne Resource-Server-Konfiguration oder ein Array davon. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md new file mode 100644 index 0000000..2acfee6 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md @@ -0,0 +1,31 @@ +--- +sidebar_label: ValidateIssuerFunction +--- + +# Typalias: ValidateIssuerFunction() + +```ts +type ValidateIssuerFunction = (tokenIssuer: string) => void; +``` + +Funktionstyp zur Validierung des Ausstellers (Issuer) des Zugangstokens (Access token). + +Diese Funktion sollte einen [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) mit dem Code 'invalid_issuer' auslösen, wenn der Aussteller +nicht gültig ist. Der Aussteller sollte anhand folgender Kriterien validiert werden: + +1. Die in den Auth-Server-Metadaten von MCP-Auth konfigurierten Autorisierungsserver (Authorization servers) +2. Die in den Metadaten der geschützten Ressource (protected resource) aufgeführten Autorisierungsserver (Authorization servers) + +## Parameter {#parameters} + +### tokenIssuer {#tokenissuer} + +`string` + +## Rückgabewert {#returns} + +`void` + +## Ausnahmen {#throws} + +Wenn der Aussteller nicht erkannt oder ungültig ist. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md new file mode 100644 index 0000000..5e0f94e --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md @@ -0,0 +1,39 @@ +--- +sidebar_label: VerifyAccessTokenFunction +--- + +# Typalias: VerifyAccessTokenFunction() + +```ts +type VerifyAccessTokenFunction = (token: string) => MaybePromise; +``` + +Funktionstyp zur Überprüfung eines Zugangstokens (Access token). + +Diese Funktion sollte einen [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) auslösen, wenn das Token ungültig ist, +oder ein AuthInfo-Objekt zurückgeben, wenn das Token gültig ist. + +Wenn du beispielsweise eine JWT-Überprüfungsfunktion hast, sollte sie mindestens die Signatur des Tokens +überprüfen, das Ablaufdatum validieren und die notwendigen Ansprüche (Claims) extrahieren, um ein `AuthInfo`- +Objekt zurückzugeben. + +**Hinweis:** Es ist nicht notwendig, die folgenden Felder im Token zu überprüfen, da sie vom Handler geprüft werden: + +- `iss` (Aussteller / issuer) +- `aud` (Zielgruppe / audience) +- `scope` (Berechtigungen / scopes) + +## Parameter {#parameters} + +### token {#token} + +`string` + +Der zu überprüfende Zugangstoken-String (Access token). + +## Rückgabewert {#returns} + +`MaybePromise`\<`AuthInfo`\> + +Ein Promise, das auf ein AuthInfo-Objekt aufgelöst wird, oder ein synchroner Wert, wenn das +Token gültig ist. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md new file mode 100644 index 0000000..b0576e7 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: VerifyAccessTokenMode +--- + +# Typalias: VerifyAccessTokenMode + +```ts +type VerifyAccessTokenMode = "jwt"; +``` + +Die von `bearerAuth` unterstützten integrierten Überprüfungsmodi. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md new file mode 100644 index 0000000..b4726e8 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: authServerErrorDescription +--- + +# Variable: authServerErrorDescription + +```ts +const authServerErrorDescription: Readonly>; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md new file mode 100644 index 0000000..67260d1 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: authorizationServerMetadataSchema +--- + +# Variable: authorizationServerMetadataSchema + +```ts +const authorizationServerMetadataSchema: ZodObject; +``` + +Zod-Schema für OAuth 2.0 Authorization Server Metadata wie in RFC 8414 definiert. + +## Siehe {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md new file mode 100644 index 0000000..ed1a931 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: bearerAuthErrorDescription +--- + +# Variable: bearerAuthErrorDescription + +```ts +const bearerAuthErrorDescription: Readonly>; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md new file mode 100644 index 0000000..7a13a9c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseAuthorizationServerMetadataSchema +--- + +# Variable: camelCaseAuthorizationServerMetadataSchema + +```ts +const camelCaseAuthorizationServerMetadataSchema: ZodObject; +``` + +Die camelCase-Version des OAuth 2.0 Authorization Server Metadata Zod-Schemas. + +## Siehe auch {#see} + +[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) für das ursprüngliche Schema und Feldinformationen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md new file mode 100644 index 0000000..d2e552c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseProtectedResourceMetadataSchema +--- + +# Variable: camelCaseProtectedResourceMetadataSchema + +```ts +const camelCaseProtectedResourceMetadataSchema: ZodObject; +``` + +Die camelCase-Version des OAuth 2.0 Protected Resource Metadata Zod-Schemas. + +## Siehe auch {#see} + +[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) für das ursprüngliche Schema und Feldinformationen. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md new file mode 100644 index 0000000..c29ea72 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md @@ -0,0 +1,9 @@ +--- +sidebar_label: defaultValues +--- + +# Variable: defaultValues + +```ts +const defaultValues: Readonly>; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md new file mode 100644 index 0000000..c304d0e --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md @@ -0,0 +1,11 @@ +--- +sidebar_label: protectedResourceMetadataSchema +--- + +# Variable: protectedResourceMetadataSchema + +```ts +const protectedResourceMetadataSchema: ZodObject; +``` + +Zod-Schema für OAuth 2.0 Geschützte Ressourcen-Metadaten (Protected Resource Metadata). \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md new file mode 100644 index 0000000..68cbf41 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md @@ -0,0 +1,12 @@ +--- +sidebar_label: serverMetadataPaths +--- + +# Variable: serverMetadataPaths + +```ts +const serverMetadataPaths: Readonly<{ + oauth: "/.well-known/oauth-authorization-server"; + oidc: "/.well-known/openid-configuration"; +}>; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md new file mode 100644 index 0000000..3d6e760 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: tokenVerificationErrorDescription +--- + +# Variable: tokenVerificationErrorDescription + +```ts +const tokenVerificationErrorDescription: Readonly>; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md new file mode 100644 index 0000000..e60de41 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md @@ -0,0 +1,9 @@ +--- +sidebar_label: validateServerConfig +--- + +# Variable: validateServerConfig + +```ts +const validateServerConfig: ValidateServerConfig; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx b/i18n/de/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx new file mode 100644 index 0000000..00f677a --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx @@ -0,0 +1,73 @@ +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + + + + +```python +mcp = FastMCP("MyMCPServer") +resource_identifier = "https://api.example.com" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_identifier, + authorization_servers=[fetch_server_config('', AuthServerType.OIDC)], + scopes_supported=["read", "write"], + ) + ) +) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + Mount('/', app=mcp.sse_app(), middleware=[Middleware( + mcp_auth.bearer_auth_middleware("jwt", + resource=resource_identifier, + audience=resource_identifier, + required_scopes=["read", "write"] + ) + )]) + ] +) + +@mcp.tool() +def whoami(): + return mcp_auth.auth_info.claims +``` + + + + +```ts +const server = new McpServer(/* ... */); +const resourceIdentifier = 'https://api.example.com'; + +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceIdentifier, + authorizationServers: [await fetchServerConfig('', { type: 'oidc' })], + scopesSupported: ['read', 'write'], + } + } +}); + +const app = express(); + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +app.use(mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, + requiredScopes: ['read', 'write'] +})); + +server.tool('whoami', ({ authInfo }) => { + return authInfo.claims; +}); +``` + + + diff --git a/i18n/de/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx b/i18n/de/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx new file mode 100644 index 0000000..8c483ce --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx @@ -0,0 +1,1396 @@ +--- +sidebar_position: 2 +sidebar_label: 'Tutorial: Baue einen Todo-Manager' +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + +# Tutorial: Baue einen Todo-Manager + +In diesem Tutorial bauen wir einen Todo-Manager-MCP-Server mit Benutzer-Authentifizierung und -Autorisierung. Nach der neuesten MCP-Spezifikation agiert unser MCP-Server als OAuth 2.0 **Ressourcenserver (Resource Server)**, der Zugangstokens validiert und berechtigungsbasierte Berechtigungen durchsetzt. + +Nach Abschluss dieses Tutorials hast du: + +- ✅ Ein grundlegendes Verständnis, wie du rollenbasierte Zugangskontrolle (RBAC) in deinem MCP-Server einrichtest. +- ✅ Einen MCP-Server, der als Ressourcenserver agiert und Zugangstokens verwendet, die von einem Autorisierungsserver ausgegeben werden. +- ✅ Eine funktionierende Implementierung der durch Berechtigungen gesteuerten Zugriffskontrolle für Todo-Operationen. + +## Überblick \{#overview} + +Das Tutorial umfasst folgende Komponenten: + +- **MCP-Client (MCP Inspector)**: Ein visuelles Test-Tool für MCP-Server, das als OAuth 2.0/OIDC-Client agiert. Es startet den Autorisierungs-Flow mit dem Autorisierungsserver und erhält Zugangstokens, um Anfragen an den MCP-Server zu authentifizieren. +- **Autorisierungsserver**: Ein OAuth 2.1- oder OpenID Connect-Anbieter, der Benutzeridentitäten verwaltet, Benutzer authentifiziert und Zugangstokens mit passenden Berechtigungen an autorisierte Clients ausgibt. +- **MCP-Server (Ressourcenserver)**: Nach der neuesten MCP-Spezifikation agiert der MCP-Server als Ressourcenserver im OAuth 2.0-Framework. Er validiert Zugangstokens, die vom Autorisierungsserver ausgegeben wurden, und erzwingt berechtigungsbasierte Berechtigungen für Todo-Operationen. + +Diese Architektur folgt dem Standard-OAuth 2.0-Flow, bei dem: +- Der **MCP Inspector** geschützte Ressourcen im Namen des Benutzers anfordert +- Der **Autorisierungsserver** den Benutzer authentifiziert und Zugangstokens ausgibt +- Der **MCP-Server** Tokens validiert und geschützte Ressourcen basierend auf gewährten Berechtigungen bereitstellt + +Hier ist ein Überblicksdiagramm der Interaktion zwischen diesen Komponenten: + +```mermaid +sequenceDiagram + autonumber + participant Client as MCP Inspector
(OAuth-Client) + participant RS as MCP-Server
(Ressourcenserver) + participant AS as Autorisierungsserver + + Client->>RS: MCP-Anfrage (kein Token) + RS-->>Client: 401 Nicht autorisiert (WWW-Authenticate) + Note over Client: Ressourcen-Metadaten-URL
aus dem WWW-Authenticate-Header extrahieren + + Client->>RS: GET /.well-known/oauth-protected-resource (resource_metadata) + RS-->>Client: Geschützte Ressourcen-Metadaten
(enthält Autorisierungsserver-URL) + + Client->>AS: GET /.well-known/oauth-authorization-server + AS-->>Client: Autorisierungsserver-Metadaten + Client->>AS: OAuth-Autorisierung (Login & Zustimmung) + AS-->>Client: Zugangstoken + + Client->>RS: MCP-Anfrage (Authorization: Bearer ) + RS->>RS: Zugangstoken validieren (gültig und autorisiert) + RS-->>Client: MCP-Antwort +``` + +## Verstehe deinen Autorisierungsserver \{#understand-your-authorization-server} + +### Zugangstokens mit Berechtigungen (Scopes) \{#access-tokens-with-scopes} + +Um [rollenbasierte Zugangskontrolle (RBAC)](https://auth.wiki/rbac) in deinem MCP-Server zu implementieren, muss dein Autorisierungsserver das Ausstellen von Zugangstokens mit Berechtigungen unterstützen. Berechtigungen (Scopes) repräsentieren die Rechte, die einem Benutzer gewährt wurden. + + + + +[Logto](https://logto.io) bietet RBAC-Unterstützung durch seine API-Ressourcen (gemäß [RFC 8707: Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707)) und Rollenfunktionen. So richtest du es ein: + +1. Melde dich bei der [Logto Console](https://cloud.logto.io) (oder deiner selbst gehosteten Logto Console) an. + +2. Erstelle API-Ressource und Berechtigungen: + + - Gehe zu "API-Ressourcen" + - Erstelle eine neue API-Ressource namens "Todo Manager" + - Füge folgende Berechtigungen hinzu: + - `create:todos`: "Neue Todo-Einträge erstellen" + - `read:todos`: "Alle Todo-Einträge lesen" + - `delete:todos`: "Beliebigen Todo-Eintrag löschen" + +3. Erstelle Rollen (empfohlen für einfachere Verwaltung): + + - Gehe zu "Rollen" + - Erstelle eine "Admin"-Rolle und weise alle Berechtigungen zu (`create:todos`, `read:todos`, `delete:todos`) + - Erstelle eine "User"-Rolle und weise nur die Berechtigung `create:todos` zu + +4. Berechtigungen zuweisen: + - Gehe zu "Benutzer" + - Wähle einen Benutzer aus + - Du kannst entweder: + - Rollen im Tab "Rollen" zuweisen (empfohlen) + - Oder direkt Berechtigungen im Tab "Berechtigungen" zuweisen + +Die Berechtigungen werden im `scope`-Anspruch des JWT-Zugangstokens als durch Leerzeichen getrennte Zeichenkette enthalten sein. + + + + +OAuth 2.0 / OIDC-Anbieter unterstützen in der Regel berechtigungsbasierte Zugangskontrolle. Bei der Implementierung von RBAC: + +1. Definiere die benötigten Berechtigungen in deinem Autorisierungsserver +2. Konfiguriere deinen Client so, dass diese Berechtigungen während des Autorisierungs-Flows angefordert werden +3. Stelle sicher, dass dein Autorisierungsserver die gewährten Berechtigungen im Zugangstoken einträgt +4. Die Berechtigungen sind üblicherweise im `scope`-Anspruch des JWT-Zugangstokens enthalten + +Siehe die Dokumentation deines Anbieters für Details zu: + +- Wie du Berechtigungen definierst und verwaltest +- Wie Berechtigungen im Zugangstoken enthalten sind +- Zusätzliche RBAC-Funktionen wie Rollenverwaltung + + + + +### Tokens validieren und Berechtigungen prüfen \{#validating-tokens-and-checking-permissions} + +Nach der neuesten MCP-Spezifikation agiert der MCP-Server als **Ressourcenserver (Resource Server)** im OAuth 2.0-Framework. Als Ressourcenserver hat der MCP-Server folgende Aufgaben: + +1. **Token-Validierung**: Überprüfe die Echtheit und Integrität der von MCP-Clients erhaltenen Zugangstokens +2. **Berechtigungsdurchsetzung**: Extrahiere und prüfe die Berechtigungen aus dem Zugangstoken, um festzustellen, welche Operationen der Client ausführen darf +3. **Ressourcenschutz**: Gebe geschützte Ressourcen (Tools ausführen) nur frei, wenn der Client gültige Tokens mit ausreichenden Berechtigungen vorlegt + +Wenn dein MCP-Server eine Anfrage erhält, läuft der Validierungsprozess wie folgt ab: + +1. Extrahiere das Zugangstoken aus dem `Authorization`-Header (Bearer-Token-Format) +2. Überprüfe die Signatur und das Ablaufdatum des Zugangstokens +3. Extrahiere die Berechtigungen und Benutzerinformationen aus dem validierten Token +4. Prüfe, ob das Token die erforderlichen Berechtigungen für die angeforderte Operation enthält + +Beispiel: Wenn ein Benutzer einen neuen Todo-Eintrag erstellen möchte, muss sein Zugangstoken die Berechtigung `create:todos` enthalten. So funktioniert der Validierungs-Flow des Ressourcenservers: + +```mermaid +sequenceDiagram + participant Client as MCP-Client + participant Server as MCP-Server
(Ressourcenserver) + participant Auth as Autorisierungsserver + + Client->>Server: Anfrage mit Zugangstoken
(Authorization: Bearer ) + + alt JWT-Validierung (bevorzugt) + Server->>Auth: JWKS abrufen (falls nicht im Cache) + Auth-->>Server: JWKS zurückgeben + Server->>Server: JWT-Signatur & Claims lokal validieren + else Token-Introspektion (Fallback) + Server->>Auth: POST /introspect
(token=access_token) + Auth-->>Server: Token-Info zurückgeben
(active, scope, user_id, etc.) + end + + Server->>Server: Berechtigungen & Benutzerkontext
aus validiertem Token extrahieren + + alt Hat erforderliche Berechtigungen + Server->>Server: Angeforderte Operation ausführen + Server->>Client: Operationsergebnis zurückgeben + else Fehlende Berechtigungen + Server->>Client: 403 Verboten
(insufficient_scope error) + end +``` + +### Dynamische Client-Registrierung \{#dynamic-client-registration} + +Die dynamische Client-Registrierung ist für dieses Tutorial nicht erforderlich, kann aber nützlich sein, wenn du den MCP-Client-Registrierungsprozess mit deinem Autorisierungsserver automatisieren möchtest. Siehe [Ist Dynamic Client Registration erforderlich?](/provider-list#is-dcr-required) für weitere Details. + +## Verstehe RBAC im Todo-Manager \{#understand-rbac-in-todo-manager} + +Zu Demonstrationszwecken implementieren wir ein einfaches rollenbasiertes Zugangskontrollsystem (RBAC) in unserem Todo-Manager-MCP-Server. Das zeigt dir die Grundprinzipien von RBAC bei überschaubarer Implementierung. + +:::note +Auch wenn dieses Tutorial RBAC-basierte Berechtigungsverwaltung demonstriert, ist es wichtig zu wissen, dass nicht alle Authentifizierungsanbieter die Berechtigungsverwaltung über Rollen implementieren. Manche Anbieter haben eigene Mechanismen zur Verwaltung von Zugangskontrolle und Berechtigungen. +::: + +### Tools und Berechtigungen \{#tools-and-scopes} + +Unser Todo-Manager-MCP-Server stellt drei Haupttools bereit: + +- `create-todo`: Einen neuen Todo-Eintrag erstellen +- `get-todos`: Alle Todos auflisten +- `delete-todo`: Ein Todo anhand der ID löschen + +Zur Zugriffskontrolle auf diese Tools definieren wir folgende Berechtigungen: + +- `create:todos`: Erlaubt das Erstellen neuer Todo-Einträge +- `delete:todos`: Erlaubt das Löschen bestehender Todo-Einträge +- `read:todos`: Erlaubt das Abfragen und Abrufen aller Todo-Einträge + +### Rollen und Berechtigungen \{#roles-and-permissions} + +Wir definieren zwei Rollen mit unterschiedlichen Zugriffsrechten: + +| Rolle | create:todos | read:todos | delete:todos | +| ------ | ------------ | ---------- | ------------ | +| Admin | ✅ | ✅ | ✅ | +| User | ✅ | | | + +- **User**: Ein normaler Benutzer, der Todo-Einträge erstellen und nur seine eigenen Todos ansehen oder löschen kann +- **Admin**: Ein Administrator, der alle Todo-Einträge erstellen, ansehen und löschen kann, unabhängig vom Eigentümer + +### Ressourcenbesitz \{#resource-ownership} + +Obwohl die obige Berechtigungstabelle die explizit zugewiesenen Berechtigungen pro Rolle zeigt, gibt es ein wichtiges Prinzip des Ressourcenbesitzes: + +- **Benutzer** haben nicht die Berechtigungen `read:todos` oder `delete:todos`, können aber trotzdem: + - Ihre eigenen Todo-Einträge lesen + - Ihre eigenen Todo-Einträge löschen +- **Admins** haben volle Berechtigungen (`read:todos` und `delete:todos`) und können: + - Alle Todo-Einträge im System sehen + - Jeden Todo-Eintrag löschen, unabhängig vom Eigentümer + +Das demonstriert ein häufiges Muster in RBAC-Systemen, bei dem der Besitz einer Ressource implizite Rechte für eigene Ressourcen gewährt, während administrative Rollen explizite Rechte für alle Ressourcen erhalten. + +:::tip Mehr erfahren +Um tiefer in RBAC-Konzepte und Best Practices einzutauchen, siehe [Mastering RBAC: A Comprehensive Real-World Example](https://blog.logto.io/mastering-rbac). +::: + +## Autorisierung im Anbieter konfigurieren \{#configure-authorization-in-your-provider} + +Um das oben beschriebene Zugangskontrollsystem zu implementieren, musst du deinen Autorisierungsserver so konfigurieren, dass er die benötigten Berechtigungen unterstützt. So geht es mit verschiedenen Anbietern: + + + + +[Logto](https://logto.io) bietet RBAC-Unterstützung durch seine API-Ressourcen und Rollenfunktionen. So richtest du es ein: + +1. Melde dich bei der [Logto Console](https://cloud.logto.io) (oder deiner selbst gehosteten Logto Console) an. + +2. Erstelle API-Ressource und Berechtigungen: + + - Gehe zu "API-Ressourcen" + - Erstelle eine neue API-Ressource namens "Todo Manager" und verwende `http://localhost:3001` als Ressourcenindikator. + - **Wichtig**: Der Ressourcenindikator muss mit der URL deines MCP-Servers übereinstimmen. Für dieses Tutorial verwenden wir `http://localhost:3001`, da unser MCP-Server auf Port 3001 läuft. In Produktion verwende deine tatsächliche MCP-Server-URL (z. B. `https://your-mcp-server.example.com`). + - Erstelle folgende Berechtigungen: + - `create:todos`: "Neue Todo-Einträge erstellen" + - `read:todos`: "Alle Todo-Einträge lesen" + - `delete:todos`: "Beliebigen Todo-Eintrag löschen" + +3. Erstelle Rollen (empfohlen für einfachere Verwaltung): + + - Gehe zu "Rollen" + - Erstelle eine "Admin"-Rolle und weise alle Berechtigungen zu (`create:todos`, `read:todos`, `delete:todos`) + - Erstelle eine "User"-Rolle und weise nur die Berechtigung `create:todos` zu + - Wechsle auf der Detailseite der "User"-Rolle zum Tab "Allgemein" und setze die "User"-Rolle als "Standardrolle". + +4. Benutzerrollen und Berechtigungen verwalten: + - Für neue Benutzer: + - Sie erhalten automatisch die "User"-Rolle, da wir sie als Standardrolle gesetzt haben + - Für bestehende Benutzer: + - Gehe zu "Benutzerverwaltung" + - Wähle einen Benutzer aus + - Weise dem Benutzer Rollen im Tab "Rollen" zu + +:::tip Programmatische Rollenverwaltung +Du kannst auch die [Management API](https://docs.logto.io/integrate-logto/interact-with-management-api) von Logto verwenden, um Benutzerrollen programmatisch zu verwalten. Das ist besonders nützlich für automatisierte Benutzerverwaltung oder beim Bau von Admin-Panels. +::: + +Beim Anfordern eines Zugangstokens wird Logto die Berechtigungen im `scope`-Anspruch des Tokens basierend auf den Rollenzuweisungen des Benutzers eintragen. + + + + +Für OAuth 2.0- oder OpenID Connect-Anbieter musst du die Berechtigungen konfigurieren, die verschiedene Rechte repräsentieren. Die genauen Schritte hängen vom Anbieter ab, aber im Allgemeinen: + +1. Berechtigungen definieren: + + - Konfiguriere deinen Autorisierungsserver so, dass er unterstützt: + - `create:todos` + - `read:todos` + - `delete:todos` + +2. Client konfigurieren: + + - Registriere oder aktualisiere deinen Client, damit diese Berechtigungen angefordert werden + - Stelle sicher, dass die Berechtigungen im Zugangstoken enthalten sind + +3. Berechtigungen zuweisen: + - Verwende die Oberfläche deines Anbieters, um Benutzern passende Berechtigungen zuzuweisen + - Manche Anbieter unterstützen rollenbasierte Verwaltung, andere direkte Berechtigungszuweisung + - Siehe die Dokumentation deines Anbieters für den empfohlenen Ansatz + +:::tip +Die meisten Anbieter werden die gewährten Berechtigungen im `scope`-Anspruch des Zugangstokens eintragen. Das Format ist typischerweise eine durch Leerzeichen getrennte Zeichenkette von Berechtigungswerten. +::: + + + + +Nach der Konfiguration deines Autorisierungsservers erhalten Benutzer Zugangstokens mit ihren gewährten Berechtigungen. Der MCP-Server verwendet diese Berechtigungen, um zu bestimmen: + +- Ob ein Benutzer neue Todos erstellen darf (`create:todos`) +- Ob ein Benutzer alle Todos (`read:todos`) oder nur seine eigenen sehen darf +- Ob ein Benutzer beliebige Todos (`delete:todos`) oder nur seine eigenen löschen darf + +## MCP-Server einrichten \{#set-up-the-mcp-server} + +Wir verwenden die [offiziellen MCP-SDKs](https://github.com/modelcontextprotocol), um unseren Todo-Manager-MCP-Server zu erstellen. + +### Neues Projekt erstellen \{#create-a-new-project} + + + + +Neues Python-Projekt einrichten: + +```bash +mkdir mcp-todo-server +cd mcp-todo-server + +# Neues Python-Projekt initialisieren +uv init + +# Neue virtuelle Umgebung mit uv erstellen +uv venv + +# Virtuelle Umgebung aktivieren (optional bei 'uv run') +source .venv/bin/activate +``` + +:::note +Dieses Projekt verwendet `uv` für das Paketmanagement, aber du kannst auch andere Paketmanager wie `pip`, `poetry` oder `conda` verwenden. +::: + + + + +Neues Node.js-Projekt einrichten: + +```bash +mkdir mcp-server +cd mcp-server +npm init -y # Oder `pnpm init` verwenden +npm pkg set type="module" +npm pkg set main="todo-manager.ts" +npm pkg set scripts.start="node --experimental-strip-types todo-manager.ts" +``` + +:::note +Wir verwenden TypeScript in unseren Beispielen, da Node.js v22.6.0+ TypeScript nativ mit dem Flag `--experimental-strip-types` unterstützt. Wenn du JavaScript verwendest, ist der Code ähnlich – stelle nur sicher, dass du Node.js v22.6.0 oder neuer verwendest. Siehe Node.js-Dokumentation für Details. +::: + + + + +### MCP-SDK und Abhängigkeiten installieren \{#install-the-mcp-sdk-and-dependencies} + + + + +Installiere die benötigten Abhängigkeiten: + +```bash +uv add "mcp[cli]" uvicorn starlette +``` + + + + +```bash +npm install @modelcontextprotocol/sdk express zod +``` + +Oder einen anderen Paketmanager deiner Wahl, wie `pnpm` oder `yarn`. + + + + +### MCP-Server erstellen \{#create-the-mcp-server} + +Erstelle zunächst einen Basis-MCP-Server mit den Tool-Definitionen: + + + + +Erstelle eine Datei namens `server.py` und füge folgenden Code hinzu: + +```python +# server.py + +import contextlib +from typing import Any +from mcp.server.fastmcp import FastMCP +from starlette.applications import Starlette +from starlette.routing import Mount + +# Initialisiere den FastMCP-Server +mcp = FastMCP(name="Todo Manager", stateless_http=True, streamable_http_path='/') + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """Neues Todo erstellen. Erfordert 'create:todos'-Berechtigung.""" + return {"error": "Not implemented"} + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """Todos auflisten. Benutzer mit 'read:todos'-Berechtigung sehen alle Todos.""" + return {"error": "Not implemented"} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """Todo anhand der ID löschen. Benutzer können ihre eigenen Todos löschen.""" + return {"error": "Not implemented"} + +@contextlib.asynccontextmanager +async def lifespan(app: Starlette): + async with contextlib.AsyncExitStack() as stack: + await stack.enter_async_context(mcp.session_manager.run()) + yield + +# App erstellen +app = Starlette( + routes=[ + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + +Starte den Server mit: + +```bash +# Todo Manager Server mit uvicorn starten +uvicorn server:app --host 127.0.0.1 --port 3001 + +# Oder mit uv: +# uv run uvicorn server:app --host 127.0.0.1 --port 3001 +``` + + + + +Erstelle eine Datei namens `todo-manager.ts` und füge folgenden Code hinzu: + +```ts +// todo-manager.ts + +import { z } from 'zod'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import express, { type Request, type Response } from 'express'; + +// MCP-Server erstellen +const server = new McpServer({ + name: 'Todo Manager', + version: '0.0.0', +}); + +server.tool('create-todo', 'Neues Todo erstellen', { content: z.string() }, async ({ content }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('get-todos', 'Alle Todos auflisten', async () => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('delete-todo', 'Todo anhand der ID löschen', { id: z.string() }, async ({ id }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +// Boilerplate-Code aus der MCP-SDK-Dokumentation +const PORT = 3001; +const app = express(); + +app.post('/', async (request: Request, response: Response) => { + // Im stateless-Modus für jede Anfrage eine neue Instanz von Transport und Server erstellen, + // um vollständige Isolation zu gewährleisten. Eine einzelne Instanz würde zu Request-ID-Kollisionen führen, + // wenn mehrere Clients gleichzeitig verbinden. + + try { + const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + }); + response.on('close', async () => { + console.log('Request closed'); + await transport.close(); + await server.close(); + }); + await server.connect(transport); + await transport.handleRequest(request, response, request.body); + } catch (error) { + console.error('Fehler bei der MCP-Anfrage:', error); + if (!response.headersSent) { + response.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32_603, + message: 'Internal server error', + }, + id: null, + }); + } + } +}); + +// SSE-Benachrichtigungen werden im stateless-Modus nicht unterstützt +app.get('/', async (request: Request, response: Response) => { + console.log('GET-MCP-Anfrage erhalten'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +// Sitzungsbeendigung im stateless-Modus nicht erforderlich +app.delete('/', async (request: Request, response: Response) => { + console.log('DELETE-MCP-Anfrage erhalten'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +app.listen(PORT); +``` + +Starte den Server mit: + +```bash +npm start +``` + + + + +### MCP-Server inspizieren \{#inspect-the-mcp-server} + +#### MCP Inspector klonen und starten \{#clone-and-run-mcp-inspector} + +Nachdem der MCP-Server läuft, können wir den MCP Inspector verwenden, um zu prüfen, ob Tools verfügbar sind. + +Die offizielle MCP Inspector v0.16.2 hat einige Bugs, die die Authentifizierungsfunktionalität beeinträchtigen. Um diese Probleme zu beheben, haben wir eine [gepatchte Version des MCP Inspectors](https://github.com/mcp-auth/inspector/tree/patch/0.16.2-fixes) erstellt, die notwendige Fixes für OAuth/OIDC-Authentifizierungsflows enthält. Wir haben auch Pull Requests an das offizielle Repository eingereicht, um diese Fixes beizutragen. + +Um den MCP Inspector zu starten, verwende folgenden Befehl (Node.js erforderlich): + +```bash +git clone https://github.com/mcp-auth/inspector.git -b patch/0.16.2-fixes +cd inspector +npm install +npm run dev +``` + +Der MCP Inspector öffnet sich automatisch im Standardbrowser, oder du kannst ihn manuell über den Link aus der Terminalausgabe aufrufen (achte darauf, den Link mit dem Parameter `MCP_PROXY_AUTH_TOKEN` zu verwenden, z. B. `http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=458ae4a4...acab1907`). + +#### MCP Inspector mit dem MCP-Server verbinden \{#connect-mcp-inspector-to-the-mcp-server} + +Vor dem Fortfahren prüfe folgende Konfiguration im MCP Inspector: + +- **Transport-Typ**: Setze auf `Streamable HTTP`. +- **URL**: Setze auf die URL deines MCP-Servers. In unserem Fall: `http://localhost:3001`. + +Jetzt kannst du auf den "Connect"-Button klicken, um zu sehen, ob der MCP Inspector eine Verbindung zum MCP-Server herstellen kann. Wenn alles funktioniert, siehst du den Status "Connected" im MCP Inspector. + +#### Checkpoint: Todo-Manager-Tools ausführen \{#checkpoint-run-todo-manager-tools} + +1. Klicke im oberen Menü des MCP Inspectors auf den Tab "Tools". +2. Klicke auf den Button "List Tools". +3. Du solltest die Tools `create-todo`, `get-todos` und `delete-todo` aufgelistet sehen. Klicke darauf, um die Tool-Details zu öffnen. +4. Rechts solltest du den Button "Run Tool" sehen. Klicke darauf und gib die erforderlichen Parameter ein, um das Tool auszuführen. +5. Du solltest das Tool-Ergebnis mit der JSON-Antwort `{"error": "Not implemented"}` sehen. + +![MCP Inspector erster Lauf](/docs-assets/images/tutorials/todo-manager/inspector-first-run.png) + +## Integration mit deinem Autorisierungsserver \{#integrate-with-your-authorization-server} + +Für diesen Abschnitt gibt es einige Überlegungen: + +
+**Die Issuer-URL deines Autorisierungsservers** + +Dies ist normalerweise die Basis-URL deines Autorisierungsservers, z. B. `https://auth.example.com`. Manche Anbieter haben einen Pfad wie `https://example.logto.app/oidc`, prüfe daher die Dokumentation deines Anbieters. + +
+ +
+**Wie du die Metadaten des Autorisierungsservers abrufst** + +- Wenn dein Autorisierungsserver dem [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) oder [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) entspricht, kannst du die eingebauten Utilities von MCP Auth verwenden, um die Metadaten automatisch abzurufen. +- Wenn dein Autorisierungsserver diese Standards nicht unterstützt, musst du die Metadaten-URL oder Endpunkte manuell in der MCP-Server-Konfiguration angeben. Siehe die Dokumentation deines Anbieters für die spezifischen Endpunkte. + +
+ +
+**Wie du den MCP Inspector als Client im Autorisierungsserver registrierst** + +- Wenn dein Autorisierungsserver [Dynamic Client Registration](https://datatracker.ietf.org/doc/html/rfc7591) unterstützt, kannst du diesen Schritt überspringen, da der MCP Inspector sich automatisch als Client registriert. +- Wenn dein Autorisierungsserver Dynamic Client Registration nicht unterstützt, musst du den MCP Inspector manuell als Client im Autorisierungsserver registrieren. + +
+ +
+**Verstehe Token-Request-Parameter** + +Beim Anfordern von Zugangstokens von verschiedenen Autorisierungsservern gibt es verschiedene Ansätze, um die Zielressource und Berechtigungen anzugeben. Hier die Hauptmuster: + +- **Ressourcenindikator-basiert**: + + - Verwendet den Parameter `resource`, um die Ziel-API anzugeben (siehe [RFC 8707: Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707)) + - Häufig in modernen OAuth 2.0-Implementierungen + - Beispielanfrage: + ```json + { + "resource": "http://localhost:3001", + "scope": "create:todos read:todos" + } + ``` + - Der Server gibt Tokens aus, die speziell an die angeforderte Ressource gebunden sind + +- **Audience-basiert**: + + - Verwendet den Parameter `audience`, um den beabsichtigten Token-Empfänger anzugeben + - Ähnlich wie Ressourcenindikatoren, aber mit anderen Semantiken + - Beispielanfrage: + ```json + { + "audience": "todo-api", + "scope": "create:todos read:todos" + } + ``` + +- **Nur Scope-basiert**: + - Verwendet ausschließlich Berechtigungen ohne resource/audience-Parameter + - Traditioneller OAuth 2.0-Ansatz + - Beispielanfrage: + ```json + { + "scope": "todo-api:create todo-api:read openid profile" + } + ``` + - Oft werden Präfixe verwendet, um Berechtigungen zu namespacen + - Häufig in einfacheren OAuth 2.0-Implementierungen + +:::tip Best Practices + +- Prüfe die Dokumentation deines Anbieters auf unterstützte Parameter +- Manche Anbieter unterstützen mehrere Ansätze gleichzeitig +- Ressourcenindikatoren bieten bessere Sicherheit durch Audience-Restriktion +- Verwende Ressourcenindikatoren, wenn verfügbar, für bessere Zugangskontrolle + ::: + +
+ +Auch wenn jeder Anbieter eigene Anforderungen hat, führen dich die folgenden Schritte durch die Integration des MCP Inspectors und MCP Servers mit anbieter-spezifischen Konfigurationen. + +### MCP Inspector als Client registrieren \{#register-mcp-inspector-as-a-client} + + + + +Die Integration des Todo-Managers mit [Logto](https://logto.io) ist einfach, da es ein OpenID Connect-Anbieter ist, der Ressourcenindikatoren und Berechtigungen unterstützt. So kannst du deine Todo-API mit `http://localhost:3001` als Ressourcenindikator absichern. + +Da Logto noch keine Dynamic Client Registration unterstützt, musst du den MCP Inspector manuell als Client in deinem Logto-Tenant registrieren: + +1. Öffne deinen MCP Inspector, gehe zur Authentifizierungskonfiguration und klicke auf die "OAuth2.0 Flow"-Konfiguration. Kopiere den **Redirect URI**-Wert, z. B. `http://localhost:6274/oauth/callback`. +2. Melde dich bei der [Logto Console](https://cloud.logto.io) (oder deiner selbst gehosteten Logto Console) an. +3. Navigiere zum Tab "Anwendungen", klicke auf "Anwendung erstellen". Unten auf der Seite klicke auf "App ohne Framework erstellen". +4. Fülle die Anwendungsdetails aus und klicke auf "Anwendung erstellen": + - **Anwendungstyp auswählen**: "Single-page application" wählen. + - **Anwendungsname**: Z. B. "MCP Inspector". +5. Im Bereich "Einstellungen / Redirect URIs" füge den kopierten **Redirect URI** ein. Klicke dann unten auf "Änderungen speichern". +6. Im oberen Bereich siehst du den Wert "App ID". Kopiere ihn. +7. Gehe zurück zum MCP Inspector und füge die "App ID" in der Authentifizierungskonfiguration unter "OAuth2.0 Flow" im Feld "Client ID" ein. +8. Im Feld "Scope" gib ein: `create:todos read:todos delete:todos`. So enthält das Zugangstoken von Logto die nötigen Berechtigungen für den Todo-Manager. + + + + +:::note +Dies ist eine generische Anleitung für OAuth 2.0 / OpenID Connect-Anbieter. Beide folgen ähnlichen Schritten, da OIDC auf OAuth 2.0 aufbaut. Siehe die Dokumentation deines Anbieters für Details. +::: + +Wenn dein Anbieter Dynamic Client Registration unterstützt, kannst du direkt zu Schritt 8 unten gehen; andernfalls musst du den MCP Inspector manuell als Client registrieren: + +1. Öffne deinen MCP Inspector, gehe zur Authentifizierungskonfiguration und klicke auf die "OAuth2.0 Flow"-Konfiguration. Kopiere den **Redirect URI**-Wert, z. B. `http://localhost:6274/oauth/callback`. + +2. Melde dich in der Konsole deines Anbieters an. + +3. Navigiere zum Bereich "Anwendungen" oder "Clients" und erstelle eine neue Anwendung oder einen neuen Client. + +4. Falls erforderlich, wähle als Client-Typ "Single-page application" oder "Public client". + +5. Nach dem Erstellen der Anwendung musst du den Redirect URI konfigurieren. Füge den kopierten **Redirect URI** ein. + +6. Finde die "Client ID" oder "Application ID" der neuen Anwendung und kopiere sie. + +7. Gehe zurück zum MCP Inspector und füge die "Client ID" in der Authentifizierungskonfiguration unter "OAuth2.0 Flow" im Feld "Client ID" ein. + +8. Im Feld "Scope" gib folgende Berechtigungen ein, um die nötigen Rechte für Todo-Operationen anzufordern: + +```text +create:todos read:todos delete:todos +``` + + + + +### MCP Auth einrichten \{#set-up-mcp-auth} + +Installiere zunächst das MCP Auth SDK in deinem MCP-Server-Projekt. + + + + +```bash +uv add mcpauth==0.2.0b1 +``` + + + + +```bash +npm install mcp-auth@0.2.0-beta.1 +``` + + + + +Jetzt müssen wir MCP Auth im MCP-Server initialisieren. Das umfasst zwei Hauptschritte: + +1. **Metadaten des Autorisierungsservers abrufen**: Wird für die spätere MCP Auth-Überprüfung der vom Autorisierungsserver ausgegebenen Zugangstokens verwendet und um die Issuer-ID des Auth-Servers in den Ressourcenmetadaten einzutragen +2. **Geschützte Ressourcenmetadaten konfigurieren**: Definiere die Ressourcenkennung deines MCP-Servers und unterstützte Berechtigungen + +#### Schritt 1: Metadaten des Autorisierungsservers abrufen \{#step-1-fetch-authorization-server-metadata\} + +Laut OAuth / OIDC-Spezifikation können wir die Metadaten des Autorisierungsservers anhand der Issuer-URL abrufen. + + + + + +In Logto findest du die Issuer-URL auf der Anwendungsdetailseite in der Logto Console unter "Endpoints & Credentials / Issuer endpoint". Sie sieht aus wie `https://my-project.logto.app/oidc`. + + + + + +Für OAuth 2.0-Anbieter musst du: + +1. Die Dokumentation deines Anbieters nach der Autorisierungsserver-URL (oft Issuer-URL oder Basis-URL genannt) durchsuchen +2. Manche Anbieter stellen dies unter `https://{your-domain}/.well-known/oauth-authorization-server` bereit +3. Im Admin-Panel deines Anbieters unter OAuth/API-Einstellungen nachsehen + + + + + +Jetzt rufe die Metadaten des Autorisierungsservers mit der MCP Auth Utility-Funktion ab: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +issuer_url = "" # Ersetze durch die Issuer-URL deines Autorisierungsservers + +# Autorisierungsserver-Konfiguration abrufen +auth_server_config = fetch_server_config(issuer_url, AuthServerType.OIDC) # oder AuthServerType.OAUTH +``` + + + +```js +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const issuerUrl = ''; // Ersetze durch die Issuer-URL deines Autorisierungsservers + +// Autorisierungsserver-Konfiguration abrufen (OIDC Discovery) +const authServerConfig = await fetchServerConfig(issuerUrl, { type: 'oidc' }); // oder { type: 'oauth' } +``` + + + + +Wenn du alternative Wege benötigst, um die Metadaten des Autorisierungsservers abzurufen oder die Konfiguration anpassen möchtest, siehe [Andere Wege zur Konfiguration der Autorisierungsserver-Metadaten](/docs/configure-server/mcp-auth#other-ways). + +#### Schritt 2: Geschützte Ressourcenmetadaten konfigurieren \{#step-2-configure-protected-resource-metadata} + +Als nächstes konfigurieren wir die Protected Resource Metadata beim Erstellen der MCP Auth-Instanz. Anschließend stellt der MCP-Server die in MCP Auth konfigurierten Ressourcenmetadaten bereit. + + + + +```python +# server.py + +# weitere Importe... +from mcpauth.types import ResourceServerConfig, ResourceServerMetadata + +# Ressourcenkennung für diesen MCP-Server definieren +resource_id = "http://localhost:3001" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + # Autorisierungsserver-Metadaten aus dem vorherigen Schritt + authorization_servers=[auth_server_config], + # Unterstützte Berechtigungen dieses MCP-Servers + scopes_supported=[ + "create:todos", + "read:todos", + "delete:todos" + ] + ) + ) +) +``` + + + +```js +// todo-manager.ts + +// Ressourcenkennung für diesen MCP-Server definieren +const resourceId = 'http://localhost:3001'; + +// MCP Auth mit Ressourcenmetadaten konfigurieren +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceId, + // Autorisierungsserver-Metadaten aus dem vorherigen Schritt + authorizationServers: [authServerConfig], + // Unterstützte Berechtigungen dieses MCP-Servers + scopesSupported: [ + "create:todos", + "read:todos", + "delete:todos" + ] + } + } +}); +``` + + + + +### MCP-Server aktualisieren \{#update-mcp-server} + +Fast geschafft! Jetzt aktualisieren wir den MCP-Server, um die MCP Auth-Route und Middleware-Funktion anzuwenden und die berechtigungsbasierte Zugriffskontrolle für die Todo-Manager-Tools basierend auf den Benutzerberechtigungen zu implementieren. + +Jetzt Protected Resource Metadata-Routen anwenden, damit MCP-Clients die erwarteten Ressourcenmetadaten vom MCP-Server abrufen können. + + + +```python +# server.py + +# ..weitere Codes + +app = Starlette( + routes=[ + # Protected Resource Metadata-Routen einrichten + # Stellt Metadaten über diesen Ressourcenserver für OAuth-Clients bereit + *mcp_auth.resource_metadata_router().routes, + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +// Protected Resource Metadata-Routen einrichten +// Stellt Metadaten über diesen Ressourcenserver für OAuth-Clients bereit +app.use(mcpAuth.protectedResourceMetadataRouter()); + +``` + + + +Als nächstes wenden wir die MCP Auth-Middleware auf den MCP-Server an. Diese Middleware übernimmt Authentifizierung und Autorisierung für eingehende Anfragen und stellt sicher, dass nur autorisierte Benutzer Zugriff auf die Todo-Manager-Tools haben. + + + +```python +# server.py + +# weitere Importe... +from starlette.middleware import Middleware + +# weitere Codes... + +# Middleware erstellen +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', resource=resource_id, audience=resource_id)) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # MCP Auth-Middleware anwenden + Mount("/", app=mcp.streamable_http_app(), middleware=[bearer_auth]), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// MCP Auth-Middleware anwenden +app.use( + mcpAuth.bearerAuth('jwt', { + resource: resourceId, + audience: resourceId, + }) +); +``` + + + +Jetzt können wir die Todo-Manager-Tools so aktualisieren, dass sie die MCP Auth-Middleware für Authentifizierung und Autorisierung nutzen. + +Aktualisiere die Implementierung der Tools wie folgt. + + + +```python +# server.py + +# weitere Importe... + +from typing import Any, List, Optional +from mcpauth.exceptions import MCPAuthBearerAuthException, BearerAuthExceptionCode +from mcpauth.types import AuthInfo, ResourceServerConfig, ResourceServerMetadata + +# Wird im nächsten Abschnitt erwähnt +from service import TodoService + +def assert_user_id(auth_info: Optional[AuthInfo]) -> str: + """Stellt sicher, dass auth_info eine gültige Benutzer-ID enthält und gibt sie zurück.""" + if not auth_info or not auth_info.subject: + raise Exception("Invalid auth info") + return auth_info.subject + +def has_required_scopes(user_scopes: List[str], required_scopes: List[str]) -> bool: + """Prüft, ob der Benutzer alle erforderlichen Berechtigungen hat.""" + return all(scope in user_scopes for scope in required_scopes) + +# TodoService-Instanz erstellen +todo_service = TodoService() + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """Neues Todo erstellen. Erfordert 'create:todos'-Berechtigung.""" + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # Nur Benutzer mit 'create:todos'-Berechtigung dürfen Todos erstellen + user_scopes = auth_info.scopes if auth_info else [] + if not has_required_scopes(user_scopes, ["create:todos"]): + raise MCPAuthBearerAuthException(BearerAuthExceptionCode.MISSING_REQUIRED_SCOPES) + + created_todo = todo_service.create_todo(content=content, owner_id=user_id) + return created_todo + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """ + Todos auflisten. Benutzer mit 'read:todos'-Berechtigung sehen alle Todos, + sonst nur ihre eigenen Todos. + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # Mit 'read:todos'-Berechtigung Zugriff auf alle Todos, + # sonst nur eigene Todos + user_scopes = auth_info.scopes if auth_info else [] + todo_owner_id = None if has_required_scopes(user_scopes, ["read:todos"]) else user_id + + todos = todo_service.get_all_todos(todo_owner_id) + return {"todos": todos} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """ + Todo anhand der ID löschen. Benutzer können ihre eigenen Todos löschen. + Benutzer mit 'delete:todos'-Berechtigung können beliebige Todos löschen. + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + todo = todo_service.get_todo_by_id(id) + + if not todo: + return {"error": "Failed to delete todo"} + + # Benutzer können nur ihre eigenen Todos löschen + # Benutzer mit 'delete:todos'-Berechtigung können beliebige Todos löschen + user_scopes = auth_info.scopes if auth_info else [] + if todo.owner_id != user_id and not has_required_scopes(user_scopes, ["delete:todos"]): + return {"error": "Failed to delete todo"} + + deleted_todo = todo_service.delete_todo(id) + + if deleted_todo: + return { + "message": f"Todo {id} deleted", + "details": deleted_todo + } + else: + return {"error": "Failed to delete todo"} +``` + + + +```js +// todo-manager.ts + +// weitere Importe... +import assert from 'node:assert'; +import { fetchServerConfig, MCPAuth, MCPAuthBearerAuthError } from 'mcp-auth'; +import { type AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js'; + +// Wird im nächsten Abschnitt erwähnt +import { TodoService } from './todo-service.js'; + +const assertUserId = (authInfo?: AuthInfo) => { + const { subject } = authInfo ?? {}; + assert(subject, 'Invalid auth info'); + return subject; +}; + +const hasRequiredScopes = (userScopes: string[], requiredScopes: string[]): boolean => { + return requiredScopes.every((scope) => userScopes.includes(scope)); +}; + +const todoService = new TodoService(); + +server.tool( + 'create-todo', + 'Neues Todo erstellen', + { content: z.string() }, + ({ content }: { content: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * Nur Benutzer mit 'create:todos'-Berechtigung dürfen Todos erstellen + */ + if (!hasRequiredScopes(authInfo?.scopes ?? [], ['create:todos'])) { + throw new MCPAuthBearerAuthError('missing_required_scopes'); + } + + const createdTodo = todoService.createTodo({ content, ownerId: userId }); + + return { + content: [{ type: 'text', text: JSON.stringify(createdTodo) }], + }; + } +); + +server.tool('get-todos', 'Alle Todos auflisten', ({ authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * Mit 'read:todos'-Berechtigung Zugriff auf alle Todos (todoOwnerId = undefined) + * Ohne 'read:todos'-Berechtigung nur eigene Todos (todoOwnerId = userId) + */ + const todoOwnerId = hasRequiredScopes(authInfo?.scopes ?? [], ['read:todos']) + ? undefined + : userId; + + const todos = todoService.getAllTodos(todoOwnerId); + + return { + content: [{ type: 'text', text: JSON.stringify(todos) }], + }; +}); + +server.tool( + 'delete-todo', + 'Todo anhand der ID löschen', + { id: z.string() }, + ({ id }: { id: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + const todo = todoService.getTodoById(id); + + if (!todo) { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Failed to delete todo' }) }], + }; + } + + /** + * Benutzer können nur ihre eigenen Todos löschen + * Benutzer mit 'delete:todos'-Berechtigung können beliebige Todos löschen + */ + if (todo.ownerId !== userId && !hasRequiredScopes(authInfo?.scopes ?? [], ['delete:todos'])) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ error: 'Failed to delete todo' }), + }, + ], + }; + } + + const deletedTodo = todoService.deleteTodo(id); + + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + message: `Todo ${id} deleted`, + details: deletedTodo, + }), + }, + ], + }; + } +); +``` + + + +Jetzt erstelle den "Todo-Service", der in obigem Code verwendet wird, um die zugehörige Funktionalität zu implementieren: + + + + +Erstelle die Datei `service.py` für den Todo-Service: + +```python +""" +Ein einfacher Todo-Service zu Demonstrationszwecken. +Verwendet eine In-Memory-Liste zur Speicherung der Todos. +""" + +from datetime import datetime +from typing import List, Optional, Dict, Any +import random +import string + +class Todo: + """Repräsentiert einen Todo-Eintrag.""" + + def __init__(self, id: str, content: str, owner_id: str, created_at: str): + self.id = id + self.content = content + self.owner_id = owner_id + self.created_at = created_at + + def to_dict(self) -> Dict[str, Any]: + """Todo in ein Dictionary für JSON-Serialisierung umwandeln.""" + return { + "id": self.id, + "content": self.content, + "ownerId": self.owner_id, + "createdAt": self.created_at + } + + +class TodoService: + """Ein einfacher Todo-Service zu Demonstrationszwecken.""" + + def __init__(self): + self._todos: List[Todo] = [] + + def get_all_todos(self, owner_id: Optional[str] = None) -> List[Dict[str, Any]]: + """ + Gibt alle Todos zurück, optional gefiltert nach owner_id. + + Args: + owner_id: Falls angegeben, nur Todos dieses Benutzers zurückgeben + + Returns: + Liste von Todo-Dictionaries + """ + if owner_id: + filtered_todos = [todo for todo in self._todos if todo.owner_id == owner_id] + return [todo.to_dict() for todo in filtered_todos] + return [todo.to_dict() for todo in self._todos] + + def get_todo_by_id(self, todo_id: str) -> Optional[Todo]: + """ + Gibt ein Todo anhand seiner ID zurück. + + Args: + todo_id: Die ID des Todos + + Returns: + Todo-Objekt falls gefunden, sonst None + """ + for todo in self._todos: + if todo.id == todo_id: + return todo + return None + + def create_todo(self, content: str, owner_id: str) -> Dict[str, Any]: + """ + Erstellt ein neues Todo. + + Args: + content: Inhalt des Todos + owner_id: ID des Benutzers, dem das Todo gehört + + Returns: + Dictionary-Darstellung des erstellten Todos + """ + todo = Todo( + id=self._generate_id(), + content=content, + owner_id=owner_id, + created_at=datetime.now().isoformat() + ) + self._todos.append(todo) + return todo.to_dict() + + def delete_todo(self, todo_id: str) -> Optional[Dict[str, Any]]: + """ + Löscht ein Todo anhand seiner ID. + + Args: + todo_id: Die ID des zu löschenden Todos + + Returns: + Dictionary-Darstellung des gelöschten Todos falls gefunden, sonst None + """ + for i, todo in enumerate(self._todos): + if todo.id == todo_id: + deleted_todo = self._todos.pop(i) + return deleted_todo.to_dict() + return None + + def _generate_id(self) -> str: + """Generiert eine zufällige ID für ein Todo.""" + return ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)) +``` + + + + +Erstelle die Datei `todo-service.ts` für den Todo-Service: + +```ts +// todo-service.ts + +type Todo = { + id: string; + content: string; + ownerId: string; + createdAt: string; +}; + +/** + * Ein einfacher Todo-Service zu Demonstrationszwecken. + * Verwendet ein In-Memory-Array zur Speicherung der Todos + */ +export class TodoService { + private readonly todos: Todo[] = []; + + getAllTodos(ownerId?: string): Todo[] { + if (ownerId) { + return this.todos.filter((todo) => todo.ownerId === ownerId); + } + return this.todos; + } + + getTodoById(id: string): Todo | undefined { + return this.todos.find((todo) => todo.id === id); + } + + createTodo({ content, ownerId }: { content: string; ownerId: string }): Todo { + const todo: Todo = { + id: this.genId(), + content, + ownerId, + createdAt: new Date().toISOString(), + }; + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + this.todos.push(todo); + return todo; + } + + deleteTodo(id: string): Todo | undefined { + const index = this.todos.findIndex((todo) => todo.id === id); + + if (index === -1) { + return undefined; + } + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + const [deleted] = this.todos.splice(index, 1); + return deleted; + } + + private genId(): string { + return Math.random().toString(36).slice(2, 10); + } +} +``` + + + + +🎉 Glückwunsch! Wir haben erfolgreich einen vollständigen MCP-Server mit Authentifizierung und Autorisierung implementiert! + +Du kannst auch unseren Beispielcode als Referenz ansehen: + + + + +:::info +Siehe das [MCP Auth Python SDK Repository](https://github.com/mcp-auth/python/tree/master/samples/current/todo-manager) für den vollständigen Code des MCP-Servers (OIDC-Version). +::: + + + + +:::info +Siehe das [MCP Auth Node.js SDK Repository](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) für den vollständigen Code des MCP-Servers (OIDC-Version). +::: + + + + +## Checkpoint: Die `todo-manager`-Tools ausführen \{#checkpoint-run-the-todo-manager-tools} + +Starte deinen MCP-Server neu und öffne den MCP Inspector im Browser. Wenn du auf den "Connect"-Button klickst, solltest du zur Anmeldeseite deines Autorisierungsservers weitergeleitet werden. + +Nach der Anmeldung und Rückkehr zum MCP Inspector wiederhole die Aktionen aus dem vorherigen Checkpoint, um die Todo-Manager-Tools auszuführen. Dieses Mal kannst du die Tools mit deiner authentifizierten Benutzeridentität nutzen. Das Verhalten der Tools hängt von den Rollen und Berechtigungen ab, die deinem Benutzer zugewiesen sind: + +- Wenn du als **User** (nur mit `create:todos`-Berechtigung) angemeldet bist: + + - Du kannst neue Todos mit dem Tool `create-todo` erstellen + - Du kannst nur deine eigenen Todos ansehen und löschen + - Du kannst keine Todos anderer Benutzer sehen oder löschen + +- Wenn du als **Admin** (mit allen Berechtigungen: `create:todos`, `read:todos`, `delete:todos`) angemeldet bist: + - Du kannst neue Todos erstellen + - Du kannst alle Todos im System mit dem Tool `get-todos` ansehen + - Du kannst beliebige Todos mit dem Tool `delete-todo` löschen, unabhängig davon, wer sie erstellt hat + +Du kannst diese unterschiedlichen Berechtigungsstufen testen, indem du: + +1. Die aktuelle Sitzung abmeldest (klicke auf "Disconnect" im MCP Inspector) +2. Dich mit einem anderen Benutzerkonto anmeldest, das andere Rollen/Berechtigungen hat +3. Die gleichen Tools erneut ausprobierst, um zu sehen, wie sich das Verhalten je nach Benutzerberechtigungen ändert + +Das demonstriert, wie rollenbasierte Zugangskontrolle (RBAC) in der Praxis funktioniert, wobei verschiedene Benutzer unterschiedliche Zugriffsebenen auf die Systemfunktionen haben. + +![MCP Inspector Todo-Manager-Tool-Ergebnis](/docs-assets/images/tutorials/todo-manager/result.png) + + + + +:::info +Siehe das [MCP Auth Python SDK Repository](https://github.com/mcp-auth/python) für den vollständigen Code des MCP-Servers (OIDC-Version). +::: + + + + +:::info +Siehe das [MCP Auth Node.js SDK Repository](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) für den vollständigen Code des MCP-Servers (OIDC-Version). +::: + + + + +## Abschließende Hinweise \{#closing-notes} + +🎊 Glückwunsch! Du hast das Tutorial erfolgreich abgeschlossen. Lass uns zusammenfassen, was wir gemacht haben: + +- Einen Basis-MCP-Server mit Todo-Management-Tools (`create-todo`, `get-todos`, `delete-todo`) eingerichtet +- Rollenbasierte Zugangskontrolle (RBAC) mit unterschiedlichen Berechtigungsstufen für Benutzer und Admins implementiert +- Den MCP-Server mit einem Autorisierungsserver über MCP Auth integriert +- Den MCP Inspector so konfiguriert, dass Benutzer authentifiziert werden und Zugangstokens mit Berechtigungen zum Aufruf der Tools verwendet werden + +Sieh dir auch andere Tutorials und die Dokumentation an, um das Beste aus MCP Auth herauszuholen. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/README.mdx b/i18n/es/docusaurus-plugin-content-docs/current/README.mdx new file mode 100644 index 0000000..29a931a --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/README.mdx @@ -0,0 +1,297 @@ +--- +sidebar_position: 1 +sidebar_label: Comenzar +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# Comenzar + +:::info Soporte para la especificación de autorización MCP +Esta versión es compatible con la [especificación de autorización MCP (versión 2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization). +::: + + +## Elige un proveedor compatible con OAuth 2.1 u OpenID Connect \{#choose-a-compatible-oauth-2-1-or-openid-connect-provider} + +La especificación MCP tiene [requisitos específicos](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#standards-compliance) para la autorización. El mecanismo de autorización se basa en especificaciones establecidas, implementando un subconjunto seleccionado de sus características para garantizar seguridad e interoperabilidad, manteniendo la simplicidad: + +- OAuth 2.1 IETF DRAFT ([draft-ietf-oauth-v2-1-13](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13)) +- OAuth 2.0 Authorization Server Metadata ([RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)) +- OAuth 2.0 Dynamic Client Registration Protocol ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) +- OAuth 2.0 Protected Resource Metadata ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)) + +Estas especificaciones trabajan juntas para proporcionar un marco de autorización seguro y estandarizado para implementaciones MCP. + +Puedes consultar la [lista de proveedores compatibles con MCP](/provider-list) para ver si tu proveedor es compatible. + +## Instala MCP Auth SDK \{#install-mcp-auth-sdk} + +MCP Auth está disponible tanto para Python como para TypeScript. ¡Avísanos si necesitas soporte para otro lenguaje o framework! + + + + +```bash +pip install mcpauth +``` + +O cualquier otro gestor de paquetes que prefieras, como pipenv o poetry. + + + + +```bash +npm install mcp-auth +``` + +O cualquier otro gestor de paquetes que prefieras, como pnpm o yarn. + + + + +## Inicializa MCP Auth \{#init-mcp-auth} + +El primer paso es definir tu identificador de recurso y configurar el servidor de autorización que será confiable para la autenticación. MCP Auth ahora opera en modo servidor de recursos, conforme a la especificación MCP actualizada que requiere OAuth 2.0 Protected Resource Metadata (RFC 9728). + +Si tu proveedor cumple con: + +- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +Puedes usar la función incorporada para obtener los metadatos e inicializar la instancia de MCP Auth: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType, ResourceServerConfig, ResourceServerMetadata +from mcpauth.utils import fetch_server_config + +# 1. Define tu identificador de recurso y obtén la configuración de su servidor de autorización confiable. +resource_id = "https://api.example.com/notes" +auth_server_config = fetch_server_config("https://auth.logto.io/oidc", AuthServerType.OIDC) + +# 2. Inicializa MCPAuth en modo servidor de recursos. +# `protected_resources` puede ser un solo objeto o una lista para múltiples recursos. +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +// 1. Define tu identificador de recurso y obtén la configuración de su servidor de autorización confiable. +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +// 2. Inicializa MCPAuth en modo servidor de recursos. +// `protectedResources` puede ser un solo objeto o un array para múltiples recursos. +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +Para otras formas de configurar los metadatos del servidor de autorización, incluyendo URLs de metadatos personalizadas, transpile de datos o especificación manual de metadatos, consulta [Otras formas de configurar MCP Auth](./configure-server/mcp-auth.mdx#other-ways). + +## Monta el endpoint de metadatos del recurso protegido \{#mount-the-protected-resource-metadata-endpoint} + +Para cumplir con la especificación MCP actualizada, MCP Auth monta el endpoint OAuth 2.0 Protected Resource Metadata (RFC 9728) en tu servidor MCP. Este endpoint permite a los clientes descubrir: + +- Qué servidores de autorización pueden emitir tokens válidos para tus recursos protegidos +- Qué alcances (scopes) son compatibles para cada recurso +- Otros metadatos requeridos para la validación adecuada de tokens + +La ruta del endpoint se determina automáticamente por el componente de ruta de tu identificador de recurso: + +- **Sin ruta**: `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **Con ruta**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + +El servidor MCP ahora **funciona como un servidor de recursos** que valida tokens y proporciona metadatos sobre sus recursos protegidos, confiando completamente en servidores de autorización externos para la autenticación y autorización. + +Puedes usar el método proporcionado por el SDK para montar este endpoint: + + + + +```python +from starlette.applications import Starlette + +# Monta el router para servir los metadatos del recurso protegido. +# Para el recurso "https://api.example.com" → endpoint: /.well-known/oauth-protected-resource +# Para el recurso "https://api.example.com/notes" → endpoint: /.well-known/oauth-protected-resource/notes +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// Monta el router para servir los metadatos del recurso protegido. +// Para el recurso "https://api.example.com" → endpoint: /.well-known/oauth-protected-resource +// Para el recurso "https://api.example.com/notes" → endpoint: /.well-known/oauth-protected-resource/notes +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + + +## Usa el middleware Bearer auth \{#use-the-bearer-auth-middleware} + +Una vez inicializada la instancia de MCP Auth, puedes aplicar el middleware Bearer auth para proteger tus rutas MCP. El middleware ahora requiere especificar a qué recurso pertenece el endpoint, permitiendo la validación adecuada del token: + +:::note Validación de audiencia (Audience Validation) +El parámetro `audience` es **requerido** por la especificación OAuth 2.0 para una validación segura de tokens. Sin embargo, actualmente es **opcional** para mantener la compatibilidad con servidores de autorización que aún no admiten identificadores de recursos. Por razones de seguridad, **por favor incluye siempre el parámetro audience** cuando sea posible. Las versiones futuras harán obligatoria la validación de audiencia para cumplir completamente con la especificación. +::: + + + + +```python +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount + +# Crea el middleware para proteger tu servidor MCP con la política específica del recurso. +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', + resource=resource_id, + audience=resource_id, # Habilita la validación de audiencia por seguridad + required_scopes=['read:notes'] +)) + +# Monta el router para servir los metadatos del recurso protegido y proteger el servidor MCP. +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # Protege el servidor MCP con el middleware Bearer auth. + Mount("/", app=mcp.sse_app(), middleware=[bearer_auth]), + ], +) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// Monta el router para servir los metadatos del recurso protegido. +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Protege un endpoint de API usando la política específica del recurso. +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, // Habilita la validación de audiencia por seguridad + requiredScopes: ['read:notes'], + }), + (req, res) => { + // Si el token es válido, `req.auth` se rellena con sus reclamos (claims). + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); + +app.listen(3000); +``` + + + + +En los ejemplos anteriores, especificamos el tipo de token `jwt` y el identificador de recurso. El middleware validará automáticamente el token JWT contra los servidores de autorización confiables configurados para ese recurso específico y rellenará la información del usuario autenticado. + +:::info +¿Nunca has oído hablar de JWT (JSON Web Token) antes? No te preocupes, puedes seguir leyendo la documentación y lo explicaremos cuando sea necesario. También puedes consultar [Auth Wiki](https://auth.wiki/jwt) para una introducción rápida. +::: + +Para más información sobre la configuración de Bearer auth, consulta [Configurar Bearer auth](./configure-server/bearer-auth.mdx). + +## Recupera la información de autenticación en tu implementación MCP \{#retrieve-the-auth-info-in-your-mcp-implementation} + +Una vez aplicado el middleware Bearer auth, puedes acceder a la información del usuario autenticado (o identidad) en tu implementación MCP: + + + + +MCP Auth almacenará la información del usuario autenticado en una variable de contexto tras una autenticación exitosa una vez aplicado el middleware Bearer auth. Puedes acceder a ella en tus handlers de herramientas MCP así: + +```python +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP() + +# Inicializa con MCP Auth como se muestra en los ejemplos anteriores +# ... + +@mcp.tool() +def add(a: int, b: int): + """ + Una herramienta que suma dos números. + La información del usuario autenticado estará disponible en el contexto. + """ + auth_info = mcp_auth.auth_info # Accede a la información de autenticación en el contexto actual + if auth_info: + print(f"Usuario autenticado: {auth_info.claims}") + return a + b +``` + + + + +El segundo argumento del handler de la herramienta contendrá el objeto `authInfo`, que incluye la información del usuario autenticado: + +```ts +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { z } from 'zod'; + +const server = new McpServer(/* ... */); + +// Inicializa con MCP Auth como se muestra en los ejemplos anteriores +// ... + +server.tool('add', { a: z.number(), b: z.number() }, async ({ a, b }, { authInfo }) => { + // Ahora puedes usar el objeto `authInfo` para acceder a la información autenticada +}); +``` + + + + +## Próximos pasos \{#next-steps} + +Continúa leyendo para aprender un ejemplo de extremo a extremo sobre cómo integrar MCP Auth con tu servidor MCP, y cómo manejar el flujo de autenticación en los clientes MCP. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx b/i18n/es/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx new file mode 100644 index 0000000..2d3db4c --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx @@ -0,0 +1,280 @@ +--- +sidebar_position: 2 +sidebar_label: Bearer auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# Configura la autenticación Bearer en el servidor MCP + +Con la última especificación de MCP, tu servidor MCP actúa como un **Servidor de Recursos** que valida los tokens de acceso para recursos protegidos. MCP Auth proporciona varias formas de configurar la autorización Bearer: + +- Modo [JWT (JSON Web Token)](https://auth.wiki/jwt): Un método de autorización integrado que verifica JWTs con aserciones de reclamos. +- Modo personalizado: Te permite implementar tu propia lógica de autorización. + +El middleware de autenticación Bearer ahora requiere especificar a qué recurso pertenece el endpoint, permitiendo una validación adecuada del token contra los servidores de autorización configurados. + +## Configura la autenticación Bearer con el modo JWT \{#configure-bearer-auth-with-jwt-mode} + +Si tu proveedor OAuth / OIDC emite JWTs para la autorización, puedes usar el modo JWT integrado en MCP Auth. Verifica la firma del JWT, la expiración y otros reclamos que especifiques; luego, rellena la información de autenticación en el contexto de la solicitud para su posterior procesamiento en tu implementación MCP. + +### Validación de alcances (Scope validation) \{#scope-validation} + +Aquí tienes un ejemplo de la validación básica de alcances: + + + + +```python +from mcpauth import MCPAuth +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP("MyMCPServer") +mcp_auth = MCPAuth( + # Initialize with your auth server config +) +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", # Especifica a qué recurso pertenece este endpoint + audience="https://api.example.com", # Habilita la validación de audiencia para mayor seguridad + required_scopes=["read", "write"] # [!code highlight] +) + +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + /* ... */ +}); +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // Especifica a qué recurso pertenece este endpoint + audience: 'https://api.example.com', // Habilita la validación de audiencia para mayor seguridad + requiredScopes: ['read', 'write'] // [!code highlight] +}); + +app.use('/mcp', bearerAuth, (req, res) => { + // Ahora `req.auth` contiene la información de autenticación + console.log(req.auth); +}); +``` + + + + +En el ejemplo anterior, especificamos que el JWT requiere los alcances (scopes) `read` y `write`. Si el JWT no contiene **ninguno** de estos alcances, la solicitud será rechazada con un error 403 Forbidden. + +### Validación de audiencia (RFC 8707) \{#audience-validation-rfc-8707} + +Para una validación segura del token, siempre debes incluir la validación de audiencia especificando el parámetro `audience`. Esto valida el reclamo `aud` (audiencia) en el JWT para asegurar que el token fue emitido específicamente para el recurso de tu servidor MCP. + +:::note Audience Validation +El parámetro `audience` es **requerido** por la especificación OAuth 2.0 para una validación segura del token. Sin embargo, actualmente es **opcional** para mantener la compatibilidad con servidores de autorización que aún no admiten identificadores de recursos. Por razones de seguridad, **por favor, incluye siempre el parámetro de audiencia** cuando sea posible. Las versiones futuras harán obligatoria la validación de audiencia para cumplir completamente con la especificación. +::: + +El valor de audiencia normalmente debe coincidir con tu identificador de recurso: + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", # Especifica a qué recurso pertenece este endpoint + audience="https://api.example.com", # Habilita la validación de audiencia para mayor seguridad [!code highlight] + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // Especifica a qué recurso pertenece este endpoint + audience: 'https://api.example.com', // Habilita la validación de audiencia para mayor seguridad [!code highlight] + requiredScopes: ['read', 'write'], +}); +``` + + + + +En el ejemplo anterior, MCP Auth validará **tanto** el reclamo `aud` en el JWT como los alcances requeridos. + +### Proporciona opciones personalizadas para la verificación JWT \{#provide-custom-options-to-the-jwt-verification} + +También puedes proporcionar opciones personalizadas a la biblioteca subyacente de verificación JWT: + + + + +En el SDK de Python, usamos [PyJWT](https://pyjwt.readthedocs.io/en/stable/) para la verificación de JWT. Puedes usar las siguientes opciones: + +- `leeway`: Permite cierta tolerancia al verificar el tiempo de expiración del JWT (en segundos). El valor predeterminado es 60 segundos. + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", + audience="https://api.example.com", + required_scopes=["read", "write"], + leeway=10, # Reduce la diferencia de reloj permitiendo 10 segundos de tolerancia [!code highlight] +) +``` + + + + +En el SDK de Node.js, usamos la biblioteca [jose](https://github.com/panva/jose) para la verificación de JWT. Puedes proporcionar las siguientes opciones: + +- `jwtVerify`: Opciones para el proceso de verificación JWT (función `jwtVerify` de `jose`). +- `remoteJwtSet`: Opciones para obtener el conjunto JWT remoto (función `createRemoteJWKSet` de `jose`). + +```ts {5-10} +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', + requiredScopes: ['read', 'write'], + jwtVerify: { + clockTolerance: 60, // Permite una diferencia de reloj de 60 segundos + }, + remoteJwtSet: { + timeoutDuration: 10 * 1000, // 10 segundos de tiempo de espera para obtener el JWT remoto + }, +}); +``` + + + + +## Configura la autenticación Bearer con verificación personalizada \{#configure-bearer-auth-with-custom-verification} + +Si tu proveedor OAuth / OIDC no emite JWTs, o deseas implementar tu propia lógica de autorización, MCP Auth te permite crear una función de verificación personalizada: + +:::info +Dado que el middleware de autenticación Bearer verificará el emisor (`iss`), la audiencia (`aud`) y los alcances requeridos (`scope`) con el resultado de la verificación proporcionado, no es necesario implementar estas comprobaciones en tu función de verificación personalizada. Puedes centrarte en verificar la validez del token (por ejemplo, firma, expiración, etc.) y devolver el objeto de información de autenticación. +::: + + + + +```python +from mcpauth.exceptions import MCPAuthJwtVerificationException, MCPAuthJwtVerificationExceptionCode +from mcpauth.types import AuthInfo + +async def custom_verification(token: str) -> AuthInfo: + # Implementa aquí tu lógica de verificación personalizada + info = await verify_token(token) + if not info: + raise MCPAuthJwtVerificationException( + MCPAuthJwtVerificationExceptionCode.JWT_VERIFICATION_FAILED + ) + return info # Devuelve el objeto de información de autenticación + +bearer_auth = mcp_auth.bearer_auth_middleware( + custom_verification, + resource="https://api.example.com", + audience="https://api.example.com", # Habilita la validación de audiencia para mayor seguridad + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth( + async (token) => { + // Implementa aquí tu lógica de verificación personalizada + const info = await verifyToken(token); + if (!info) { + throw new MCPAuthJwtVerificationError('jwt_verification_failed'); + } + return info; // Devuelve el objeto de información de autenticación + }, + { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // Habilita la validación de audiencia para mayor seguridad + requiredScopes: ['read', 'write'] + } +); +``` + + + + +## Aplica la autenticación Bearer en tu servidor MCP \{#apply-bearer-auth-in-your-mcp-server} + +Para proteger tu servidor MCP con autenticación Bearer, necesitas aplicar el middleware de autenticación Bearer a tu instancia del servidor MCP. + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", + audience="https://api.example.com", # Habilita la validación de audiencia para mayor seguridad + required_scopes=["read", "write"] +) +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```js +const app = express(); +app.use(mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // Habilita la validación de audiencia para mayor seguridad + requiredScopes: ['read', 'write'] +})); +``` + + + + +Esto asegurará que todas las solicitudes entrantes sean autenticadas y autorizadas de acuerdo con la configuración de autenticación Bearer, y la información de autenticación estará disponible en el contexto de la solicitud. + +Luego puedes acceder a la información en tu implementación del servidor MCP: + + + + +```python +@mcp.tool() +async def whoami() -> dict: + # `mcp_auth.auth_info` es el objeto de contexto para la solicitud actual + auth_info = mcp_auth.auth_info + print(f"Usuario autenticado: {auth_info.subject}") + return {"subject": auth_info.subject} +``` + + + + +```js +// `authInfo` se obtendrá del objeto `req.auth` +server.tool('whoami', ({ authInfo }) => { + console.log(`Usuario autenticado: ${authInfo.subject}`); + return { subject: authInfo.subject }; +}); +``` + + + diff --git a/i18n/es/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx b/i18n/es/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx new file mode 100644 index 0000000..d282647 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx @@ -0,0 +1,290 @@ +--- +sidebar_position: 1 +sidebar_label: MCP Auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# Configura MCP Auth en el servidor MCP + +Con la última [Especificación MCP (2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18), tu servidor MCP actúa como un **Servidor de Recursos** que valida los tokens de acceso emitidos por servidores de autorización externos. + +Para configurar MCP Auth, necesitas dos pasos principales: +1. **Configurar los metadatos del servidor de autorización** - Define qué servidores de autorización pueden emitir tokens válidos para tu servidor MCP y guía a los clientes MCP sobre dónde obtener tokens de acceso +2. **Configurar los metadatos del recurso protegido** - Define tu servidor MCP como un recurso protegido con los alcances soportados + +## Paso 1: Configura los metadatos del servidor de autorización \{#configure-authorization-server-metadata} + +### Obtención automática de metadatos \{#automatic-metadata-fetching} + +La forma más sencilla de configurar los metadatos del servidor de autorización es utilizando las funciones integradas que obtienen los metadatos desde URLs bien conocidas. Si tu proveedor cumple con uno de los siguientes estándares: + +- [Metadatos del servidor de autorización OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8414) +- [Descubrimiento de OpenID Connect](https://openid.net/specs/openid-connect-discovery-1_0.html) + +Puedes usar `fetchServerConfig` para recuperar automáticamente los metadatos proporcionando la URL del `issuer`: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +# Obtener los metadatos del servidor de autorización +auth_server_config = fetch_server_config( + "https://auth.logto.io/oidc", + AuthServerType.OIDC # o AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +// Obtener los metadatos del servidor de autorización +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); // o 'oauth' +``` + + + + +Si tu issuer incluye una ruta, el comportamiento difiere ligeramente entre OAuth 2.0 y OpenID Connect: + +- **OAuth 2.0**: La URL bien conocida se añade al **dominio** del issuer. Por ejemplo, si tu issuer es `https://my-project.logto.app/oauth`, la URL bien conocida será `https://auth.logto.io/.well-known/oauth-authorization-server/oauth`. +- **OpenID Connect**: La URL bien conocida se añade directamente al **issuer**. Por ejemplo, si tu issuer es `https://my-project.logto.app/oidc`, la URL bien conocida será `https://auth.logto.io/oidc/.well-known/openid-configuration`. + +### Otras formas de configurar los metadatos del servidor de autorización \{#other-ways} + +#### Transpilación personalizada de datos \{#custom-data-transpilation} + +En algunos casos, los metadatos devueltos por el proveedor pueden no ajustarse al formato esperado. Si estás seguro de que el proveedor es compatible, puedes usar la opción `transpile_data` para modificar los metadatos antes de que se utilicen: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +auth_server_config = fetch_server_config( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfig('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +Esto te permite modificar el objeto de metadatos antes de que sea utilizado por MCP Auth. Por ejemplo, puedes añadir o eliminar campos, cambiar sus valores o convertirlos a un formato diferente. + +#### Obtener metadatos desde una URL específica \{#fetch-metadata-from-a-specific-url} + +Si tu proveedor tiene una URL de metadatos específica en lugar de las estándar, puedes usarla de manera similar: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC # o AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfigByWellKnownUrl } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { type: 'oidc' }); // o 'oauth' +``` + + + + +#### Obtener metadatos desde una URL específica con transpilación personalizada de datos \{#fetch-metadata-from-a-specific-url-with-custom-data-transpilation} + +En algunos casos, la respuesta del proveedor puede estar malformada o no ajustarse al formato de metadatos esperado. Si estás seguro de que el proveedor es compatible, puedes transpilar los metadatos mediante la opción de configuración: + + + + +```python +from mcpauth.config import AuthServerType, fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +#### Proporcionar manualmente los metadatos \{#manually-provide-metadata} + +Si tu proveedor no admite la obtención de metadatos, puedes proporcionar manualmente el objeto de metadatos: + + + + +```python +from mcpauth.config import AuthServerConfig, AuthServerType, AuthorizationServerMetadata + +auth_server_config = AuthServerConfig( + type=AuthServerType.OIDC, # o AuthServerType.OAUTH + metadata=AuthorizationServerMetadata( + issuer='', + authorization_endpoint='', + # ... otros campos de metadatos + ), +) +``` + + + + +```ts +const authServerConfig = { + metadata: { + issuer: '', + // Los campos de metadatos deben estar en camelCase + authorizationEndpoint: '', + // ... otros campos de metadatos + }, + type: 'oidc', // o 'oauth' +}; +``` + + + + +## Paso 2: Configura los metadatos del recurso protegido \{#configure-protected-resource-metadata} + +Después de configurar los metadatos del servidor de autorización, necesitas inicializar MCPAuth como un Servidor de Recursos definiendo los metadatos de tus recursos protegidos. + +Este paso sigue la especificación [RFC 9728 (Metadatos de recursos protegidos OAuth 2.0)](https://datatracker.ietf.org/doc/html/rfc9728) para describir tu servidor MCP como un recurso protegido: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import ResourceServerConfig, ResourceServerMetadata + +# Define tu identificador de recurso +resource_id = "https://api.example.com/notes" + +# Inicializa MCPAuth en modo servidor de recursos +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], # Usando la configuración del Paso 1 + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth } from 'mcp-auth'; + +// Define tu identificador de recurso +const resourceIdentifier = 'https://api.example.com/notes'; + +// Inicializa MCPAuth en modo servidor de recursos +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], // Usando la configuración del Paso 1 + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +Para múltiples recursos, puedes proporcionar un array de recursos protegidos, cada uno con su propia configuración de metadatos. + +La configuración mostrada arriba cubre la configuración básica. Para parámetros de metadatos más avanzados, consulta la [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata). + +## Paso 3: Monta el endpoint de metadatos del recurso protegido \{#mount-the-protected-resource-metadata-endpoint} + +Monta el router para servir el endpoint de metadatos del recurso protegido. La ruta del endpoint se determina automáticamente por el componente de ruta de tu identificador de recurso: + +- **Sin ruta**: `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **Con ruta**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + + + + +```python +from starlette.applications import Starlette +from mcpauth import MCPAuth + +mcp_auth = MCPAuth({/* ... */}) + +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +const mcpAuth = new MCPAuth({/* ... */}); + +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/README.md new file mode 100644 index 0000000..68cf318 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/README.md @@ -0,0 +1,59 @@ +--- +sidebar_label: Node.js SDK +--- + +# Referencia del SDK MCP Auth Node.js + +## Clases {#classes} + +- [MCPAuth](/references/js/classes/MCPAuth.md) +- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) +- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) +- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) +- [MCPAuthError](/references/js/classes/MCPAuthError.md) +- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) + +## Alias de tipos {#type-aliases} + +- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) +- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) +- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) +- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) +- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) +- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) +- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) +- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) +- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) +- [AuthServerType](/references/js/type-aliases/AuthServerType.md) +- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) +- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) +- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) +- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) +- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) +- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) +- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) +- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) +- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) +- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) +- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) +- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) + +## Variables {#variables} + +- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) +- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) +- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) +- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) +- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) +- [defaultValues](/references/js/variables/defaultValues.md) +- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) +- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) +- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) +- [validateServerConfig](/references/js/variables/validateServerConfig.md) + +## Funciones {#functions} + +- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) +- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) +- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) +- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md new file mode 100644 index 0000000..b114e05 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md @@ -0,0 +1,299 @@ +--- +sidebar_label: MCPAuth +--- + +# Clase: MCPAuth + +La clase principal de la librería mcp-auth. Actúa como una fábrica y registro para crear políticas de autenticación para tus recursos protegidos. + +Se inicializa con las configuraciones de tu servidor y proporciona un método `bearerAuth` para generar middleware de Express para la autenticación basada en tokens. + +## Ejemplo {#example} + +### Uso en modo `servidor de recursos` {#usage-in-resource-server-mode} + +Este es el enfoque recomendado para nuevas aplicaciones. + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); + +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +const mcpAuth = new MCPAuth({ + // `protectedResources` puede ser un solo objeto de configuración o un arreglo de ellos. + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); + +// Monta el router para manejar Metadata de Recursos Protegidos +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Protege un endpoint de API para el recurso configurado +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, // Especifica a qué recurso pertenece este endpoint + audience: resourceIdentifier, // Opcionalmente, valida el reclamo 'aud' + requiredScopes: ['read:notes'], + }), + (req, res) => { + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); +``` + +### Uso heredado en modo `servidor de autorización` (Obsoleto) {#legacy-usage-in-authorization-server-mode-deprecated} + +Este enfoque se admite por compatibilidad con versiones anteriores. + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + server: await fetchServerConfig( + 'https://auth.logto.io/oidc', + { type: 'oidc' } + ), +}); + +// Monta el router para manejar Metadata heredada del Servidor de Autorización +app.use(mcpAuth.delegatedRouter()); + +// Protege un endpoint usando la política predeterminada +app.get( + '/mcp', + mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), + (req, res) => { + console.log('Auth info:', req.auth); + // Maneja aquí la solicitud MCP + }, +); +``` + +## Constructores {#constructors} + +### Constructor {#constructor} + +```ts +new MCPAuth(config: MCPAuthConfig): MCPAuth; +``` + +Crea una instancia de MCPAuth. +Valida toda la configuración de antemano para fallar rápidamente en caso de errores. + +#### Parámetros {#parameters} + +##### config {#config} + +[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) + +La configuración de autenticación. + +#### Devuelve {#returns} + +`MCPAuth` + +## Propiedades {#properties} + +### config {#config} + +```ts +readonly config: MCPAuthConfig; +``` + +La configuración de autenticación. + +## Métodos {#methods} + +### bearerAuth() {#bearerauth} + +#### Firma de llamada {#call-signature} + +```ts +bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; +``` + +Crea un manejador Bearer auth (middleware de Express) que verifica el token de acceso en el encabezado +`Authorization` de la solicitud. + +##### Parámetros {#parameters} + +###### verifyAccessToken {#verifyaccesstoken} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +Una función que verifica el token de acceso. Debe aceptar el +token de acceso como una cadena y devolver una promesa (o un valor) que resuelva el +resultado de la verificación. + +**Ver** + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para la definición de tipo de la función +`verifyAccessToken`. + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> + +Configuración opcional para el manejador Bearer auth. + +**Ver** + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para las opciones de configuración disponibles (excluyendo +`verifyAccessToken` y `issuer`). + +##### Devuelve {#returns} + +`RequestHandler` + +Una función middleware de Express que verifica el token de acceso y añade el +resultado de la verificación al objeto de la solicitud (`req.auth`). + +##### Ver {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) para los detalles de implementación y los tipos extendidos del +objeto `req.auth` (`AuthInfo`). + +#### Firma de llamada {#call-signature} + +```ts +bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; +``` + +Crea un manejador Bearer auth (middleware de Express) que verifica el token de acceso en el +encabezado `Authorization` de la solicitud usando un modo de verificación predefinido. + +En el modo `'jwt'`, el manejador creará una función de verificación JWT usando el JWK Set +del JWKS URI del servidor de autorización. + +##### Parámetros {#parameters} + +###### mode {#mode} + +`"jwt"` + +El modo de verificación para el token de acceso. Actualmente, solo se admite 'jwt'. + +**Ver** + +[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) para los modos disponibles. + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` + +Configuración opcional para el manejador Bearer auth, incluyendo opciones de verificación JWT y +opciones remotas de JWK set. + +**Ver** + + - VerifyJwtConfig para las opciones de configuración disponibles para la verificación JWT. + - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para las opciones de configuración disponibles (excluyendo +`verifyAccessToken` y `issuer`). + +##### Devuelve {#returns} + +`RequestHandler` + +Una función middleware de Express que verifica el token de acceso y añade el +resultado de la verificación al objeto de la solicitud (`req.auth`). + +##### Ver {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) para los detalles de implementación y los tipos extendidos del +objeto `req.auth` (`AuthInfo`). + +##### Lanza {#throws} + +si el JWKS URI no se proporciona en los metadatos del servidor al +usar el modo `'jwt'`. + +*** + +### ~~delegatedRouter()~~ {#delegatedrouter} + +```ts +delegatedRouter(): Router; +``` + +Crea un router delegado para servir el endpoint heredado de Metadata del Servidor de Autorización OAuth 2.0 +(`/.well-known/oauth-authorization-server`) con los metadatos proporcionados a la instancia. + +#### Devuelve {#returns} + +`Router` + +Un router que sirve el endpoint de Metadata del Servidor de Autorización OAuth 2.0 con los +metadatos proporcionados a la instancia. + +#### Obsoleto {#deprecated} + +Usa [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) en su lugar. + +#### Ejemplo {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth: MCPAuth; // Supón que esto está inicializado +app.use(mcpAuth.delegatedRouter()); +``` + +#### Lanza {#throws} + +Si se llama en modo `servidor de recursos`. + +*** + +### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} + +```ts +protectedResourceMetadataRouter(): Router; +``` + +Crea un router que sirve el endpoint de Metadata de Recursos Protegidos OAuth 2.0 +para todos los recursos configurados. + +Este router crea automáticamente los endpoints `.well-known` correctos para cada +identificador de recurso proporcionado en tu configuración. + +#### Devuelve {#returns} + +`Router` + +Un router que sirve el endpoint de Metadata de Recursos Protegidos OAuth 2.0. + +#### Lanza {#throws} + +Si se llama en modo `servidor de autorización`. + +#### Ejemplo {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +// Suponiendo que mcpAuth está inicializado con una o más configuraciones de `protectedResources` +const mcpAuth: MCPAuth; +const app = express(); + +// Esto servirá metadata en `/.well-known/oauth-protected-resource/...` +// basado en tus identificadores de recursos. +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md new file mode 100644 index 0000000..25f261e --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthAuthServerError +--- + +# Clase: MCPAuthAuthServerError + +Error lanzado cuando hay un problema con el servidor de autorización remoto. + +## Hereda de {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Constructores {#constructors} + +### Constructor {#constructor} + +```ts +new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; +``` + +#### Parámetros {#parameters} + +##### code {#code} + +[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### Devuelve {#returns} + +`MCPAuthAuthServerError` + +#### Sobrescribe {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propiedades {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: AuthServerErrorCode; +``` + +El código de error en formato snake_case. + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthAuthServerError'; +``` + +#### Sobrescribe {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +La propiedad `Error.stackTraceLimit` especifica el número de marcos de pila +recopilados por un seguimiento de pila (ya sea generado por `new Error().stack` o +`Error.captureStackTrace(obj)`). + +El valor predeterminado es `10`, pero se puede establecer en cualquier número válido de JavaScript. Los cambios +afectarán a cualquier seguimiento de pila capturado _después_ de que se haya cambiado el valor. + +Si se establece en un valor que no es un número, o en un número negativo, los seguimientos de pila +no capturarán ningún marco. + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Métodos {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Convierte el error a un formato JSON amigable para respuestas HTTP. + +#### Parámetros {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Indica si se debe incluir la causa del error en la respuesta JSON. +Por defecto es `false`. + +#### Devuelve {#returns} + +`Record`\<`string`, `unknown`\> + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Crea una propiedad `.stack` en `targetObject`, que al accederse devuelve +una cadena que representa la ubicación en el código en la que +se llamó a `Error.captureStackTrace()`. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Similar a `new Error().stack` +``` + +La primera línea del seguimiento estará precedida por +`${myObject.name}: ${myObject.message}`. + +El argumento opcional `constructorOpt` acepta una función. Si se proporciona, todos los marcos +por encima de `constructorOpt`, incluido `constructorOpt`, se omitirán del +seguimiento de pila generado. + +El argumento `constructorOpt` es útil para ocultar detalles de implementación +de la generación de errores al usuario. Por ejemplo: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Crear un error sin seguimiento de pila para evitar calcular el seguimiento dos veces. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Captura el seguimiento de pila por encima de la función b + Error.captureStackTrace(error, b); // Ni la función c ni b se incluyen en el seguimiento de pila + throw error; +} + +a(); +``` + +#### Parámetros {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Devuelve {#returns} + +`void` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parámetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Devuelve {#returns} + +`any` + +#### Ver {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md new file mode 100644 index 0000000..aab8847 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md @@ -0,0 +1,247 @@ +--- +sidebar_label: MCPAuthBearerAuthError +--- + +# Clase: MCPAuthBearerAuthError + +Error lanzado cuando hay un problema al autenticar con tokens Bearer. + +## Hereda de {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Constructores {#constructors} + +### Constructor {#constructor} + +```ts +new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; +``` + +#### Parámetros {#parameters} + +##### code {#code} + +[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) + +##### cause? {#cause} + +[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) + +#### Devuelve {#returns} + +`MCPAuthBearerAuthError` + +#### Sobrescribe {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propiedades {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: MCPAuthBearerAuthErrorDetails; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: BearerAuthErrorCode; +``` + +El código de error en formato snake_case. + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthBearerAuthError'; +``` + +#### Sobrescribe {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +La propiedad `Error.stackTraceLimit` especifica el número de marcos de pila +recopilados por un seguimiento de pila (ya sea generado por `new Error().stack` o +`Error.captureStackTrace(obj)`). + +El valor predeterminado es `10`, pero se puede establecer en cualquier número válido de JavaScript. Los cambios +afectarán a cualquier seguimiento de pila capturado _después_ de que el valor haya sido cambiado. + +Si se establece en un valor que no es un número, o en un número negativo, los seguimientos de pila +no capturarán ningún marco. + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Métodos {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Convierte el error a un formato JSON amigable para respuestas HTTP. + +#### Parámetros {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Indica si se debe incluir la causa del error en la respuesta JSON. +Por defecto es `false`. + +#### Devuelve {#returns} + +`Record`\<`string`, `unknown`\> + +#### Sobrescribe {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Crea una propiedad `.stack` en `targetObject`, que al accederse devuelve +una cadena que representa la ubicación en el código en la que +se llamó a `Error.captureStackTrace()`. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Similar a `new Error().stack` +``` + +La primera línea del seguimiento estará precedida por +`${myObject.name}: ${myObject.message}`. + +El argumento opcional `constructorOpt` acepta una función. Si se proporciona, todos los marcos +por encima de `constructorOpt`, incluido `constructorOpt`, se omitirán del seguimiento de pila generado. + +El argumento `constructorOpt` es útil para ocultar detalles de implementación +de la generación de errores al usuario. Por ejemplo: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Crear un error sin seguimiento de pila para evitar calcular el seguimiento dos veces. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Capturar el seguimiento de pila por encima de la función b + Error.captureStackTrace(error, b); // Ni la función c ni b se incluyen en el seguimiento de pila + throw error; +} + +a(); +``` + +#### Parámetros {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Devuelve {#returns} + +`void` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parámetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Devuelve {#returns} + +`any` + +#### Ver {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md new file mode 100644 index 0000000..4104aba --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md @@ -0,0 +1,251 @@ +--- +sidebar_label: MCPAuthConfigError +--- + +# Clase: MCPAuthConfigError + +Error lanzado cuando hay un problema de configuración con mcp-auth. + +## Hereda de {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Constructores {#constructors} + +### Constructor {#constructor} + +```ts +new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; +``` + +#### Parámetros {#parameters} + +##### code {#code} + +`string` + +El código de error en formato snake_case. + +##### message {#message} + +`string` + +Una descripción legible para humanos del error. + +#### Devuelve {#returns} + +`MCPAuthConfigError` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propiedades {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +El código de error en formato snake_case. + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthConfigError'; +``` + +#### Sobrescribe {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +La propiedad `Error.stackTraceLimit` especifica el número de marcos de pila +recopilados por un seguimiento de pila (ya sea generado por `new Error().stack` o +`Error.captureStackTrace(obj)`). + +El valor predeterminado es `10`, pero se puede establecer en cualquier número válido de JavaScript. Los cambios +afectarán cualquier seguimiento de pila capturado _después_ de que el valor haya sido cambiado. + +Si se establece en un valor que no es un número, o en un número negativo, los seguimientos de pila +no capturarán ningún marco. + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Métodos {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Convierte el error a un formato JSON apto para respuestas HTTP. + +#### Parámetros {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Indica si se debe incluir la causa del error en la respuesta JSON. +Por defecto es `false`. + +#### Devuelve {#returns} + +`Record`\<`string`, `unknown`\> + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Crea una propiedad `.stack` en `targetObject`, que al accederse devuelve +una cadena que representa la ubicación en el código en la que +se llamó a `Error.captureStackTrace()`. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Similar a `new Error().stack` +``` + +La primera línea del seguimiento estará precedida por +`${myObject.name}: ${myObject.message}`. + +El argumento opcional `constructorOpt` acepta una función. Si se proporciona, todos los marcos +por encima de `constructorOpt`, incluido `constructorOpt`, se omitirán del seguimiento de pila generado. + +El argumento `constructorOpt` es útil para ocultar detalles de implementación +de la generación del error al usuario. Por ejemplo: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Crear un error sin seguimiento de pila para evitar calcular el seguimiento dos veces. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Captura el seguimiento de pila por encima de la función b + Error.captureStackTrace(error, b); // Ni la función c ni b se incluyen en el seguimiento de pila + throw error; +} + +a(); +``` + +#### Parámetros {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Devuelve {#returns} + +`void` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parámetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Devuelve {#returns} + +`any` + +#### Ver {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md new file mode 100644 index 0000000..549ca11 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md @@ -0,0 +1,269 @@ +--- +sidebar_label: MCPAuthError +--- + +# Clase: MCPAuthError + +Clase base para todos los errores de mcp-auth. + +Proporciona una forma estandarizada de manejar errores relacionados con la Autenticación (Authentication) y Autorización (Authorization) de MCP. + +## Hereda de {#extends} + +- `Error` + +## Extendida por {#extended-by} + +- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) +- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) +- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) +- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) + +## Constructores {#constructors} + +### Constructor {#constructor} + +```ts +new MCPAuthError(code: string, message: string): MCPAuthError; +``` + +#### Parámetros {#parameters} + +##### code {#code} + +`string` + +El código de error en formato snake_case. + +##### message {#message} + +`string` + +Una descripción legible para humanos del error. + +#### Devuelve {#returns} + +`MCPAuthError` + +#### Sobrescribe {#overrides} + +```ts +Error.constructor +``` + +## Propiedades {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### Heredado de {#inherited-from} + +```ts +Error.cause +``` + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +El código de error en formato snake_case. + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Heredado de {#inherited-from} + +```ts +Error.message +``` + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthError'; +``` + +#### Sobrescribe {#overrides} + +```ts +Error.name +``` + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Heredado de {#inherited-from} + +```ts +Error.stack +``` + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +La propiedad `Error.stackTraceLimit` especifica el número de marcos de pila +recopilados por un seguimiento de pila (ya sea generado por `new Error().stack` o +`Error.captureStackTrace(obj)`). + +El valor predeterminado es `10`, pero puede establecerse en cualquier número válido de JavaScript. Los cambios +afectarán a cualquier seguimiento de pila capturado _después_ de que se haya cambiado el valor. + +Si se establece en un valor que no es un número, o en un número negativo, los seguimientos de pila +no capturarán ningún marco. + +#### Heredado de {#inherited-from} + +```ts +Error.stackTraceLimit +``` + +## Métodos {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Convierte el error a un formato JSON amigable para respuestas HTTP. + +#### Parámetros {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Indica si se debe incluir la causa del error en la respuesta JSON. +Por defecto es `false`. + +#### Devuelve {#returns} + +`Record`\<`string`, `unknown`\> + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Crea una propiedad `.stack` en `targetObject`, que al accederse devuelve +una cadena que representa la ubicación en el código en la que +se llamó a `Error.captureStackTrace()`. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Similar a `new Error().stack` +``` + +La primera línea del seguimiento estará precedida por +`${myObject.name}: ${myObject.message}`. + +El argumento opcional `constructorOpt` acepta una función. Si se proporciona, todos los marcos +por encima de `constructorOpt`, incluido `constructorOpt`, se omitirán del +seguimiento de pila generado. + +El argumento `constructorOpt` es útil para ocultar detalles de implementación +de la generación de errores al usuario. Por ejemplo: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Crear un error sin seguimiento de pila para evitar calcular el seguimiento dos veces. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Capturar el seguimiento de pila por encima de la función b + Error.captureStackTrace(error, b); // Ni la función c ni b se incluyen en el seguimiento de pila + throw error; +} + +a(); +``` + +#### Parámetros {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Devuelve {#returns} + +`void` + +#### Heredado de {#inherited-from} + +```ts +Error.captureStackTrace +``` + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parámetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Devuelve {#returns} + +`any` + +#### Ver {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Heredado de {#inherited-from} + +```ts +Error.prepareStackTrace +``` \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md new file mode 100644 index 0000000..ba500ee --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthTokenVerificationError +--- + +# Clase: MCPAuthTokenVerificationError + +Error lanzado cuando hay un problema al verificar tokens. + +## Hereda de {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Constructores {#constructors} + +### Constructor {#constructor} + +```ts +new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; +``` + +#### Parámetros {#parameters} + +##### code {#code} + +[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### Devuelve {#returns} + +`MCPAuthTokenVerificationError` + +#### Sobrescribe {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propiedades {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: MCPAuthTokenVerificationErrorCode; +``` + +El código de error en formato snake_case. + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthTokenVerificationError'; +``` + +#### Sobrescribe {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +La propiedad `Error.stackTraceLimit` especifica el número de marcos de pila +recopilados por un seguimiento de pila (ya sea generado por `new Error().stack` o +`Error.captureStackTrace(obj)`). + +El valor predeterminado es `10`, pero se puede establecer en cualquier número válido de JavaScript. Los cambios +afectarán cualquier seguimiento de pila capturado _después_ de que se haya cambiado el valor. + +Si se establece en un valor que no es un número, o en un número negativo, los seguimientos de pila +no capturarán ningún marco. + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Métodos {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Convierte el error a un formato JSON apto para respuestas HTTP. + +#### Parámetros {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Indica si se debe incluir la causa del error en la respuesta JSON. +Por defecto es `false`. + +#### Devuelve {#returns} + +`Record`\<`string`, `unknown`\> + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Crea una propiedad `.stack` en `targetObject`, que al accederse devuelve +una cadena que representa la ubicación en el código en la que +se llamó a `Error.captureStackTrace()`. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Similar a `new Error().stack` +``` + +La primera línea del seguimiento estará precedida por +`${myObject.name}: ${myObject.message}`. + +El argumento opcional `constructorOpt` acepta una función. Si se proporciona, todos los marcos +por encima de `constructorOpt`, incluido `constructorOpt`, se omitirán del +seguimiento de pila generado. + +El argumento `constructorOpt` es útil para ocultar detalles de implementación +de la generación de errores al usuario. Por ejemplo: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Crear un error sin seguimiento de pila para evitar calcular el seguimiento dos veces. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Captura el seguimiento de pila por encima de la función b + Error.captureStackTrace(error, b); // Ni la función c ni b se incluyen en el seguimiento de pila + throw error; +} + +a(); +``` + +#### Parámetros {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Devuelve {#returns} + +`void` + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parámetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Devuelve {#returns} + +`any` + +#### Ver {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Heredado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md new file mode 100644 index 0000000..717cdeb --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md @@ -0,0 +1,43 @@ +--- +sidebar_label: createVerifyJwt +--- + +# Función: createVerifyJwt() + +```ts +function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; +``` + +Crea una función para verificar tokens de acceso JWT utilizando la función de recuperación de clave proporcionada y opciones. + +## Parámetros {#parameters} + +### getKey {#getkey} + +`JWTVerifyGetKey` + +La función para recuperar la clave utilizada para verificar el JWT. + +**Ver** + +JWTVerifyGetKey para la definición de tipo de la función de recuperación de clave. + +### options? {#options} + +`JWTVerifyOptions` + +Opciones opcionales de verificación de JWT. + +**Ver** + +JWTVerifyOptions para la definición de tipo de las opciones. + +## Devuelve {#returns} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +Una función que verifica tokens de acceso JWT (Access tokens) y devuelve un objeto AuthInfo si el token es válido. Requiere que el JWT contenga los campos `iss`, `client_id` y `sub` en su payload, y opcionalmente puede contener los campos `scope` o `scopes`. La función utiliza la librería `jose` internamente para realizar la verificación del JWT. + +## Ver {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para la definición de tipo de la función devuelta. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md new file mode 100644 index 0000000..5a3e174 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md @@ -0,0 +1,60 @@ +--- +sidebar_label: fetchServerConfig +--- + +# Función: fetchServerConfig() + +```ts +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +``` + +Obtiene la configuración del servidor según el emisor (Issuer) y el tipo de servidor de autorización (Authorization). + +Esta función determina automáticamente la URL well-known en función del tipo de servidor, ya que los servidores OAuth y OpenID Connect tienen convenciones diferentes para sus endpoints de metadatos. + +## Parámetros {#parameters} + +### issuer {#issuer} + +`string` + +La URL del emisor (Issuer) del servidor de autorización (Authorization). + +### config {#config} + +`ServerMetadataConfig` + +El objeto de configuración que contiene el tipo de servidor y una función de transpilación opcional. + +## Devuelve {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +Una promesa que se resuelve con la configuración del servidor. + +## Ver también {#see} + + - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) para la implementación subyacente. + - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) para la especificación de metadatos del servidor de autorización OAuth 2.0 (Authorization). + - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) para la especificación de descubrimiento de OpenID Connect. + +## Ejemplo {#example} + +```ts +import { fetchServerConfig } from 'mcp-auth'; +// Obteniendo la configuración del servidor OAuth +// Esto obtendrá los metadatos de `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` +const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); + +// Obteniendo la configuración del servidor OpenID Connect +// Esto obtendrá los metadatos de `https://auth.logto.io/oidc/.well-known/openid-configuration` +const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); +``` + +## Lanza {#throws} + +si la operación de obtención falla. + +## Lanza {#throws} + +si los metadatos del servidor son inválidos o no coinciden con la especificación MCP. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md new file mode 100644 index 0000000..856985f --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md @@ -0,0 +1,41 @@ +--- +sidebar_label: fetchServerConfigByWellKnownUrl +--- + +# Función: fetchServerConfigByWellKnownUrl() + +```ts +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +``` + +Obtiene la configuración del servidor desde la URL well-known proporcionada y la valida según la especificación MCP. + +Si los metadatos del servidor no se ajustan al esquema esperado, pero estás seguro de que son compatibles, puedes definir una función `transpileData` para transformar los metadatos al formato esperado. + +## Parámetros {#parameters} + +### wellKnownUrl {#wellknownurl} + +La URL well-known desde la que obtener la configuración del servidor. Puede ser una cadena de texto o un objeto URL. + +`string` | `URL` + +### config {#config} + +`ServerMetadataConfig` + +El objeto de configuración que contiene el tipo de servidor y una función opcional de transformación. + +## Devuelve {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +Una promesa que se resuelve con la configuración del servidor. + +## Lanza {#throws} + +si la operación de obtención falla. + +## Lanza {#throws} + +si los metadatos del servidor son inválidos o no coinciden con la especificación MCP. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md new file mode 100644 index 0000000..3b21e6a --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md @@ -0,0 +1,41 @@ +--- +sidebar_label: handleBearerAuth +--- + +# Función: handleBearerAuth() + +```ts +function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; +``` + +Crea una función middleware para manejar la autenticación Bearer en una aplicación Express. + +Este middleware extrae el token Bearer del encabezado `Authorization`, lo verifica usando la función +`verifyAccessToken` proporcionada y comprueba el emisor (Issuer), la audiencia (Audience) y los alcances (Scopes) requeridos. + +- Si el token es válido, añade la información de autenticación al atributo `request.auth`; +si no, responde con un mensaje de error apropiado. +- Si la verificación del token de acceso (Access token) falla, responde con un error 401 No autorizado. +- Si el token no tiene los alcances (Scopes) requeridos, responde con un error 403 Prohibido. +- Si ocurren errores inesperados durante el proceso de autenticación (Authentication), el middleware los volverá a lanzar. + +**Nota:** El objeto `request.auth` contendrá campos extendidos en comparación con la interfaz estándar +AuthInfo definida en el módulo `@modelcontextprotocol/sdk`. Consulta la interfaz extendida en este archivo para más detalles. + +## Parámetros {#parameters} + +### param0 {#param0} + +[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) + +Configuración para el manejador de autenticación Bearer. + +## Retorna {#returns} + +`RequestHandler` + +Una función middleware para Express que maneja la autenticación Bearer. + +## Consulta {#see} + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para las opciones de configuración. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md new file mode 100644 index 0000000..4ff9f1b --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md @@ -0,0 +1,48 @@ +--- +sidebar_label: AuthServerConfig +--- + +# Alias de tipo: AuthServerConfig + +```ts +type AuthServerConfig = { + metadata: CamelCaseAuthorizationServerMetadata; + type: AuthServerType; +}; +``` + +Configuración para el servidor de autorización remoto integrado con el servidor MCP. + +## Propiedades {#properties} + +### metadata {#metadata} + +```ts +metadata: CamelCaseAuthorizationServerMetadata; +``` + +Los metadatos del servidor de autorización (authorization server), que deben cumplir con la especificación MCP +(basada en los metadatos del servidor de autorización OAuth 2.0). + +Estos metadatos normalmente se obtienen del endpoint well-known del servidor (metadatos del servidor de autorización OAuth 2.0 o descubrimiento de OpenID Connect); también pueden proporcionarse directamente en la configuración si el servidor no admite dichos endpoints. + +**Nota:** Los metadatos deben estar en formato camelCase según lo prefiere la librería mcp-auth. + +#### Ver {#see} + + - [Metadatos del servidor de autorización OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8414) + - [Descubrimiento de OpenID Connect](https://openid.net/specs/openid-connect-discovery-1_0.html) + +*** + +### type {#type} + +```ts +type: AuthServerType; +``` + +El tipo de servidor de autorización (authorization server). + +#### Ver {#see} + +[AuthServerType](/references/js/type-aliases/AuthServerType.md) para los valores posibles. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md new file mode 100644 index 0000000..0110b48 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md @@ -0,0 +1,45 @@ +--- +sidebar_label: AuthServerConfigError +--- + +# Alias de tipo: AuthServerConfigError + +```ts +type AuthServerConfigError = { + cause?: Error; + code: AuthServerConfigErrorCode; + description: string; +}; +``` + +Representa un error que ocurre durante la validación de los metadatos del servidor de autorización (authorization server). + +## Propiedades {#properties} + +### cause? {#cause} + +```ts +optional cause: Error; +``` + +Una causa opcional del error, normalmente una instancia de `Error` que proporciona más contexto. + +*** + +### code {#code} + +```ts +code: AuthServerConfigErrorCode; +``` + +El código que representa el error de validación específico. + +*** + +### description {#description} + +```ts +description: string; +``` + +Una descripción legible para humanos del error. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md new file mode 100644 index 0000000..8ff6e61 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: AuthServerConfigErrorCode +--- + +# Alias de tipo: AuthServerConfigErrorCode + +```ts +type AuthServerConfigErrorCode = + | "invalid_server_metadata" + | "code_response_type_not_supported" + | "authorization_code_grant_not_supported" + | "pkce_not_supported" + | "s256_code_challenge_method_not_supported"; +``` + +Los códigos para los errores que pueden ocurrir al validar los metadatos del servidor de autorización. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md new file mode 100644 index 0000000..b2f60ad --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md @@ -0,0 +1,34 @@ +--- +sidebar_label: AuthServerConfigWarning +--- + +# Alias de tipo: AuthServerConfigWarning + +```ts +type AuthServerConfigWarning = { + code: AuthServerConfigWarningCode; + description: string; +}; +``` + +Representa una advertencia que ocurre durante la validación de los metadatos del servidor de autorización (authorization server). + +## Propiedades {#properties} + +### code {#code} + +```ts +code: AuthServerConfigWarningCode; +``` + +El código que representa la advertencia de validación específica. + +*** + +### description {#description} + +```ts +description: string; +``` + +Una descripción legible para humanos de la advertencia. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md new file mode 100644 index 0000000..a55f500 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerConfigWarningCode +--- + +# Alias de tipo: AuthServerConfigWarningCode + +```ts +type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; +``` + +Los códigos para advertencias que pueden ocurrir al validar los metadatos del servidor de autorización (authorization server metadata). \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md new file mode 100644 index 0000000..98ed927 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md @@ -0,0 +1,12 @@ +--- +sidebar_label: AuthServerErrorCode +--- + +# Alias de tipo: AuthServerErrorCode + +```ts +type AuthServerErrorCode = + | "invalid_server_metadata" + | "invalid_server_config" + | "missing_jwks_uri"; +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md new file mode 100644 index 0000000..e251a2a --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md @@ -0,0 +1,31 @@ +--- +sidebar_label: AuthServerModeConfig +--- + +# Alias de tipo: ~~AuthServerModeConfig~~ + +```ts +type AuthServerModeConfig = { + server: AuthServerConfig; +}; +``` + +Configuración para el modo de servidor de autorización heredado, MCP. + +## Obsoleto {#deprecated} + +Utiliza la configuración `ResourceServerModeConfig` en su lugar. + +## Propiedades {#properties} + +### ~~server~~ {#server} + +```ts +server: AuthServerConfig; +``` + +La configuración del único servidor de autorización. + +#### Obsoleto {#deprecated} + +Utiliza la configuración `protectedResources` en su lugar. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md new file mode 100644 index 0000000..4a6ba45 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md @@ -0,0 +1,17 @@ +--- +sidebar_label: AuthServerSuccessCode +--- + +# Alias de tipo: AuthServerSuccessCode + +```ts +type AuthServerSuccessCode = + | "server_metadata_valid" + | "dynamic_registration_supported" + | "pkce_supported" + | "s256_code_challenge_method_supported" + | "authorization_code_grant_supported" + | "code_response_type_supported"; +``` + +Los códigos para la validación exitosa de los metadatos del servidor de autorización. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md new file mode 100644 index 0000000..9b36c07 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerType +--- + +# Alias de tipo: AuthServerType + +```ts +type AuthServerType = "oauth" | "oidc"; +``` + +El tipo del servidor de autorización (authorization server). Esta información debe ser proporcionada por la configuración del servidor y señala si el servidor es un servidor de autorización OAuth 2.0 o OpenID Connect (OIDC). \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md new file mode 100644 index 0000000..868428f --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md @@ -0,0 +1,236 @@ +--- +sidebar_label: AuthorizationServerMetadata +--- + +# Alias de tipo: AuthorizationServerMetadata + +```ts +type AuthorizationServerMetadata = { + authorization_endpoint: string; + code_challenge_methods_supported?: string[]; + grant_types_supported?: string[]; + introspection_endpoint?: string; + introspection_endpoint_auth_methods_supported?: string[]; + introspection_endpoint_auth_signing_alg_values_supported?: string[]; + issuer: string; + jwks_uri?: string; + op_policy_uri?: string; + op_tos_uri?: string; + registration_endpoint?: string; + response_modes_supported?: string[]; + response_types_supported: string[]; + revocation_endpoint?: string; + revocation_endpoint_auth_methods_supported?: string[]; + revocation_endpoint_auth_signing_alg_values_supported?: string[]; + scopes_supported?: string[]; + service_documentation?: string; + token_endpoint: string; + token_endpoint_auth_methods_supported?: string[]; + token_endpoint_auth_signing_alg_values_supported?: string[]; + ui_locales_supported?: string[]; + userinfo_endpoint?: string; +}; +``` + +Esquema para los metadatos del servidor de autorización OAuth 2.0 según lo definido en RFC 8414. + +## Declaración de tipo {#type-declaration} + +### authorization\_endpoint {#authorization-endpoint} + +```ts +authorization_endpoint: string; +``` + +URL del endpoint de autorización del servidor de autorización [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. +Esto es OBLIGATORIO a menos que no se admitan tipos de concesión que utilicen el endpoint de autorización. + +#### Ver {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.1 + +### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} + +```ts +optional code_challenge_methods_supported: string[]; +``` + +Arreglo JSON que contiene una lista de métodos de desafío de código Proof Key for Code Exchange (PKCE) +[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] admitidos por este servidor de autorización. + +### grant\_types\_supported? {#grant-types-supported} + +```ts +optional grant_types_supported: string[]; +``` + +Arreglo JSON que contiene una lista de los valores de tipo de concesión OAuth 2.0 que este servidor de autorización +admite. Los valores del arreglo son los mismos que se usan con el parámetro `grant_types` +definido por el "Protocolo de Registro Dinámico de Clientes OAuth 2.0" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. +Si se omite, el valor predeterminado es `["authorization_code", "implicit"]`. + +### introspection\_endpoint? {#introspection-endpoint} + +```ts +optional introspection_endpoint: string; +``` + +URL del endpoint de introspección OAuth 2.0 del servidor de autorización +[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. + +### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} + +```ts +optional introspection_endpoint_auth_methods_supported: string[]; +``` + +### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} + +```ts +optional introspection_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +El identificador de emisor (Issuer) del servidor de autorización, que es una URL que utiliza el esquema `https` y +no tiene componentes de consulta ni fragmentos. + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +URL del documento JWK Set del servidor de autorización [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)]. +El documento referenciado contiene la(s) clave(s) de firma que el cliente utiliza para validar +firmas del servidor de autorización. Esta URL DEBE usar el esquema `https`. + +### op\_policy\_uri? {#op-policy-uri} + +```ts +optional op_policy_uri: string; +``` + +### op\_tos\_uri? {#op-tos-uri} + +```ts +optional op_tos_uri: string; +``` + +### registration\_endpoint? {#registration-endpoint} + +```ts +optional registration_endpoint: string; +``` + +URL del endpoint de registro dinámico de clientes OAuth 2.0 del servidor de autorización +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. + +### response\_modes\_supported? {#response-modes-supported} + +```ts +optional response_modes_supported: string[]; +``` + +Arreglo JSON que contiene una lista de los valores `response_mode` de OAuth 2.0 que este +servidor de autorización admite, según lo especificado en "Prácticas de codificación de tipo de respuesta múltiple de OAuth 2.0" +[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]. + +Si se omite, el valor predeterminado es `["query", "fragment"]`. El valor de modo de respuesta `"form_post"` también está definido en "OAuth 2.0 Form Post Response Mode" +[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]. + +### response\_types\_supported {#response-types-supported} + +```ts +response_types_supported: string[]; +``` + +Arreglo JSON que contiene una lista de los valores `response_type` de OAuth 2.0 que este servidor de autorización +admite. Los valores del arreglo son los mismos que se usan con el parámetro `response_types` +definido por el "Protocolo de Registro Dinámico de Clientes OAuth 2.0" +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. + +### revocation\_endpoint? {#revocation-endpoint} + +```ts +optional revocation_endpoint: string; +``` + +URL del endpoint de revocación OAuth 2.0 del servidor de autorización +[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. + +### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} + +```ts +optional revocation_endpoint_auth_methods_supported: string[]; +``` + +### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} + +```ts +optional revocation_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +Arreglo JSON que contiene una lista de los valores `scope` de OAuth 2.0 que este servidor de autorización +admite. +[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] + +### service\_documentation? {#service-documentation} + +```ts +optional service_documentation: string; +``` + +### token\_endpoint {#token-endpoint} + +```ts +token_endpoint: string; +``` + +URL del endpoint de token del servidor de autorización [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. +Esto es OBLIGATORIO a menos que solo se admita el tipo de concesión implícita. + +#### Ver {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.2 + +### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} + +```ts +optional token_endpoint_auth_methods_supported: string[]; +``` + +### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} + +```ts +optional token_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### ui\_locales\_supported? {#ui-locales-supported} + +```ts +optional ui_locales_supported: string[]; +``` + +### userinfo\_endpoint? {#userinfo-endpoint} + +```ts +optional userinfo_endpoint: string; +``` + +URL del [endpoint userinfo](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) de OpenID Connect. +Este endpoint se utiliza para recuperar información sobre el usuario autenticado. + +## Ver {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md new file mode 100644 index 0000000..ad587e9 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md @@ -0,0 +1,117 @@ +--- +sidebar_label: BearerAuthConfig +--- + +# Alias de tipo: BearerAuthConfig + +```ts +type BearerAuthConfig = { + audience?: string; + issuer: | string + | ValidateIssuerFunction; + requiredScopes?: string[]; + resource?: string; + showErrorDetails?: boolean; + verifyAccessToken: VerifyAccessTokenFunction; +}; +``` + +## Propiedades {#properties} + +### audience? {#audience} + +```ts +optional audience: string; +``` + +La audiencia esperada del token de acceso (reclamo `aud`). Normalmente, este es el servidor de recursos +(API) para el que está destinado el token. Si no se proporciona, se omitirá la comprobación de audiencia. + +**Nota:** Si tu servidor de autorización no admite Indicadores de recurso (RFC 8707), +puedes omitir este campo ya que la audiencia puede no ser relevante. + +#### Ver {#see} + +https://datatracker.ietf.org/doc/html/rfc8707 + +*** + +### issuer {#issuer} + +```ts +issuer: + | string + | ValidateIssuerFunction; +``` + +Una cadena que representa un emisor válido, o una función para validar el emisor del token de acceso. + +Si se proporciona una cadena, se usará como el valor de emisor esperado para la comparación directa. + +Si se proporciona una función, debe validar el emisor según las reglas en +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md). + +#### Ver {#see} + +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) para más detalles sobre la función de validación. + +*** + +### requiredScopes? {#requiredscopes} + +```ts +optional requiredScopes: string[]; +``` + +Un arreglo de alcances (scopes) requeridos que el token de acceso debe tener. Si el token no contiene +todos estos alcances, se lanzará un error. + +**Nota:** El manejador comprobará el reclamo `scope` en el token, que puede ser una cadena separada por espacios +o un arreglo de cadenas, dependiendo de la implementación del servidor de autorización. Si el reclamo `scope` no está presente, el manejador comprobará el reclamo `scopes` +si está disponible. + +*** + +### resource? {#resource} + +```ts +optional resource: string; +``` + +El identificador del recurso protegido. Cuando se proporciona, el manejador usará los +servidores de autorización configurados para este recurso para validar el token recibido. +Es obligatorio cuando se utiliza el manejador con una configuración de `protectedResources`. + +*** + +### showErrorDetails? {#showerrordetails} + +```ts +optional showErrorDetails: boolean; +``` + +Indica si se debe mostrar información detallada de errores en la respuesta. Esto es útil para depuración +durante el desarrollo, pero debe deshabilitarse en producción para evitar la filtración de información sensible. + +#### Valor por defecto {#default} + +```ts +false +``` + +*** + +### verifyAccessToken {#verifyaccesstoken} + +```ts +verifyAccessToken: VerifyAccessTokenFunction; +``` + +Tipo de función para verificar un token de acceso. + +Esta función debe lanzar un [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) si el token es inválido, +o devolver un objeto AuthInfo si el token es válido. + +#### Ver {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para más detalles. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md new file mode 100644 index 0000000..f752c9f --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: BearerAuthErrorCode +--- + +# Alias de tipo: BearerAuthErrorCode + +```ts +type BearerAuthErrorCode = + | "missing_auth_header" + | "invalid_auth_header_format" + | "missing_bearer_token" + | "invalid_issuer" + | "invalid_audience" + | "missing_required_scopes" + | "invalid_token"; +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md new file mode 100644 index 0000000..78e386e --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md @@ -0,0 +1,179 @@ +--- +sidebar_label: CamelCaseAuthorizationServerMetadata +--- + +# Alias de tipo: CamelCaseAuthorizationServerMetadata + +```ts +type CamelCaseAuthorizationServerMetadata = { + authorizationEndpoint: string; + codeChallengeMethodsSupported?: string[]; + grantTypesSupported?: string[]; + introspectionEndpoint?: string; + introspectionEndpointAuthMethodsSupported?: string[]; + introspectionEndpointAuthSigningAlgValuesSupported?: string[]; + issuer: string; + jwksUri?: string; + opPolicyUri?: string; + opTosUri?: string; + registrationEndpoint?: string; + responseModesSupported?: string[]; + responseTypesSupported: string[]; + revocationEndpoint?: string; + revocationEndpointAuthMethodsSupported?: string[]; + revocationEndpointAuthSigningAlgValuesSupported?: string[]; + scopesSupported?: string[]; + serviceDocumentation?: string; + tokenEndpoint: string; + tokenEndpointAuthMethodsSupported?: string[]; + tokenEndpointAuthSigningAlgValuesSupported?: string[]; + uiLocalesSupported?: string[]; + userinfoEndpoint?: string; +}; +``` + +La versión en camelCase del tipo de metadatos del Servidor de Autorización (Authorization Server) de OAuth 2.0. + +## Declaración de tipo {#type-declaration} + +### authorizationEndpoint {#authorizationendpoint} + +```ts +authorizationEndpoint: string; +``` + +### codeChallengeMethodsSupported? {#codechallengemethodssupported} + +```ts +optional codeChallengeMethodsSupported: string[]; +``` + +### grantTypesSupported? {#granttypessupported} + +```ts +optional grantTypesSupported: string[]; +``` + +### introspectionEndpoint? {#introspectionendpoint} + +```ts +optional introspectionEndpoint: string; +``` + +### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} + +```ts +optional introspectionEndpointAuthMethodsSupported: string[]; +``` + +### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} + +```ts +optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### opPolicyUri? {#oppolicyuri} + +```ts +optional opPolicyUri: string; +``` + +### opTosUri? {#optosuri} + +```ts +optional opTosUri: string; +``` + +### registrationEndpoint? {#registrationendpoint} + +```ts +optional registrationEndpoint: string; +``` + +### responseModesSupported? {#responsemodessupported} + +```ts +optional responseModesSupported: string[]; +``` + +### responseTypesSupported {#responsetypessupported} + +```ts +responseTypesSupported: string[]; +``` + +### revocationEndpoint? {#revocationendpoint} + +```ts +optional revocationEndpoint: string; +``` + +### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} + +```ts +optional revocationEndpointAuthMethodsSupported: string[]; +``` + +### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} + +```ts +optional revocationEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### serviceDocumentation? {#servicedocumentation} + +```ts +optional serviceDocumentation: string; +``` + +### tokenEndpoint {#tokenendpoint} + +```ts +tokenEndpoint: string; +``` + +### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} + +```ts +optional tokenEndpointAuthMethodsSupported: string[]; +``` + +### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} + +```ts +optional tokenEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### uiLocalesSupported? {#uilocalessupported} + +```ts +optional uiLocalesSupported: string[]; +``` + +### userinfoEndpoint? {#userinfoendpoint} + +```ts +optional userinfoEndpoint: string; +``` + +## Ver también {#see} + +[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) para el tipo original y la información de los campos. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md new file mode 100644 index 0000000..2007597 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md @@ -0,0 +1,123 @@ +--- +sidebar_label: CamelCaseProtectedResourceMetadata +--- + +# Alias de tipo: CamelCaseProtectedResourceMetadata + +```ts +type CamelCaseProtectedResourceMetadata = { + authorizationDetailsTypesSupported?: string[]; + authorizationServers?: string[]; + bearerMethodsSupported?: string[]; + dpopBoundAccessTokensRequired?: boolean; + dpopSigningAlgValuesSupported?: string[]; + jwksUri?: string; + resource: string; + resourceDocumentation?: string; + resourceName?: string; + resourcePolicyUri?: string; + resourceSigningAlgValuesSupported?: string[]; + resourceTosUri?: string; + scopesSupported?: string[]; + signedMetadata?: string; + tlsClientCertificateBoundAccessTokens?: boolean; +}; +``` + +La versión en camelCase del tipo de metadatos de recurso protegido de OAuth 2.0. + +## Declaración de tipo {#type-declaration} + +### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} + +```ts +optional authorizationDetailsTypesSupported: string[]; +``` + +### authorizationServers? {#authorizationservers} + +```ts +optional authorizationServers: string[]; +``` + +### bearerMethodsSupported? {#bearermethodssupported} + +```ts +optional bearerMethodsSupported: string[]; +``` + +### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} + +```ts +optional dpopBoundAccessTokensRequired: boolean; +``` + +### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} + +```ts +optional dpopSigningAlgValuesSupported: string[]; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### resource {#resource} + +```ts +resource: string; +``` + +### resourceDocumentation? {#resourcedocumentation} + +```ts +optional resourceDocumentation: string; +``` + +### resourceName? {#resourcename} + +```ts +optional resourceName: string; +``` + +### resourcePolicyUri? {#resourcepolicyuri} + +```ts +optional resourcePolicyUri: string; +``` + +### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} + +```ts +optional resourceSigningAlgValuesSupported: string[]; +``` + +### resourceTosUri? {#resourcetosuri} + +```ts +optional resourceTosUri: string; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### signedMetadata? {#signedmetadata} + +```ts +optional signedMetadata: string; +``` + +### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} + +```ts +optional tlsClientCertificateBoundAccessTokens: boolean; +``` + +## Ver también {#see} + +[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) para el tipo original e información de los campos. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md new file mode 100644 index 0000000..c215b31 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md @@ -0,0 +1,55 @@ +--- +sidebar_label: MCPAuthBearerAuthErrorDetails +--- + +# Alias de tipo: MCPAuthBearerAuthErrorDetails + +```ts +type MCPAuthBearerAuthErrorDetails = { + actual?: unknown; + cause?: unknown; + expected?: unknown; + missingScopes?: string[]; + uri?: URL; +}; +``` + +## Propiedades {#properties} + +### actual? {#actual} + +```ts +optional actual: unknown; +``` + +*** + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +*** + +### expected? {#expected} + +```ts +optional expected: unknown; +``` + +*** + +### missingScopes? {#missingscopes} + +```ts +optional missingScopes: string[]; +``` + +*** + +### uri? {#uri} + +```ts +optional uri: URL; +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md new file mode 100644 index 0000000..147a991 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md @@ -0,0 +1,13 @@ +--- +sidebar_label: MCPAuthConfig +--- + +# Alias de tipo: MCPAuthConfig + +```ts +type MCPAuthConfig = + | AuthServerModeConfig + | ResourceServerModeConfig; +``` + +Configuración para la clase [MCPAuth](/references/js/classes/MCPAuth.md), compatible con un único `servidor de autorización` heredado o la configuración de `servidor de recursos`. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md new file mode 100644 index 0000000..58f095e --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md @@ -0,0 +1,9 @@ +--- +sidebar_label: MCPAuthTokenVerificationErrorCode +--- + +# Alias de tipo: MCPAuthTokenVerificationErrorCode (Type Alias: MCPAuthTokenVerificationErrorCode) + +```ts +type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md new file mode 100644 index 0000000..f1c015e --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md @@ -0,0 +1,157 @@ +--- +sidebar_label: ProtectedResourceMetadata +--- + +# Alias de tipo: ProtectedResourceMetadata + +```ts +type ProtectedResourceMetadata = { + authorization_details_types_supported?: string[]; + authorization_servers?: string[]; + bearer_methods_supported?: string[]; + dpop_bound_access_tokens_required?: boolean; + dpop_signing_alg_values_supported?: string[]; + jwks_uri?: string; + resource: string; + resource_documentation?: string; + resource_name?: string; + resource_policy_uri?: string; + resource_signing_alg_values_supported?: string[]; + resource_tos_uri?: string; + scopes_supported?: string[]; + signed_metadata?: string; + tls_client_certificate_bound_access_tokens?: boolean; +}; +``` + +Esquema para los metadatos de recursos protegidos de OAuth 2.0. + +## Declaración de tipo {#type-declaration} + +### authorization\_details\_types\_supported? {#authorization-details-types-supported} + +```ts +optional authorization_details_types_supported: string[]; +``` + +Valores de tipo de detalles de autorización admitidos al usar el parámetro de solicitud authorization_details. + +### authorization\_servers? {#authorization-servers} + +```ts +optional authorization_servers: string[]; +``` + +Lista de identificadores de emisor del servidor de autorización OAuth que se pueden usar con este recurso protegido. + +### bearer\_methods\_supported? {#bearer-methods-supported} + +```ts +optional bearer_methods_supported: string[]; +``` + +Métodos admitidos para enviar tokens de portador OAuth 2.0. Valores: ["header", "body", "query"]. + +### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} + +```ts +optional dpop_bound_access_tokens_required: boolean; +``` + +Indica si el recurso protegido siempre requiere tokens de acceso vinculados a DPoP. + +### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} + +```ts +optional dpop_signing_alg_values_supported: string[]; +``` + +Algoritmos JWS admitidos para validar JWTs de prueba DPoP. + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +URL del documento JSON Web Key (JWK) Set del recurso protegido. Este documento contiene las claves públicas +que se pueden usar para verificar firmas digitales de respuestas o datos devueltos por este recurso protegido. +Esto difiere del jwks_uri del servidor de autorización, que se utiliza para la validación de tokens. Cuando el recurso protegido +firma sus respuestas, los clientes pueden obtener estas claves públicas para verificar la autenticidad e integridad +de los datos recibidos. + +### resource {#resource} + +```ts +resource: string; +``` + +El identificador de recurso del recurso protegido. + +### resource\_documentation? {#resource-documentation} + +```ts +optional resource_documentation: string; +``` + +URL que contiene la documentación para desarrolladores sobre el uso del recurso protegido. + +### resource\_name? {#resource-name} + +```ts +optional resource_name: string; +``` + +Nombre legible por humanos del recurso protegido para mostrar a los usuarios finales. + +### resource\_policy\_uri? {#resource-policy-uri} + +```ts +optional resource_policy_uri: string; +``` + +URL que contiene información sobre los requisitos de uso de datos del recurso protegido. + +### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} + +```ts +optional resource_signing_alg_values_supported: string[]; +``` + +Algoritmos de firma JWS admitidos por el recurso protegido para firmar respuestas del recurso. + +### resource\_tos\_uri? {#resource-tos-uri} + +```ts +optional resource_tos_uri: string; +``` + +URL que contiene los términos de servicio del recurso protegido. + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +Lista de valores de alcance (scope) utilizados en solicitudes de autorización para acceder a este recurso protegido. + +### signed\_metadata? {#signed-metadata} + +```ts +optional signed_metadata: string; +``` + +Un JWT firmado que contiene parámetros de metadatos como reclamos. El JWT debe estar firmado usando JWS e incluir +un reclamo 'iss'. Este campo proporciona una forma de verificar criptográficamente la autenticidad de los metadatos +en sí. La firma se puede verificar usando las claves públicas disponibles en el endpoint `jwks_uri`. +Cuando está presente, los valores en estos metadatos firmados tienen prioridad sobre los valores JSON +simples correspondientes en este documento de metadatos. Esto ayuda a prevenir la manipulación de los metadatos del recurso. + +### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} + +```ts +optional tls_client_certificate_bound_access_tokens: boolean; +``` + +Indica si el recurso protegido admite tokens de acceso vinculados a certificados de cliente mutual-TLS. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md new file mode 100644 index 0000000..7760029 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md @@ -0,0 +1,23 @@ +--- +sidebar_label: ResourceServerModeConfig +--- + +# Alias de tipo: ResourceServerModeConfig + +```ts +type ResourceServerModeConfig = { + protectedResources: ResourceServerConfig | ResourceServerConfig[]; +}; +``` + +Configuración para el servidor MCP en modo servidor de recursos. + +## Propiedades {#properties} + +### protectedResources {#protectedresources} + +```ts +protectedResources: ResourceServerConfig | ResourceServerConfig[]; +``` + +Una sola configuración de servidor de recursos o un arreglo de ellas. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md new file mode 100644 index 0000000..ffab10f --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md @@ -0,0 +1,30 @@ +--- +sidebar_label: ValidateIssuerFunction +--- + +# Alias de tipo: ValidateIssuerFunction() + +```ts +type ValidateIssuerFunction = (tokenIssuer: string) => void; +``` + +Tipo de función para validar el emisor (Issuer) del token de acceso (Access token). + +Esta función debe lanzar un [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) con el código 'invalid_issuer' si el emisor no es válido. El emisor debe validarse contra: + +1. Los servidores de autorización configurados en los metadatos del servidor de autenticación de MCP-Auth +2. Los servidores de autorización listados en los metadatos del recurso protegido + +## Parámetros {#parameters} + +### tokenIssuer {#tokenissuer} + +`string` + +## Devuelve {#returns} + +`void` + +## Lanza {#throws} + +Cuando el emisor no es reconocido o es inválido. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md new file mode 100644 index 0000000..7145862 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md @@ -0,0 +1,39 @@ +--- +sidebar_label: VerifyAccessTokenFunction +--- + +# Alias de tipo: VerifyAccessTokenFunction() + +```ts +type VerifyAccessTokenFunction = (token: string) => MaybePromise; +``` + +Tipo de función para verificar un token de acceso (Access token). + +Esta función debe lanzar un [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) si el token es inválido, +o devolver un objeto AuthInfo si el token es válido. + +Por ejemplo, si tienes una función de verificación de JWT, al menos debe comprobar la firma del token, +validar su expiración y extraer los reclamos (Claims) necesarios para devolver un objeto `AuthInfo`. + +**Nota:** No es necesario verificar los siguientes campos en el token, ya que serán comprobados +por el manejador: + +- `iss` (emisor / issuer) +- `aud` (audiencia / audience) +- `scope` (alcances / scopes) + +## Parámetros {#parameters} + +### token {#token} + +`string` + +La cadena del token de acceso (Access token) a verificar. + +## Devuelve {#returns} + +`MaybePromise`\<`AuthInfo`\> + +Una promesa que se resuelve en un objeto AuthInfo o un valor sincrónico si el +token es válido. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md new file mode 100644 index 0000000..6e88a1a --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: VerifyAccessTokenMode +--- + +# Alias de tipo: VerifyAccessTokenMode + +```ts +type VerifyAccessTokenMode = "jwt"; +``` + +Los modos de verificación integrados admitidos por `bearerAuth`. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md new file mode 100644 index 0000000..b4726e8 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: authServerErrorDescription +--- + +# Variable: authServerErrorDescription + +```ts +const authServerErrorDescription: Readonly>; +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md new file mode 100644 index 0000000..6eba06b --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: authorizationServerMetadataSchema +--- + +# Variable: authorizationServerMetadataSchema + +```ts +const authorizationServerMetadataSchema: ZodObject; +``` + +Esquema Zod para los metadatos del servidor de autorización OAuth 2.0 según lo definido en RFC 8414. + +## Ver {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md new file mode 100644 index 0000000..ed1a931 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: bearerAuthErrorDescription +--- + +# Variable: bearerAuthErrorDescription + +```ts +const bearerAuthErrorDescription: Readonly>; +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md new file mode 100644 index 0000000..55f0dde --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseAuthorizationServerMetadataSchema +--- + +# Variable: camelCaseAuthorizationServerMetadataSchema + +```ts +const camelCaseAuthorizationServerMetadataSchema: ZodObject; +``` + +La versión en camelCase del esquema Zod de metadatos del servidor de autorización OAuth 2.0. + +## Ver {#see} + +[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) para el esquema original e información de los campos. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md new file mode 100644 index 0000000..c575595 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseProtectedResourceMetadataSchema +--- + +# Variable: camelCaseProtectedResourceMetadataSchema + +```ts +const camelCaseProtectedResourceMetadataSchema: ZodObject; +``` + +La versión en camelCase del esquema Zod de Metadatos de Recurso Protegido de OAuth 2.0. + +## Ver {#see} + +[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) para el esquema original e información de los campos. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md new file mode 100644 index 0000000..c29ea72 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md @@ -0,0 +1,9 @@ +--- +sidebar_label: defaultValues +--- + +# Variable: defaultValues + +```ts +const defaultValues: Readonly>; +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md new file mode 100644 index 0000000..c2f97f4 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md @@ -0,0 +1,11 @@ +--- +sidebar_label: protectedResourceMetadataSchema +--- + +# Variable: protectedResourceMetadataSchema + +```ts +const protectedResourceMetadataSchema: ZodObject; +``` + +Esquema Zod para los metadatos de recursos protegidos de OAuth 2.0 (OAuth 2.0 Protected Resource Metadata). \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md new file mode 100644 index 0000000..68cbf41 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md @@ -0,0 +1,12 @@ +--- +sidebar_label: serverMetadataPaths +--- + +# Variable: serverMetadataPaths + +```ts +const serverMetadataPaths: Readonly<{ + oauth: "/.well-known/oauth-authorization-server"; + oidc: "/.well-known/openid-configuration"; +}>; +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md new file mode 100644 index 0000000..b0004b3 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: tokenVerificationErrorDescription +--- + +# Variable: tokenVerificationErrorDescription + +```ts +const tokenVerificationErrorDescription: Readonly>; +``` \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md new file mode 100644 index 0000000..e60de41 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md @@ -0,0 +1,9 @@ +--- +sidebar_label: validateServerConfig +--- + +# Variable: validateServerConfig + +```ts +const validateServerConfig: ValidateServerConfig; +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx b/i18n/es/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx new file mode 100644 index 0000000..00f677a --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx @@ -0,0 +1,73 @@ +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + + + + +```python +mcp = FastMCP("MyMCPServer") +resource_identifier = "https://api.example.com" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_identifier, + authorization_servers=[fetch_server_config('', AuthServerType.OIDC)], + scopes_supported=["read", "write"], + ) + ) +) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + Mount('/', app=mcp.sse_app(), middleware=[Middleware( + mcp_auth.bearer_auth_middleware("jwt", + resource=resource_identifier, + audience=resource_identifier, + required_scopes=["read", "write"] + ) + )]) + ] +) + +@mcp.tool() +def whoami(): + return mcp_auth.auth_info.claims +``` + + + + +```ts +const server = new McpServer(/* ... */); +const resourceIdentifier = 'https://api.example.com'; + +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceIdentifier, + authorizationServers: [await fetchServerConfig('', { type: 'oidc' })], + scopesSupported: ['read', 'write'], + } + } +}); + +const app = express(); + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +app.use(mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, + requiredScopes: ['read', 'write'] +})); + +server.tool('whoami', ({ authInfo }) => { + return authInfo.claims; +}); +``` + + + diff --git a/i18n/es/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx b/i18n/es/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx new file mode 100644 index 0000000..ac3c1ea --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx @@ -0,0 +1,1396 @@ +--- +sidebar_position: 2 +sidebar_label: 'Tutorial: Construye un gestor de tareas' +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + +# Tutorial: Construye un gestor de tareas + +En este tutorial, construiremos un servidor MCP gestor de tareas con Autenticación (Authentication) y Autorización (Authorization) de usuarios. Siguiendo la última especificación de MCP, nuestro servidor MCP actuará como un **Servidor de Recursos** OAuth 2.0 que valida tokens de acceso y aplica permisos basados en Alcances (Scopes). + +Al completar este tutorial, tendrás: + +- ✅ Una comprensión básica de cómo configurar el control de acceso basado en roles (RBAC) en tu servidor MCP. +- ✅ Un servidor MCP que actúa como Servidor de Recursos, consumiendo tokens de acceso emitidos por un Servidor de Autorización (Authorization Server). +- ✅ Una implementación funcional de la aplicación de permisos basados en Alcances (Scopes) para operaciones de tareas. + +## Visión general \{#overview} + +El tutorial involucrará los siguientes componentes: + +- **Cliente MCP (MCP Inspector)**: Una herramienta visual de pruebas para servidores MCP que actúa como cliente OAuth 2.0/OIDC. Inicia el flujo de autorización con el servidor de autorización y obtiene tokens de acceso para autenticar solicitudes al servidor MCP. +- **Servidor de Autorización (Authorization Server)**: Un proveedor OAuth 2.1 o OpenID Connect que gestiona identidades de usuario, autentica usuarios y emite tokens de acceso con los Alcances (Scopes) apropiados a los clientes autorizados. +- **Servidor MCP (Servidor de Recursos)**: Según la última especificación de MCP, el servidor MCP actúa como un Servidor de Recursos en el marco OAuth 2.0. Valida los tokens de acceso emitidos por el servidor de autorización y aplica permisos basados en Alcances (Scopes) para las operaciones de tareas. + +Esta arquitectura sigue el flujo estándar de OAuth 2.0 donde: +- El **MCP Inspector** solicita recursos protegidos en nombre del usuario +- El **Servidor de Autorización (Authorization Server)** autentica al usuario y emite tokens de acceso +- El **Servidor MCP** valida los tokens y sirve recursos protegidos según los permisos concedidos + +Aquí tienes un diagrama de alto nivel de la interacción entre estos componentes: + +```mermaid +sequenceDiagram + autonumber + participant Client as MCP Inspector
(Cliente OAuth) + participant RS as Servidor MCP
(Servidor de Recursos) + participant AS as Servidor de Autorización + + Client->>RS: Solicitud MCP (sin token) + RS-->>Client: 401 No autorizado (WWW-Authenticate) + Note over Client: Extrae la URL de resource_metadata
del encabezado WWW-Authenticate + + Client->>RS: GET /.well-known/oauth-protected-resource (resource_metadata) + RS-->>Client: Metadatos del recurso protegido
(incluye la URL del servidor de autorización) + + Client->>AS: GET /.well-known/oauth-authorization-server + AS-->>Client: Metadatos del servidor de autorización + Client->>AS: Autorización OAuth (inicio de sesión & consentimiento) + AS-->>Client: Token de acceso + + Client->>RS: Solicitud MCP (Authorization: Bearer ) + RS->>RS: Valida que el token de acceso es válido y autorizado + RS-->>Client: Respuesta MCP +``` + +## Comprende tu servidor de autorización \{#understand-your-authorization-server} + +### Tokens de acceso con Alcances (Scopes) \{#access-tokens-with-scopes} + +Para implementar el [control de acceso basado en roles (RBAC)](https://auth.wiki/rbac) en tu servidor MCP, tu servidor de autorización debe admitir la emisión de tokens de acceso con Alcances (Scopes). Los Alcances (Scopes) representan los Permisos (Permissions) que se han concedido a un usuario. + + + + +[Logto](https://logto.io) proporciona soporte RBAC a través de sus Recursos de API (API resources) (conforme a [RFC 8707: Indicadores de recurso para OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707)) y funciones de Roles (Roles). Así es como se configura: + +1. Inicia sesión en [Logto Console](https://cloud.logto.io) (o en tu Logto Console autoalojado) + +2. Crea un recurso de API y Alcances (Scopes): + + - Ve a "Recursos de API" + - Crea un nuevo recurso de API llamado "Gestor de tareas" + - Añade los siguientes Alcances (Scopes): + - `create:todos`: "Crear nuevas tareas" + - `read:todos`: "Leer todas las tareas" + - `delete:todos`: "Eliminar cualquier tarea" + +3. Crea Roles (Roles) (recomendado para una gestión más sencilla): + + - Ve a "Roles" + - Crea un rol "Admin" y asigna todos los Alcances (Scopes) (`create:todos`, `read:todos`, `delete:todos`) + - Crea un rol "User" y asigna solo el Alcance (Scope) `create:todos` + +4. Asigna Permisos (Permissions): + - Ve a "Usuarios" + - Selecciona un usuario + - Puedes: + - Asignar Roles (Roles) en la pestaña "Roles" (recomendado) + - O asignar directamente Alcances (Scopes) en la pestaña "Permisos" (Permissions) + +Los Alcances (Scopes) se incluirán en el Reclamo (Claim) `scope` del token de acceso JWT como una cadena separada por espacios. + + + + +Los proveedores OAuth 2.0 / OIDC suelen admitir el control de acceso basado en Alcances (Scopes). Al implementar RBAC: + +1. Define los Alcances (Scopes) requeridos en tu servidor de autorización +2. Configura tu cliente para solicitar estos Alcances (Scopes) durante el flujo de autorización +3. Asegúrate de que tu servidor de autorización incluya los Alcances (Scopes) concedidos en el token de acceso +4. Los Alcances (Scopes) suelen incluirse en el Reclamo (Claim) `scope` del token de acceso JWT + +Consulta la documentación de tu proveedor para detalles específicos sobre: + +- Cómo definir y gestionar Alcances (Scopes) +- Cómo se incluyen los Alcances (Scopes) en el token de acceso +- Cualquier característica adicional de RBAC como la gestión de Roles (Roles) + + + + +### Validación de tokens y comprobación de Permisos (Permissions) \{#validating-tokens-and-checking-permissions} + +Según la última especificación de MCP, el servidor MCP actúa como un **Servidor de Recursos** en el marco OAuth 2.0. Como Servidor de Recursos, el servidor MCP tiene las siguientes responsabilidades: + +1. **Validación de tokens**: Verificar la autenticidad e integridad de los tokens de acceso recibidos de los clientes MCP +2. **Aplicación de Alcances (Scopes)**: Extraer y validar los Alcances (Scopes) del token de acceso para determinar qué operaciones está autorizado a realizar el cliente +3. **Protección de recursos**: Solo servir recursos protegidos (ejecutar herramientas) cuando el cliente presente tokens válidos con Permisos (Permissions) suficientes + +Cuando tu servidor MCP recibe una solicitud, realiza el siguiente proceso de validación: + +1. Extrae el token de acceso del encabezado `Authorization` (formato Bearer token) +2. Valida la firma y expiración del token de acceso +3. Extrae los Alcances (Scopes) e información del usuario del token validado +4. Comprueba si el token tiene los Alcances (Scopes) requeridos para la operación solicitada + +Por ejemplo, si un usuario quiere crear una nueva tarea, su token de acceso debe incluir el Alcance (Scope) `create:todos`. Así es como funciona el flujo de validación del Servidor de Recursos: + +```mermaid +sequenceDiagram + participant Client as Cliente MCP + participant Server as Servidor MCP
(Servidor de Recursos) + participant Auth as Servidor de Autorización + + Client->>Server: Solicitud con token de acceso
(Authorization: Bearer ) + + alt Validación JWT (Preferido) + Server->>Auth: Obtener JWKS (si no está en caché) + Auth-->>Server: Devuelve JWKS + Server->>Server: Valida localmente la firma y los Reclamos (Claims) del JWT + else Introspección de token (Alternativa) + Server->>Auth: POST /introspect
(token=access_token) + Auth-->>Server: Devuelve información del token
(activo, Alcance (Scope), user_id, etc.) + end + + Server->>Server: Extrae Alcances (Scopes) y contexto de usuario
del token validado + + alt Tiene los Alcances (Scopes) requeridos + Server->>Server: Ejecuta la operación solicitada + Server->>Client: Devuelve el resultado de la operación + else Faltan Alcances (Scopes) requeridos + Server->>Client: Devuelve 403 Prohibido
(error insufficient_scope) + end +``` + +### Registro dinámico de clientes (Dynamic Client Registration) \{#dynamic-client-registration} + +El registro dinámico de clientes no es necesario para este tutorial, pero puede ser útil si deseas automatizar el proceso de registro del cliente MCP con tu servidor de autorización. Consulta [¿Se requiere Dynamic Client Registration?](/provider-list#is-dcr-required) para más detalles. + +## Comprende RBAC en el gestor de tareas \{#understand-rbac-in-todo-manager} + +Para fines demostrativos, implementaremos un sistema simple de control de acceso basado en roles (RBAC) en nuestro servidor MCP gestor de tareas. Esto te mostrará los principios básicos de RBAC manteniendo la implementación sencilla. + +:::note +Aunque este tutorial demuestra la gestión de Alcances (Scopes) basada en RBAC, es importante señalar que no todos los proveedores de autenticación implementan la gestión de Alcances (Scopes) a través de Roles (Roles). Algunos proveedores pueden tener sus propias implementaciones y mecanismos únicos para gestionar el control de acceso y los Permisos (Permissions). +::: + +### Herramientas y Alcances (Scopes) \{#tools-and-scopes} + +Nuestro servidor MCP gestor de tareas proporciona tres herramientas principales: + +- `create-todo`: Crear una nueva tarea +- `get-todos`: Listar todas las tareas +- `delete-todo`: Eliminar una tarea por ID + +Para controlar el acceso a estas herramientas, definimos los siguientes Alcances (Scopes): + +- `create:todos`: Permite crear nuevas tareas +- `delete:todos`: Permite eliminar tareas existentes +- `read:todos`: Permite consultar y recuperar la lista de todas las tareas + +### Roles (Roles) y Permisos (Permissions) \{#roles-and-permissions} + +Definiremos dos Roles (Roles) con diferentes niveles de acceso: + +| Rol | create:todos | read:todos | delete:todos | +| ----- | ------------ | ---------- | ------------ | +| Admin | ✅ | ✅ | ✅ | +| User | ✅ | | | + +- **User**: Un usuario regular que puede crear tareas y ver o eliminar solo sus propias tareas +- **Admin**: Un administrador que puede crear, ver y eliminar todas las tareas, sin importar la propiedad + +### Propiedad de recursos \{#resource-ownership} + +Aunque la tabla de Permisos (Permissions) anterior muestra los Alcances (Scopes) explícitos asignados a cada Rol (Role), hay un principio importante de propiedad de recursos a considerar: + +- **Los usuarios** no tienen los Alcances (Scopes) `read:todos` o `delete:todos`, pero aún pueden: + - Leer sus propias tareas + - Eliminar sus propias tareas +- **Los administradores** tienen todos los Permisos (Permissions) (`read:todos` y `delete:todos`), lo que les permite: + - Ver todas las tareas del sistema + - Eliminar cualquier tarea, sin importar la propiedad + +Esto demuestra un patrón común en los sistemas RBAC donde la propiedad de recursos otorga Permisos (Permissions) implícitos a los usuarios para sus propios recursos, mientras que los Roles (Roles) administrativos reciben Permisos (Permissions) explícitos para todos los recursos. + +:::tip Aprende más +Para profundizar en los conceptos y mejores prácticas de RBAC, consulta [Dominando RBAC: Un ejemplo completo del mundo real](https://blog.logto.io/mastering-rbac). +::: + +## Configura la autorización en tu proveedor \{#configure-authorization-in-your-provider} + +Para implementar el sistema de control de acceso que describimos antes, deberás configurar tu servidor de autorización para admitir los Alcances (Scopes) requeridos. Así es como hacerlo con diferentes proveedores: + + + + +[Logto](https://logto.io) proporciona soporte RBAC a través de sus Recursos de API (API resources) y funciones de Roles (Roles). Así es como se configura: + +1. Inicia sesión en [Logto Console](https://cloud.logto.io) (o en tu Logto Console autoalojado) + +2. Crea un recurso de API y Alcances (Scopes): + + - Ve a "Recursos de API" + - Crea un nuevo recurso de API llamado "Gestor de tareas" y usa `http://localhost:3001` como el indicador de recurso. + - **Importante**: El indicador de recurso debe coincidir con la URL de tu servidor MCP. Para este tutorial, usamos `http://localhost:3001` ya que nuestro servidor MCP se ejecuta en el puerto 3001. En producción, usa la URL real de tu servidor MCP (por ejemplo, `https://tu-servidor-mcp.ejemplo.com`). + - Crea los siguientes Alcances (Scopes): + - `create:todos`: "Crear nuevas tareas" + - `read:todos`: "Leer todas las tareas" + - `delete:todos`: "Eliminar cualquier tarea" + +3. Crea Roles (Roles) (recomendado para una gestión más sencilla): + + - Ve a "Roles" + - Crea un rol "Admin" y asigna todos los Alcances (Scopes) (`create:todos`, `read:todos`, `delete:todos`) + - Crea un rol "User" y asigna solo el Alcance (Scope) `create:todos` + - En la página de detalles del rol "User", cambia a la pestaña "General" y establece el rol "User" como el "Rol predeterminado". + +4. Gestiona los Roles (Roles) y Permisos (Permissions) de los usuarios: + - Para nuevos usuarios: + - Obtendrán automáticamente el rol "User" ya que lo configuramos como el rol predeterminado + - Para usuarios existentes: + - Ve a "Gestión de usuarios" + - Selecciona un usuario + - Asigna Roles (Roles) al usuario en la pestaña "Roles" + +:::tip Gestión programática de Roles (Roles) +También puedes usar la [Management API](https://docs.logto.io/integrate-logto/interact-with-management-api) de Logto para gestionar Roles (Roles) de usuarios de forma programática. Esto es especialmente útil para la gestión automatizada de usuarios o al construir paneles de administración. +::: + +Al solicitar un token de acceso, Logto incluirá los Alcances (Scopes) en el Reclamo (Claim) `scope` del token según los Permisos (Permissions) de los Roles (Roles) del usuario. + + + + +Para proveedores OAuth 2.0 u OpenID Connect, deberás configurar los Alcances (Scopes) que representan diferentes Permisos (Permissions). Los pasos exactos dependerán de tu proveedor, pero generalmente: + +1. Define Alcances (Scopes): + + - Configura tu servidor de autorización para admitir: + - `create:todos` + - `read:todos` + - `delete:todos` + +2. Configura el cliente: + + - Registra o actualiza tu cliente para solicitar estos Alcances (Scopes) + - Asegúrate de que los Alcances (Scopes) se incluyan en el token de acceso + +3. Asigna Permisos (Permissions): + - Usa la interfaz de tu proveedor para conceder los Alcances (Scopes) apropiados a los usuarios + - Algunos proveedores pueden admitir la gestión basada en Roles (Roles), mientras que otros pueden usar asignaciones directas de Alcances (Scopes) + - Consulta la documentación de tu proveedor para el enfoque recomendado + +:::tip +La mayoría de los proveedores incluirán los Alcances (Scopes) concedidos en el Reclamo (Claim) `scope` del token de acceso. El formato suele ser una cadena de valores de Alcance (Scope) separados por espacios. +::: + + + + +Después de configurar tu servidor de autorización, los usuarios recibirán tokens de acceso que contienen los Alcances (Scopes) concedidos. El servidor MCP usará estos Alcances (Scopes) para determinar: + +- Si un usuario puede crear nuevas tareas (`create:todos`) +- Si un usuario puede ver todas las tareas (`read:todos`) o solo las suyas +- Si un usuario puede eliminar cualquier tarea (`delete:todos`) o solo las suyas + +## Configura el servidor MCP \{#set-up-the-mcp-server} + +Usaremos los [SDKs oficiales de MCP](https://github.com/modelcontextprotocol) para crear nuestro servidor MCP gestor de tareas. + +### Crea un nuevo proyecto \{#create-a-new-project} + + + + +Configura un nuevo proyecto Python: + +```bash +mkdir mcp-todo-server +cd mcp-todo-server + +# Inicializa un nuevo proyecto Python +uv init + +# Crea un nuevo entorno virtual usando uv +uv venv + +# Activa el entorno virtual (opcional al usar 'uv run') +source .venv/bin/activate +``` + +:::note +Este proyecto usa `uv` para la gestión de paquetes, pero puedes usar otros gestores como `pip`, `poetry` o `conda` si lo prefieres. +::: + + + + +Configura un nuevo proyecto Node.js: + +```bash +mkdir mcp-server +cd mcp-server +npm init -y # O usa `pnpm init` +npm pkg set type="module" +npm pkg set main="todo-manager.ts" +npm pkg set scripts.start="node --experimental-strip-types todo-manager.ts" +``` + +:::note +Usamos TypeScript en nuestros ejemplos ya que Node.js v22.6.0+ admite la ejecución nativa de TypeScript usando la opción `--experimental-strip-types`. Si usas JavaScript, el código será similar; solo asegúrate de usar Node.js v22.6.0 o posterior. Consulta la documentación de Node.js para más detalles. +::: + + + + +### Instala el SDK de MCP y dependencias \{#install-the-mcp-sdk-and-dependencies} + + + + +Instala las dependencias requeridas: + +```bash +uv add "mcp[cli]" uvicorn starlette +``` + + + + +```bash +npm install @modelcontextprotocol/sdk express zod +``` + +O cualquier otro gestor de paquetes que prefieras, como `pnpm` o `yarn`. + + + + +### Crea el servidor MCP \{#create-the-mcp-server} + +Primero, vamos a crear un servidor MCP básico con las definiciones de herramientas: + + + + +Crea un archivo llamado `server.py` y añade el siguiente código: + +```python +# server.py + +import contextlib +from typing import Any +from mcp.server.fastmcp import FastMCP +from starlette.applications import Starlette +from starlette.routing import Mount + +# Inicializa el servidor FastMCP +mcp = FastMCP(name="Gestor de tareas", stateless_http=True, streamable_http_path='/') + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """Crear una nueva tarea. Requiere el Alcance (Scope) 'create:todos'.""" + return {"error": "Not implemented"} + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """Listar tareas. Los usuarios con el Alcance (Scope) 'read:todos' pueden ver todas las tareas.""" + return {"error": "Not implemented"} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """Eliminar una tarea por id. Los usuarios pueden eliminar sus propias tareas.""" + return {"error": "Not implemented"} + +@contextlib.asynccontextmanager +async def lifespan(app: Starlette): + async with contextlib.AsyncExitStack() as stack: + await stack.enter_async_context(mcp.session_manager.run()) + yield + +# Crea la app +app = Starlette( + routes=[ + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + +Ejecuta el servidor con: + +```bash +# Inicia el servidor Gestor de tareas usando uvicorn +uvicorn server:app --host 127.0.0.1 --port 3001 + +# O usando uv: +# uv run uvicorn server:app --host 127.0.0.1 --port 3001 +``` + + + + +Crea un archivo llamado `todo-manager.ts` y añade el siguiente código: + +```ts +// todo-manager.ts + +import { z } from 'zod'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import express, { type Request, type Response } from 'express'; + +// Crea un servidor MCP +const server = new McpServer({ + name: 'Gestor de tareas', + version: '0.0.0', +}); + +server.tool('create-todo', 'Crear una nueva tarea', { content: z.string() }, async ({ content }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('get-todos', 'Listar todas las tareas', async () => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('delete-todo', 'Eliminar una tarea por id', { id: z.string() }, async ({ id }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +// A continuación el código base de la documentación del SDK de MCP +const PORT = 3001; +const app = express(); + +app.post('/', async (request: Request, response: Response) => { + // En modo sin estado, crea una nueva instancia de transporte y servidor para cada solicitud + // para asegurar el aislamiento completo. Una sola instancia causaría colisiones de ID de solicitud + // cuando varios clientes se conectan simultáneamente. + + try { + const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + }); + response.on('close', async () => { + console.log('Request closed'); + await transport.close(); + await server.close(); + }); + await server.connect(transport); + await transport.handleRequest(request, response, request.body); + } catch (error) { + console.error('Error handling MCP request:', error); + if (!response.headersSent) { + response.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32_603, + message: 'Internal server error', + }, + id: null, + }); + } + } +}); + +// Las notificaciones SSE no son compatibles en modo sin estado +app.get('/', async (request: Request, response: Response) => { + console.log('Received GET MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +// Terminación de sesión no necesaria en modo sin estado +app.delete('/', async (request: Request, response: Response) => { + console.log('Received DELETE MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +app.listen(PORT); +``` + +Ejecuta el servidor con: + +```bash +npm start +``` + + + + +## Inspecciona el servidor MCP \{#inspect-the-mcp-server} + +### Clona y ejecuta MCP inspector \{#clone-and-run-mcp-inspector} + +Ahora que tenemos el servidor MCP en funcionamiento, podemos usar el MCP inspector para ver si las herramientas están disponibles. + +La versión oficial MCP inspector v0.16.2 tiene algunos errores que afectan la funcionalidad de autenticación. Para solucionar estos problemas, hemos creado una [versión parcheada de MCP inspector](https://github.com/mcp-auth/inspector/tree/patch/0.16.2-fixes) que incluye las correcciones necesarias para los flujos de autenticación OAuth/OIDC. También hemos enviado pull requests al repositorio oficial para contribuir con estas correcciones. + +Para ejecutar el MCP inspector, puedes usar el siguiente comando (se requiere Node.js): + +```bash +git clone https://github.com/mcp-auth/inspector.git -b patch/0.16.2-fixes +cd inspector +npm install +npm run dev +``` + +El MCP inspector se abrirá automáticamente en tu navegador predeterminado, o puedes acceder manualmente haciendo clic en el enlace de la salida de la terminal (asegúrate de hacer clic en el enlace que incluye el parámetro `MCP_PROXY_AUTH_TOKEN`, como `http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=458ae4a4...acab1907`). + +### Conecta MCP inspector al servidor MCP \{#connect-mcp-inspector-to-the-mcp-server} + +Antes de continuar, verifica la siguiente configuración en MCP inspector: + +- **Tipo de transporte**: Establece en `Streamable HTTP`. +- **URL**: Establece la URL de tu servidor MCP. En nuestro caso, debe ser `http://localhost:3001`. + +Ahora puedes hacer clic en el botón "Connect" para ver si el MCP inspector puede conectarse al servidor MCP. Si todo está bien, deberías ver el estado "Connected" en el MCP inspector. + +### Punto de control: Ejecuta las herramientas del gestor de tareas \{#checkpoint-run-todo-manager-tools} + +1. En el menú superior del MCP inspector, haz clic en la pestaña "Tools". +2. Haz clic en el botón "List Tools". +3. Deberías ver las herramientas `create-todo`, `get-todos` y `delete-todo` listadas en la página. Haz clic en ellas para ver los detalles. +4. Deberías ver el botón "Run Tool" en el lado derecho. Haz clic en él e ingresa los parámetros requeridos para ejecutar la herramienta. +5. Deberías ver el resultado de la herramienta con la respuesta JSON `{"error": "Not implemented"}`. + +![Primera ejecución de MCP inspector](/docs-assets/images/tutorials/todo-manager/inspector-first-run.png) + +## Integra con tu servidor de autorización \{#integrate-with-your-authorization-server} + +Para completar esta sección, hay varias consideraciones a tener en cuenta: + +
+**La URL del emisor (Issuer) de tu servidor de autorización** + +Normalmente es la URL base de tu servidor de autorización, como `https://auth.example.com`. Algunos proveedores pueden tener una ruta como `https://example.logto.app/oidc`, así que asegúrate de consultar la documentación de tu proveedor. + +
+ +
+**Cómo obtener los metadatos del servidor de autorización** + +- Si tu servidor de autorización cumple con [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) o [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html), puedes usar las utilidades integradas de MCP Auth para obtener los metadatos automáticamente. +- Si tu servidor de autorización no cumple con estos estándares, deberás especificar manualmente la URL de metadatos o los endpoints en la configuración del servidor MCP. Consulta la documentación de tu proveedor para los endpoints específicos. + +
+ +
+**Cómo registrar MCP inspector como cliente en tu servidor de autorización** + +- Si tu servidor de autorización admite [Dynamic Client Registration](https://datatracker.ietf.org/doc/html/rfc7591), puedes omitir este paso ya que MCP inspector se registrará automáticamente como cliente. +- Si tu servidor de autorización no admite Dynamic Client Registration, deberás registrar manualmente MCP inspector como cliente en tu servidor de autorización. + +
+ +
+**Comprende los parámetros de solicitud de token** + +Al solicitar tokens de acceso de diferentes servidores de autorización, encontrarás varios enfoques para especificar el recurso objetivo y los Permisos (Permissions). Aquí los principales patrones: + +- **Basado en indicador de recurso**: + + - Usa el parámetro `resource` para especificar la API objetivo (ver [RFC 8707: Indicadores de recurso para OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707)) + - Común en implementaciones modernas de OAuth 2.0 + - Ejemplo de solicitud: + ```json + { + "resource": "http://localhost:3001", + "scope": "create:todos read:todos" + } + ``` + - El servidor emite tokens vinculados específicamente al recurso solicitado + +- **Basado en audiencia**: + + - Usa el parámetro `audience` para especificar el destinatario previsto del token + - Similar a los indicadores de recurso pero con semántica diferente + - Ejemplo de solicitud: + ```json + { + "audience": "todo-api", + "scope": "create:todos read:todos" + } + ``` + +- **Basado solo en Alcances (Scopes)**: + - Se basa únicamente en Alcances (Scopes) sin parámetros de recurso/audiencia + - Enfoque tradicional de OAuth 2.0 + - Ejemplo de solicitud: + ```json + { + "scope": "todo-api:create todo-api:read openid profile" + } + ``` + - A menudo usa Alcances (Scopes) con prefijo para namespacing de Permisos (Permissions) + - Común en implementaciones más simples de OAuth 2.0 + +:::tip Mejores prácticas + +- Consulta la documentación de tu proveedor para los parámetros admitidos +- Algunos proveedores admiten varios enfoques simultáneamente +- Los indicadores de recurso proporcionan mejor seguridad mediante restricción de audiencia +- Considera usar indicadores de recurso cuando estén disponibles para un mejor control de acceso + ::: + +
+ +Aunque cada proveedor puede tener sus propios requisitos específicos, los siguientes pasos te guiarán en el proceso de integración de MCP inspector y el servidor MCP con configuraciones específicas del proveedor. + +### Registra MCP inspector como cliente \{#register-mcp-inspector-as-a-client} + + + + +Integrar el gestor de tareas con [Logto](https://logto.io) es sencillo ya que es un proveedor OpenID Connect que admite indicadores de recurso y Alcances (Scopes), lo que te permite proteger tu API de tareas con `http://localhost:3001` como indicador de recurso. + +Como Logto aún no admite Dynamic Client Registration, deberás registrar manualmente MCP inspector como cliente en tu tenant de Logto: + +1. Abre tu MCP inspector, ve a la configuración de Autenticación (Authentication) y haz clic en la configuración "OAuth2.0 Flow". Copia el valor de **Redirect URI**, que debería ser algo como `http://localhost:6274/oauth/callback`. +2. Inicia sesión en [Logto Console](https://cloud.logto.io) (o en tu Logto Console autoalojado). +3. Navega a la pestaña "Aplicaciones", haz clic en "Crear aplicación". En la parte inferior de la página, haz clic en "Crear app sin framework". +4. Rellena los detalles de la aplicación y haz clic en "Crear aplicación": + - **Selecciona un tipo de aplicación**: Elige "Aplicación de una sola página". + - **Nombre de la aplicación**: Ingresa un nombre para tu aplicación, por ejemplo, "MCP Inspector". +5. En la sección "Configuración / Redirect URIs", pega el valor de **Redirect URI** que copiaste de MCP inspector. Luego haz clic en "Guardar cambios" en la barra inferior. +6. En la tarjeta superior, verás el valor "App ID". Cópialo. +7. Vuelve a MCP inspector y pega el valor "App ID" en la configuración de Autenticación (Authentication) bajo "OAuth2.0 Flow" en el campo "Client ID". +8. En el campo "Scope", ingresa: `create:todos read:todos delete:todos`. Esto asegurará que el token de acceso devuelto por Logto contenga los Alcances (Scopes) necesarios para acceder al gestor de tareas. + + + + +:::note +Esta es una guía genérica de integración con proveedores OAuth 2.0 / OpenID Connect. Ambos siguen pasos similares ya que OIDC se basa en OAuth 2.0. Consulta la documentación de tu proveedor para detalles específicos. +::: + +Si tu proveedor admite Dynamic Client Registration, puedes ir directamente al paso 8 a continuación para configurar MCP inspector; de lo contrario, deberás registrar manualmente MCP inspector como cliente: + +1. Abre tu MCP inspector, ve a la configuración de Autenticación (Authentication) y haz clic en la configuración "OAuth2.0 Flow". Copia el valor de **Redirect URI**, que debería ser algo como `http://localhost:6274/oauth/callback`. + +2. Inicia sesión en la consola de tu proveedor. + +3. Navega a la sección "Aplicaciones" o "Clientes", luego crea una nueva aplicación o cliente. + +4. Si tu proveedor requiere un tipo de cliente, selecciona "Aplicación de una sola página" o "Cliente público". + +5. Después de crear la aplicación, deberás configurar el Redirect URI. Pega el valor de **Redirect URI** que copiaste de MCP inspector. + +6. Busca el "Client ID" o "Application ID" de la nueva aplicación y cópialo. + +7. Vuelve a MCP inspector y pega el valor "Client ID" en la configuración de Autenticación (Authentication) bajo "OAuth2.0 Flow" en el campo "Client ID". + +8. En el campo "Scope", ingresa los siguientes Alcances (Scopes) para solicitar los Permisos (Permissions) necesarios para las operaciones de tareas: + +```text +create:todos read:todos delete:todos +``` + + + + +### Configura MCP Auth \{#set-up-mcp-auth} + +Primero, instala el SDK de MCP Auth en tu proyecto de servidor MCP. + + + + +```bash +uv add mcpauth==0.2.0b1 +``` + + + + +```bash +npm install mcp-auth@0.2.0-beta.1 +``` + + + + +Ahora necesitamos inicializar MCP Auth en tu servidor MCP. Esto implica dos pasos principales: + +1. **Obtener los metadatos del servidor de autorización**: Se utiliza para la posterior verificación de tokens de acceso emitidos por el Servidor de Autorización (Authorization Server) y para incluir el identificador del emisor (Issuer) del servidor de autorización en los metadatos del recurso +2. **Configurar los metadatos del recurso protegido**: Define el identificador de recurso de tu servidor MCP y los Alcances (Scopes) soportados + +#### Paso 1: Obtener los metadatos del servidor de autorización \{#step-1-fetch-authorization-server-metadata\} + +Según la especificación OAuth / OIDC, podemos obtener los metadatos del servidor de autorización a partir de la URL del emisor (Issuer) del servidor de autorización. + + + + + +En Logto, puedes encontrar la URL del emisor (Issuer) en la página de detalles de tu aplicación dentro de Logto Console, en la sección "Endpoints & Credentials / Issuer endpoint". Debería verse como `https://my-project.logto.app/oidc`. + + + + + +Para proveedores OAuth 2.0, deberás: + +1. Consultar la documentación de tu proveedor para la URL del servidor de autorización (a menudo llamada issuer URL o base URL) +2. Algunos proveedores pueden exponer esto en `https://{tu-dominio}/.well-known/oauth-authorization-server` +3. Busca en la consola de administración de tu proveedor bajo la configuración OAuth/API + + + + + +Ahora, obtén los metadatos del servidor de autorización usando la función utilitaria de MCP Auth para recuperar la configuración del servidor: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +issuer_url = "" # Reemplaza con la URL del emisor de tu servidor de autorización + +# Obtén la configuración del servidor de autorización +auth_server_config = fetch_server_config(issuer_url, AuthServerType.OIDC) # o AuthServerType.OAUTH +``` + + + +```js +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const issuerUrl = ''; // Reemplaza con la URL del emisor de tu servidor de autorización + +// Obtén la configuración del servidor de autorización (OIDC Discovery) +const authServerConfig = await fetchServerConfig(issuerUrl, { type: 'oidc' }); // o { type: 'oauth' } +``` + + + + +Si necesitas formas alternativas de obtener los metadatos del servidor de autorización o quieres personalizar la configuración, consulta [otras formas de configurar los metadatos del servidor de autorización](/docs/configure-server/mcp-auth#other-ways). + +#### Paso 2: Configura los metadatos del recurso protegido \{#step-2-configure-protected-resource-metadata} + +A continuación, configuraremos los Metadatos del Recurso Protegido al construir la instancia de MCP Auth. Posteriormente, el servidor MCP expondrá los metadatos del recurso configurados en MCP Auth. + + + + +```python +# server.py + +# otros imports... +from mcpauth.types import ResourceServerConfig, ResourceServerMetadata + +# Define el identificador de recurso para este servidor MCP +resource_id = "http://localhost:3001" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + # Metadatos del servidor de autorización obtenidos en el paso anterior + authorization_servers=[auth_server_config], + # Alcances (Scopes) que este servidor MCP entiende + scopes_supported=[ + "create:todos", + "read:todos", + "delete:todos" + ] + ) + ) +) +``` + + + +```js +// todo-manager.ts + +// Define el identificador de recurso para este servidor MCP +const resourceId = 'http://localhost:3001'; + +// Configura MCP Auth con los metadatos del recurso protegido +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceId, + // Metadatos del servidor de autorización obtenidos en el paso anterior + authorizationServers: [authServerConfig], + // Alcances (Scopes) que este servidor MCP entiende + scopesSupported: [ + "create:todos", + "read:todos", + "delete:todos" + ] + } + } +}); +``` + + + + +### Actualiza el servidor MCP \{#update-mcp-server} + +¡Ya casi terminamos! Es hora de actualizar el servidor MCP para aplicar la ruta y función middleware de MCP Auth, luego implementar el control de acceso basado en Permisos (Permissions) para las herramientas del gestor de tareas según los Alcances (Scopes) del usuario. + +Ahora, aplica las rutas de metadatos del recurso protegido para que los clientes MCP puedan recuperar los metadatos esperados del recurso desde el servidor MCP. + + + +```python +# server.py + +# ..otros códigos + +app = Starlette( + routes=[ + # Configura las rutas de Metadatos del Recurso Protegido + # Esto expone metadatos sobre este servidor de recursos para clientes OAuth + *mcp_auth.resource_metadata_router().routes, + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +// Configura las rutas de Metadatos del Recurso Protegido +// Esto expone metadatos sobre este servidor de recursos para clientes OAuth +app.use(mcpAuth.protectedResourceMetadataRouter()); + +``` + + + +A continuación, aplicaremos el middleware MCP Auth al servidor MCP. Este middleware gestionará la Autenticación (Authentication) y Autorización (Authorization) para las solicitudes entrantes, asegurando que solo los usuarios autorizados puedan acceder a las herramientas del gestor de tareas. + + + +```python +# server.py + +# otros imports... +from starlette.middleware import Middleware + +# otros códigos... + +# Crea el middleware +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', resource=resource_id, audience=resource_id)) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # Aplica el middleware MCP Auth + Mount("/", app=mcp.streamable_http_app(), middleware=[bearer_auth]), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Aplica el middleware MCP Auth +app.use( + mcpAuth.bearerAuth('jwt', { + resource: resourceId, + audience: resourceId, + }) +); +``` + + + +En este punto, podemos actualizar las herramientas del gestor de tareas para aprovechar el middleware MCP Auth para la Autenticación (Authentication) y Autorización (Authorization). + +Actualicemos la implementación de las herramientas. + + + +```python +# server.py + +# otros imports... + +from typing import Any, List, Optional +from mcpauth.exceptions import MCPAuthBearerAuthException, BearerAuthExceptionCode +from mcpauth.types import AuthInfo, ResourceServerConfig, ResourceServerMetadata + +# Se mencionará en la siguiente sección +from service import TodoService + +def assert_user_id(auth_info: Optional[AuthInfo]) -> str: + """Asegura que auth_info contiene un ID de usuario válido y lo devuelve.""" + if not auth_info or not auth_info.subject: + raise Exception("Invalid auth info") + return auth_info.subject + +def has_required_scopes(user_scopes: List[str], required_scopes: List[str]) -> bool: + """Comprueba si el usuario tiene todos los Alcances (Scopes) requeridos.""" + return all(scope in user_scopes for scope in required_scopes) + +# Crea la instancia de TodoService +todo_service = TodoService() + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """Crear una nueva tarea. Requiere el Alcance (Scope) 'create:todos'.""" + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # Solo los usuarios con el Alcance (Scope) 'create:todos' pueden crear tareas + user_scopes = auth_info.scopes if auth_info else [] + if not has_required_scopes(user_scopes, ["create:todos"]): + raise MCPAuthBearerAuthException(BearerAuthExceptionCode.MISSING_REQUIRED_SCOPES) + + created_todo = todo_service.create_todo(content=content, owner_id=user_id) + return created_todo + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """ + Listar tareas. Los usuarios con el Alcance (Scope) 'read:todos' pueden ver todas las tareas, + de lo contrario solo pueden ver sus propias tareas. + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # Si el usuario tiene el Alcance (Scope) 'read:todos', puede acceder a todas las tareas + # Si no, solo puede acceder a sus propias tareas + user_scopes = auth_info.scopes if auth_info else [] + todo_owner_id = None if has_required_scopes(user_scopes, ["read:todos"]) else user_id + + todos = todo_service.get_all_todos(todo_owner_id) + return {"todos": todos} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """ + Eliminar una tarea por id. Los usuarios pueden eliminar sus propias tareas. + Los usuarios con el Alcance (Scope) 'delete:todos' pueden eliminar cualquier tarea. + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + todo = todo_service.get_todo_by_id(id) + + if not todo: + return {"error": "Failed to delete todo"} + + # Los usuarios solo pueden eliminar sus propias tareas + # Los usuarios con el Alcance (Scope) 'delete:todos' pueden eliminar cualquier tarea + user_scopes = auth_info.scopes if auth_info else [] + if todo.owner_id != user_id and not has_required_scopes(user_scopes, ["delete:todos"]): + return {"error": "Failed to delete todo"} + + deleted_todo = todo_service.delete_todo(id) + + if deleted_todo: + return { + "message": f"Todo {id} deleted", + "details": deleted_todo + } + else: + return {"error": "Failed to delete todo"} +``` + + + +```js +// todo-manager.ts + +// otros imports... +import assert from 'node:assert'; +import { fetchServerConfig, MCPAuth, MCPAuthBearerAuthError } from 'mcp-auth'; +import { type AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js'; + +// Se mencionará en la siguiente sección +import { TodoService } from './todo-service.js'; + +const assertUserId = (authInfo?: AuthInfo) => { + const { subject } = authInfo ?? {}; + assert(subject, 'Invalid auth info'); + return subject; +}; + +const hasRequiredScopes = (userScopes: string[], requiredScopes: string[]): boolean => { + return requiredScopes.every((scope) => userScopes.includes(scope)); +}; + +const todoService = new TodoService(); + +server.tool( + 'create-todo', + 'Crear una nueva tarea', + { content: z.string() }, + ({ content }: { content: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * Solo los usuarios con el Alcance (Scope) 'create:todos' pueden crear tareas + */ + if (!hasRequiredScopes(authInfo?.scopes ?? [], ['create:todos'])) { + throw new MCPAuthBearerAuthError('missing_required_scopes'); + } + + const createdTodo = todoService.createTodo({ content, ownerId: userId }); + + return { + content: [{ type: 'text', text: JSON.stringify(createdTodo) }], + }; + } +); + +server.tool('get-todos', 'Listar todas las tareas', ({ authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * Si el usuario tiene el Alcance (Scope) 'read:todos', puede acceder a todas las tareas (todoOwnerId = undefined) + * Si no, solo puede acceder a sus propias tareas (todoOwnerId = userId) + */ + const todoOwnerId = hasRequiredScopes(authInfo?.scopes ?? [], ['read:todos']) + ? undefined + : userId; + + const todos = todoService.getAllTodos(todoOwnerId); + + return { + content: [{ type: 'text', text: JSON.stringify(todos) }], + }; +}); + +server.tool( + 'delete-todo', + 'Eliminar una tarea por id', + { id: z.string() }, + ({ id }: { id: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + const todo = todoService.getTodoById(id); + + if (!todo) { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Failed to delete todo' }) }], + }; + } + + /** + * Los usuarios solo pueden eliminar sus propias tareas + * Los usuarios con el Alcance (Scope) 'delete:todos' pueden eliminar cualquier tarea + */ + if (todo.ownerId !== userId && !hasRequiredScopes(authInfo?.scopes ?? [], ['delete:todos'])) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ error: 'Failed to delete todo' }), + }, + ], + }; + } + + const deletedTodo = todoService.deleteTodo(id); + + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + message: `Todo ${id} deleted`, + details: deletedTodo, + }), + }, + ], + }; + } +); +``` + + + +Ahora, crea el "Servicio de tareas" usado en el código anterior para implementar la funcionalidad relacionada: + + + + +Crea el archivo `service.py` para el servicio de tareas: + +```python +""" +Un servicio de tareas simple para fines demostrativos. +Utiliza una lista en memoria para almacenar tareas. +""" + +from datetime import datetime +from typing import List, Optional, Dict, Any +import random +import string + +class Todo: + """Representa una tarea.""" + + def __init__(self, id: str, content: str, owner_id: str, created_at: str): + self.id = id + self.content = content + self.owner_id = owner_id + self.created_at = created_at + + def to_dict(self) -> Dict[str, Any]: + """Convierte la tarea a diccionario para serialización JSON.""" + return { + "id": self.id, + "content": self.content, + "ownerId": self.owner_id, + "createdAt": self.created_at + } + + +class TodoService: + """Un servicio de tareas simple para fines demostrativos.""" + + def __init__(self): + self._todos: List[Todo] = [] + + def get_all_todos(self, owner_id: Optional[str] = None) -> List[Dict[str, Any]]: + """ + Obtiene todas las tareas, opcionalmente filtradas por owner_id. + + Args: + owner_id: Si se proporciona, solo devuelve tareas de este usuario + + Returns: + Lista de diccionarios de tareas + """ + if owner_id: + filtered_todos = [todo for todo in self._todos if todo.owner_id == owner_id] + return [todo.to_dict() for todo in filtered_todos] + return [todo.to_dict() for todo in self._todos] + + def get_todo_by_id(self, todo_id: str) -> Optional[Todo]: + """ + Obtiene una tarea por su ID. + + Args: + todo_id: El ID de la tarea a recuperar + + Returns: + Objeto Todo si se encuentra, None en caso contrario + """ + for todo in self._todos: + if todo.id == todo_id: + return todo + return None + + def create_todo(self, content: str, owner_id: str) -> Dict[str, Any]: + """ + Crea una nueva tarea. + + Args: + content: El contenido de la tarea + owner_id: El ID del usuario propietario de la tarea + + Returns: + Representación en diccionario de la tarea creada + """ + todo = Todo( + id=self._generate_id(), + content=content, + owner_id=owner_id, + created_at=datetime.now().isoformat() + ) + self._todos.append(todo) + return todo.to_dict() + + def delete_todo(self, todo_id: str) -> Optional[Dict[str, Any]]: + """ + Elimina una tarea por su ID. + + Args: + todo_id: El ID de la tarea a eliminar + + Returns: + Representación en diccionario de la tarea eliminada si se encuentra, None en caso contrario + """ + for i, todo in enumerate(self._todos): + if todo.id == todo_id: + deleted_todo = self._todos.pop(i) + return deleted_todo.to_dict() + return None + + def _generate_id(self) -> str: + """Genera un ID aleatorio para una tarea.""" + return ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)) +``` + + + + +Crea el archivo `todo-service.ts` para el servicio de tareas: + +```ts +// todo-service.ts + +type Todo = { + id: string; + content: string; + ownerId: string; + createdAt: string; +}; + +/** + * Un servicio de tareas simple para fines demostrativos. + * Usa un array en memoria para almacenar tareas + */ +export class TodoService { + private readonly todos: Todo[] = []; + + getAllTodos(ownerId?: string): Todo[] { + if (ownerId) { + return this.todos.filter((todo) => todo.ownerId === ownerId); + } + return this.todos; + } + + getTodoById(id: string): Todo | undefined { + return this.todos.find((todo) => todo.id === id); + } + + createTodo({ content, ownerId }: { content: string; ownerId: string }): Todo { + const todo: Todo = { + id: this.genId(), + content, + ownerId, + createdAt: new Date().toISOString(), + }; + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + this.todos.push(todo); + return todo; + } + + deleteTodo(id: string): Todo | undefined { + const index = this.todos.findIndex((todo) => todo.id === id); + + if (index === -1) { + return undefined; + } + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + const [deleted] = this.todos.splice(index, 1); + return deleted; + } + + private genId(): string { + return Math.random().toString(36).slice(2, 10); + } +} +``` + + + + +🎉 ¡Felicidades! ¡Hemos implementado con éxito un servidor MCP completo con Autenticación (Authentication) y Autorización (Authorization)! + +También puedes consultar nuestro código de ejemplo como referencia: + + + + +:::info +Consulta el [repositorio del SDK de MCP Auth para Python](https://github.com/mcp-auth/python/tree/master/samples/current/todo-manager) para ver el código completo del servidor MCP (versión OIDC). +::: + + + + +:::info +Consulta el [repositorio del SDK de MCP Auth para Node.js](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) para ver el código completo del servidor MCP (versión OIDC). +::: + + + + +## Punto de control: Ejecuta las herramientas `todo-manager` \{#checkpoint-run-the-todo-manager-tools} + +Reinicia tu servidor MCP y abre MCP inspector en tu navegador. Cuando hagas clic en el botón "Connect", deberías ser redirigido a la página de inicio de sesión de tu servidor de autorización. + +Una vez que inicies sesión y regreses a MCP inspector, repite las acciones que hicimos en el punto de control anterior para ejecutar las herramientas del gestor de tareas. Esta vez, puedes usar estas herramientas con tu identidad de usuario autenticada. El comportamiento de las herramientas dependerá de los Roles (Roles) y Permisos (Permissions) asignados a tu usuario: + +- Si has iniciado sesión como **User** (con solo el Alcance (Scope) `create:todos`): + + - Puedes crear nuevas tareas usando la herramienta `create-todo` + - Solo puedes ver y eliminar tus propias tareas + - No podrás ver ni eliminar tareas de otros usuarios + +- Si has iniciado sesión como **Admin** (con todos los Alcances (Scopes): `create:todos`, `read:todos`, `delete:todos`): + - Puedes crear nuevas tareas + - Puedes ver todas las tareas del sistema usando la herramienta `get-todos` + - Puedes eliminar cualquier tarea usando la herramienta `delete-todo`, sin importar quién la creó + +Puedes probar estos diferentes niveles de Permisos (Permissions) haciendo lo siguiente: + +1. Cierra la sesión actual (haz clic en el botón "Disconnect" en MCP inspector) +2. Inicia sesión con otra cuenta de usuario que tenga diferentes Roles (Roles) / Permisos (Permissions) +3. Prueba las mismas herramientas nuevamente para observar cómo cambia el comportamiento según los Permisos (Permissions) del usuario + +Esto demuestra cómo funciona el control de acceso basado en roles (RBAC) en la práctica, donde diferentes usuarios tienen diferentes niveles de acceso a la funcionalidad del sistema. + +![Resultado de la herramienta gestor de tareas en MCP inspector](/docs-assets/images/tutorials/todo-manager/result.png) + + + + +:::info +Consulta el [repositorio del SDK de MCP Auth para Python](https://github.com/mcp-auth/python) para ver el código completo del servidor MCP (versión OIDC). +::: + + + + +:::info +Consulta el [repositorio del SDK de MCP Auth para Node.js](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) para ver el código completo del servidor MCP (versión OIDC). +::: + + + + +## Notas finales \{#closing-notes} + +🎊 ¡Felicidades! Has completado con éxito el tutorial. Recapitulemos lo que hemos hecho: + +- Configuración de un servidor MCP básico con herramientas de gestión de tareas (`create-todo`, `get-todos`, `delete-todo`) +- Implementación de control de acceso basado en roles (RBAC) con diferentes niveles de Permisos (Permissions) para usuarios y administradores +- Integración del servidor MCP con un servidor de autorización usando MCP Auth +- Configuración de MCP Inspector para autenticar usuarios y usar tokens de acceso con Alcances (Scopes) para llamar a herramientas + +Asegúrate de consultar otros tutoriales y documentación para aprovechar al máximo MCP Auth. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/README.mdx b/i18n/fr/docusaurus-plugin-content-docs/current/README.mdx new file mode 100644 index 0000000..840b13f --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/README.mdx @@ -0,0 +1,297 @@ +--- +sidebar_position: 1 +sidebar_label: Commencer +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# Commencer + +:::info Prise en charge de la spécification d’autorisation MCP +Cette version prend en charge la [spécification d’autorisation MCP (version 2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization). +::: + + +## Choisir un fournisseur compatible OAuth 2.1 ou OpenID Connect \{#choose-a-compatible-oauth-2-1-or-openid-connect-provider} + +La spécification MCP comporte [des exigences spécifiques](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#standards-compliance) pour l’autorisation. Le mécanisme d’autorisation est basé sur des spécifications établies, mettant en œuvre un sous-ensemble sélectionné de leurs fonctionnalités afin de garantir la sécurité et l’interopérabilité tout en maintenant la simplicité : + +- OAuth 2.1 IETF DRAFT ([draft-ietf-oauth-v2-1-13](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13)) +- Métadonnées du serveur d’autorisation OAuth 2.0 ([RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)) +- Protocole d’enregistrement dynamique du client OAuth 2.0 ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) +- Métadonnées de ressource protégée OAuth 2.0 ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)) + +Ces spécifications fonctionnent ensemble pour fournir un cadre d’autorisation sécurisé et standardisé pour les implémentations MCP. + +Vous pouvez consulter la [liste des fournisseurs compatibles MCP](/provider-list) pour vérifier si votre fournisseur est pris en charge. + +## Installer MCP Auth SDK \{#install-mcp-auth-sdk} + +MCP Auth est disponible pour Python et TypeScript. Faites-nous savoir si vous avez besoin d’un support pour un autre langage ou framework ! + + + + +```bash +pip install mcpauth +``` + +Ou tout autre gestionnaire de paquets que vous préférez, comme pipenv ou poetry. + + + + +```bash +npm install mcp-auth +``` + +Ou tout autre gestionnaire de paquets que vous préférez, comme pnpm ou yarn. + + + + +## Initialiser MCP Auth \{#init-mcp-auth} + +La première étape consiste à définir votre identifiant de ressource et à configurer le serveur d’autorisation qui sera approuvé pour l’authentification. MCP Auth fonctionne désormais en mode serveur de ressources, conformément à la spécification MCP mise à jour qui exige les métadonnées de ressource protégée OAuth 2.0 (RFC 9728). + +Si votre fournisseur est conforme à : + +- [Métadonnées du serveur d’autorisation OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8414) +- [Découverte OpenID Connect](https://openid.net/specs/openid-connect-discovery-1_0.html) + +Vous pouvez utiliser la fonction intégrée pour récupérer les métadonnées et initialiser l’instance MCP Auth : + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType, ResourceServerConfig, ResourceServerMetadata +from mcpauth.utils import fetch_server_config + +# 1. Définir votre identifiant de ressource et récupérer la configuration de son serveur d’autorisation de confiance. +resource_id = "https://api.example.com/notes" +auth_server_config = fetch_server_config("https://auth.logto.io/oidc", AuthServerType.OIDC) + +# 2. Initialiser MCPAuth en mode serveur de ressources. +# `protected_resources` peut être un objet unique ou une liste pour plusieurs ressources. +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +// 1. Définir votre identifiant de ressource et récupérer la configuration de son serveur d’autorisation de confiance. +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +// 2. Initialiser MCPAuth en mode serveur de ressources. +// `protectedResources` peut être un objet unique ou un tableau pour plusieurs ressources. +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +Pour d’autres façons de configurer les métadonnées du serveur d’autorisation, y compris les URL de métadonnées personnalisées, la transpilation de données ou la spécification manuelle des métadonnées, consultez [Autres façons de configurer MCP Auth](./configure-server/mcp-auth.mdx#other-ways). + +## Monter le point de terminaison des métadonnées de ressource protégée \{#mount-the-protected-resource-metadata-endpoint} + +Pour se conformer à la spécification MCP mise à jour, MCP Auth monte le point de terminaison des métadonnées de ressource protégée OAuth 2.0 (RFC 9728) sur votre serveur MCP. Ce point de terminaison permet aux clients de découvrir : + +- Quels serveurs d’autorisation peuvent émettre des jetons valides pour vos ressources protégées +- Quelles portées sont prises en charge pour chaque ressource +- D’autres métadonnées nécessaires à une validation correcte des jetons + +Le chemin du point de terminaison est automatiquement déterminé par le composant chemin de votre identifiant de ressource : + +- **Sans chemin** : `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **Avec chemin** : `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + +Le serveur MCP **agit désormais comme un serveur de ressources** qui valide les jetons et fournit des métadonnées sur ses ressources protégées, tout en s’appuyant entièrement sur des serveurs d’autorisation externes pour l’authentification et l’autorisation. + +Vous pouvez utiliser la méthode fournie par le SDK pour monter ce point de terminaison : + + + + +```python +from starlette.applications import Starlette + +# Monter le routeur pour servir les métadonnées de ressource protégée. +# Pour la ressource "https://api.example.com" → endpoint: /.well-known/oauth-protected-resource +# Pour la ressource "https://api.example.com/notes" → endpoint: /.well-known/oauth-protected-resource/notes +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// Monter le routeur pour servir les métadonnées de ressource protégée. +// Pour la ressource "https://api.example.com" → endpoint: /.well-known/oauth-protected-resource +// Pour la ressource "https://api.example.com/notes" → endpoint: /.well-known/oauth-protected-resource/notes +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + + +## Utiliser le middleware d’authentification Bearer \{#use-the-bearer-auth-middleware} + +Une fois l’instance MCP Auth initialisée, vous pouvez appliquer le middleware d’authentification Bearer pour protéger vos routes MCP. Le middleware nécessite désormais de spécifier à quelle ressource appartient le point de terminaison, permettant ainsi une validation correcte du jeton : + +:::note Validation de l’audience +Le paramètre `audience` est **requis** par la spécification OAuth 2.0 pour une validation sécurisée des jetons. Cependant, il est actuellement **optionnel** afin de maintenir la compatibilité avec les serveurs d’autorisation qui ne prennent pas encore en charge les identifiants de ressource. Pour des raisons de sécurité, **incluez toujours le paramètre audience** lorsque cela est possible. Les versions futures rendront la validation de l’audience obligatoire pour une conformité totale à la spécification. +::: + + + + +```python +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount + +# Créer le middleware pour protéger votre serveur MCP avec la politique spécifique à la ressource. +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', + resource=resource_id, + audience=resource_id, # Activez la validation de l’audience pour la sécurité + required_scopes=['read:notes'] +)) + +# Monter le routeur pour servir les métadonnées de ressource protégée et protéger le serveur MCP. +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # Protéger le serveur MCP avec le middleware Bearer auth. + Mount("/", app=mcp.sse_app(), middleware=[bearer_auth]), + ], +) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// Monter le routeur pour servir les métadonnées de ressource protégée. +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Protéger un point de terminaison API avec la politique spécifique à la ressource. +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, // Activez la validation de l’audience pour la sécurité + requiredScopes: ['read:notes'], + }), + (req, res) => { + // Si le jeton est valide, `req.auth` est renseigné avec ses revendications. + console.log('Infos d’authentification :', req.auth); + res.json({ notes: [] }); + }, +); + +app.listen(3000); +``` + + + + +Dans les exemples ci-dessus, nous spécifions le type de jeton `jwt` et l’identifiant de ressource. Le middleware validera automatiquement le jeton JWT auprès des serveurs d’autorisation de confiance configurés pour cette ressource spécifique et renseignera les informations de l’utilisateur authentifié. + +:::info +Jamais entendu parler de JWT (JSON Web Token) auparavant ? Pas d’inquiétude, vous pouvez continuer à lire la documentation et nous l’expliquerons en temps voulu. Vous pouvez également consulter [Auth Wiki](https://auth.wiki/jwt) pour une introduction rapide. +::: + +Pour plus d’informations sur la configuration de l’authentification Bearer, consultez [Configurer Bearer auth](./configure-server/bearer-auth.mdx). + +## Récupérer les informations d’authentification dans votre implémentation MCP \{#retrieve-the-auth-info-in-your-mcp-implementation} + +Une fois le middleware d’authentification Bearer appliqué, vous pouvez accéder aux informations de l’utilisateur (ou de l’identité) authentifié dans votre implémentation MCP : + + + + +MCP Auth stockera les informations de l’utilisateur authentifié dans une variable de contexte après une authentification réussie une fois le middleware Bearer appliqué. Vous pouvez y accéder dans vos gestionnaires d’outils MCP comme ceci : + +```python +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP() + +# Initialiser avec MCP Auth comme montré dans les exemples précédents +# ... + +@mcp.tool() +def add(a: int, b: int): + """ + Un outil qui additionne deux nombres. + Les informations de l’utilisateur authentifié seront disponibles dans le contexte. + """ + auth_info = mcp_auth.auth_info # Accéder aux infos d’authentification dans le contexte courant + if auth_info: + print(f"Utilisateur authentifié : {auth_info.claims}") + return a + b +``` + + + + +Le second argument du gestionnaire d’outil contiendra l’objet `authInfo`, qui inclut les informations de l’utilisateur authentifié : + +```ts +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { z } from 'zod'; + +const server = new McpServer(/* ... */); + +// Initialiser avec MCP Auth comme montré dans les exemples précédents +// ... + +server.tool('add', { a: z.number(), b: z.number() }, async ({ a, b }, { authInfo }) => { + // Vous pouvez maintenant utiliser l’objet `authInfo` pour accéder aux informations authentifiées +}); +``` + + + + +## Prochaines étapes \{#next-steps} + +Continuez la lecture pour découvrir un exemple de bout en bout sur la façon d’intégrer MCP Auth à votre serveur MCP, et comment gérer le flux d’authentification côté clients MCP. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx b/i18n/fr/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx new file mode 100644 index 0000000..85a4dda --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx @@ -0,0 +1,280 @@ +--- +sidebar_position: 2 +sidebar_label: Auth Bearer +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# Configurer l’authentification Bearer dans le serveur MCP + +Avec la dernière spécification MCP, votre serveur MCP agit comme un **Serveur de ressources** qui valide les jetons d’accès pour les ressources protégées. MCP Auth propose différentes façons de configurer l’autorisation Bearer : + +- Mode [JWT (JSON Web Token)](https://auth.wiki/jwt) : Une méthode d’autorisation intégrée qui vérifie les JWT avec des assertions de revendications. +- Mode personnalisé : Vous permet d’implémenter votre propre logique d’autorisation. + +Le middleware d’authentification Bearer nécessite désormais de spécifier à quelle ressource appartient l’endpoint, permettant ainsi une validation correcte du jeton par rapport aux serveurs d’autorisation configurés. + +## Configurer l’authentification Bearer en mode JWT \{#configure-bearer-auth-with-jwt-mode} + +Si votre fournisseur OAuth / OIDC émet des JWT pour l’autorisation, vous pouvez utiliser le mode JWT intégré dans MCP Auth. Il vérifie la signature du JWT, l’expiration et d’autres revendications que vous spécifiez ; puis il renseigne les informations d’authentification dans le contexte de la requête pour un traitement ultérieur dans votre implémentation MCP. + +### Validation de la portée (Scope) \{#scope-validation} + +Voici un exemple de validation de portée basique : + + + + +```python +from mcpauth import MCPAuth +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP("MyMCPServer") +mcp_auth = MCPAuth( + # Initialisez avec la configuration de votre serveur d’authentification +) +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", # Spécifiez à quelle ressource appartient cet endpoint + audience="https://api.example.com", # Activez la validation de l’audience pour la sécurité + required_scopes=["read", "write"] # [!code highlight] +) + +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + /* ... */ +}); +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // Spécifiez à quelle ressource appartient cet endpoint + audience: 'https://api.example.com', // Activez la validation de l’audience pour la sécurité + requiredScopes: ['read', 'write'] // [!code highlight] +}); + +app.use('/mcp', bearerAuth, (req, res) => { + // Maintenant `req.auth` contient les infos d’authentification + console.log(req.auth); +}); +``` + + + + +Dans l’exemple ci-dessus, nous avons spécifié que le JWT nécessite les portées `read` et `write`. Si le JWT ne contient **aucune** de ces portées, la requête sera rejetée avec une erreur 403 Forbidden. + +### Validation de l’audience (RFC 8707) \{#audience-validation-rfc-8707} + +Pour une validation sécurisée du jeton, vous devez toujours inclure la validation de l’audience en spécifiant le paramètre `audience`. Cela valide la revendication `aud` (audience) dans le JWT pour s’assurer que le jeton a été émis spécifiquement pour la ressource de votre serveur MCP. + +:::note Audience Validation +Le paramètre `audience` est **requis** par la spécification OAuth 2.0 pour une validation sécurisée du jeton. Cependant, il est actuellement **optionnel** afin de maintenir la compatibilité avec les serveurs d’autorisation qui ne prennent pas encore en charge les identifiants de ressource. Pour des raisons de sécurité, **incluez toujours le paramètre audience** lorsque cela est possible. Les versions futures rendront la validation de l’audience obligatoire pour se conformer pleinement à la spécification. +::: + +La valeur de l’audience doit généralement correspondre à votre identifiant de ressource : + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", # Spécifiez à quelle ressource appartient cet endpoint + audience="https://api.example.com", # Activez la validation de l’audience pour la sécurité [!code highlight] + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // Spécifiez à quelle ressource appartient cet endpoint + audience: 'https://api.example.com', // Activez la validation de l’audience pour la sécurité [!code highlight] + requiredScopes: ['read', 'write'], +}); +``` + + + + +Dans l’exemple ci-dessus, MCP Auth validera **à la fois** la revendication `aud` dans le JWT et les portées requises. + +### Fournir des options personnalisées à la vérification JWT \{#provide-custom-options-to-the-jwt-verification} + +Vous pouvez également fournir des options personnalisées à la bibliothèque de vérification JWT sous-jacente : + + + + +Dans le SDK Python, nous utilisons [PyJWT](https://pyjwt.readthedocs.io/en/stable/) pour la vérification des JWT. Vous pouvez utiliser les options suivantes : + +- `leeway` : Autorise une certaine tolérance lors de la vérification de l’expiration du JWT (en secondes). La valeur par défaut est de 60 secondes. + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", + audience="https://api.example.com", + required_scopes=["read", "write"], + leeway=10, # Réduisez le décalage d’horloge en autorisant 10 secondes de tolérance [!code highlight] +) +``` + + + + +Dans le SDK Node.js, nous utilisons la bibliothèque [jose](https://github.com/panva/jose) pour la vérification des JWT. Vous pouvez fournir les options suivantes : + +- `jwtVerify` : Options pour le processus de vérification JWT (fonction `jwtVerify` de `jose`). +- `remoteJwtSet` : Options pour la récupération du jeu de JWT distant (fonction `createRemoteJWKSet` de `jose`). + +```ts {5-10} +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', + requiredScopes: ['read', 'write'], + jwtVerify: { + clockTolerance: 60, // Autorise un décalage d’horloge de 60 secondes + }, + remoteJwtSet: { + timeoutDuration: 10 * 1000, // Délai d’attente de 10 secondes pour la récupération du JWT distant + }, +}); +``` + + + + +## Configurer l’authentification Bearer avec une vérification personnalisée \{#configure-bearer-auth-with-custom-verification} + +Si votre fournisseur OAuth / OIDC n’émet pas de JWT, ou si vous souhaitez implémenter votre propre logique d’autorisation, MCP Auth vous permet de créer une fonction de vérification personnalisée : + +:::info +Puisque le middleware d’authentification Bearer vérifiera l’émetteur (`iss`), l’audience (`aud`) et les portées requises (`scope`) avec le résultat de la vérification fourni, il n’est pas nécessaire d’implémenter ces vérifications dans votre fonction de vérification personnalisée. Vous pouvez vous concentrer sur la vérification de la validité du jeton (par exemple, signature, expiration, etc.) et retourner l’objet d’informations d’authentification. +::: + + + + +```python +from mcpauth.exceptions import MCPAuthJwtVerificationException, MCPAuthJwtVerificationExceptionCode +from mcpauth.types import AuthInfo + +async def custom_verification(token: str) -> AuthInfo: + # Implémentez ici votre logique de vérification personnalisée + info = await verify_token(token) + if not info: + raise MCPAuthJwtVerificationException( + MCPAuthJwtVerificationExceptionCode.JWT_VERIFICATION_FAILED + ) + return info # Retournez l’objet d’informations d’authentification + +bearer_auth = mcp_auth.bearer_auth_middleware( + custom_verification, + resource="https://api.example.com", + audience="https://api.example.com", # Activez la validation de l’audience pour la sécurité + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth( + async (token) => { + // Implémentez ici votre logique de vérification personnalisée + const info = await verifyToken(token); + if (!info) { + throw new MCPAuthJwtVerificationError('jwt_verification_failed'); + } + return info; // Retournez l’objet d’informations d’authentification + }, + { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // Activez la validation de l’audience pour la sécurité + requiredScopes: ['read', 'write'] + } +); +``` + + + + +## Appliquer l’authentification Bearer dans votre serveur MCP \{#apply-bearer-auth-in-your-mcp-server} + +Pour protéger votre serveur MCP avec l’authentification Bearer, vous devez appliquer le middleware Bearer auth à votre instance de serveur MCP. + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", + audience="https://api.example.com", # Activez la validation de l’audience pour la sécurité + required_scopes=["read", "write"] +) +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```js +const app = express(); +app.use(mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // Activez la validation de l’audience pour la sécurité + requiredScopes: ['read', 'write'] +})); +``` + + + + +Cela garantira que toutes les requêtes entrantes sont authentifiées et autorisées selon la configuration Bearer auth, et que les informations d’authentification seront disponibles dans le contexte de la requête. + +Vous pouvez ensuite accéder à ces informations dans votre implémentation du serveur MCP : + + + + +```python +@mcp.tool() +async def whoami() -> dict: + # `mcp_auth.auth_info` est l’objet de contexte pour la requête en cours + auth_info = mcp_auth.auth_info + print(f"Utilisateur authentifié : {auth_info.subject}") + return {"subject": auth_info.subject} +``` + + + + +```js +// `authInfo` sera transmis depuis l’objet `req.auth` +server.tool('whoami', ({ authInfo }) => { + console.log(`Utilisateur authentifié : ${authInfo.subject}`); + return { subject: authInfo.subject }; +}); +``` + + + diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx b/i18n/fr/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx new file mode 100644 index 0000000..e0e5277 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx @@ -0,0 +1,290 @@ +--- +sidebar_position: 1 +sidebar_label: MCP Auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# Configurer MCP Auth sur le serveur MCP + +Avec la dernière [Spécification MCP (2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18), votre serveur MCP agit en tant que **Serveur de ressources** qui valide les jetons d’accès (Access tokens) émis par des serveurs d’autorisation externes. + +Pour configurer MCP Auth, deux étapes principales sont nécessaires : +1. **Configurer les métadonnées du serveur d’autorisation** — Définir quels serveurs d’autorisation peuvent émettre des jetons valides pour votre serveur MCP et indiquer aux clients MCP où obtenir les jetons d’accès (Access tokens) +2. **Configurer les métadonnées de la ressource protégée** — Définir votre serveur MCP comme une ressource protégée avec les portées (Scopes) prises en charge + +## Étape 1 : Configurer les métadonnées du serveur d’autorisation \{#configure-authorization-server-metadata} + +### Récupération automatique des métadonnées \{#automatic-metadata-fetching} + +La façon la plus simple de configurer les métadonnées du serveur d’autorisation est d’utiliser les fonctions intégrées qui récupèrent les métadonnées depuis les URLs bien connues. Si votre fournisseur est conforme à l’une des normes suivantes : + +- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +Vous pouvez utiliser `fetchServerConfig` pour récupérer automatiquement les métadonnées en fournissant l’URL de l’`issuer` : + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +# Récupérer les métadonnées du serveur d’autorisation +auth_server_config = fetch_server_config( + "https://auth.logto.io/oidc", + AuthServerType.OIDC # ou AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +// Récupérer les métadonnées du serveur d’autorisation +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); // ou 'oauth' +``` + + + + +Si votre issuer inclut un chemin, le comportement diffère légèrement entre OAuth 2.0 et OpenID Connect : + +- **OAuth 2.0** : L’URL bien connue est ajoutée au **domaine** de l’issuer. Par exemple, si votre issuer est `https://my-project.logto.app/oauth`, l’URL bien connue sera `https://auth.logto.io/.well-known/oauth-authorization-server/oauth`. +- **OpenID Connect** : L’URL bien connue est ajoutée directement à l’**issuer**. Par exemple, si votre issuer est `https://my-project.logto.app/oidc`, l’URL bien connue sera `https://auth.logto.io/oidc/.well-known/openid-configuration`. + +### Autres méthodes pour configurer les métadonnées du serveur d’autorisation \{#other-ways} + +#### Transpilation personnalisée des données \{#custom-data-transpilation} + +Dans certains cas, les métadonnées retournées par le fournisseur peuvent ne pas être conformes au format attendu. Si vous êtes certain que le fournisseur est conforme, vous pouvez utiliser l’option `transpile_data` pour modifier les métadonnées avant leur utilisation : + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +auth_server_config = fetch_server_config( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfig('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +Cela vous permet de modifier l’objet de métadonnées avant son utilisation par MCP Auth. Par exemple, vous pouvez ajouter ou supprimer des champs, modifier leurs valeurs ou les convertir dans un autre format. + +#### Récupérer les métadonnées depuis une URL spécifique \{#fetch-metadata-from-a-specific-url} + +Si votre fournisseur dispose d’une URL de métadonnées spécifique plutôt que des URLs standard, vous pouvez l’utiliser de manière similaire : + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC # ou AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfigByWellKnownUrl } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { type: 'oidc' }); // ou 'oauth' +``` + + + + +#### Récupérer les métadonnées depuis une URL spécifique avec transpilation personnalisée \{#fetch-metadata-from-a-specific-url-with-custom-data-transpilation} + +Dans certains cas, la réponse du fournisseur peut être mal formée ou non conforme au format attendu. Si vous êtes certain que le fournisseur est conforme, vous pouvez transpiler les métadonnées via l’option de configuration : + + + + +```python +from mcpauth.config import AuthServerType, fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +#### Fournir manuellement les métadonnées \{#manually-provide-metadata} + +Si votre fournisseur ne prend pas en charge la récupération des métadonnées, vous pouvez fournir manuellement l’objet de métadonnées : + + + + +```python +from mcpauth.config import AuthServerConfig, AuthServerType, AuthorizationServerMetadata + +auth_server_config = AuthServerConfig( + type=AuthServerType.OIDC, # ou AuthServerType.OAUTH + metadata=AuthorizationServerMetadata( + issuer='', + authorization_endpoint='', + # ... autres champs de métadonnées + ), +) +``` + + + + +```ts +const authServerConfig = { + metadata: { + issuer: '', + // Les champs de métadonnées doivent être en camelCase + authorizationEndpoint: '', + // ... autres champs de métadonnées + }, + type: 'oidc', // ou 'oauth' +}; +``` + + + + +## Étape 2 : Configurer les métadonnées de la ressource protégée \{#configure-protected-resource-metadata} + +Après avoir configuré les métadonnées du serveur d’autorisation, vous devez initialiser MCPAuth en tant que Serveur de ressources en définissant les métadonnées de vos ressources protégées. + +Cette étape suit la spécification [RFC 9728 (OAuth 2.0 Protected Resource Metadata)](https://datatracker.ietf.org/doc/html/rfc9728) pour décrire votre serveur MCP comme une ressource protégée : + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import ResourceServerConfig, ResourceServerMetadata + +# Définir l’identifiant de votre ressource +resource_id = "https://api.example.com/notes" + +# Initialiser MCPAuth en mode serveur de ressources +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], # Utilisation de la config de l’étape 1 + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth } from 'mcp-auth'; + +// Définir l’identifiant de votre ressource +const resourceIdentifier = 'https://api.example.com/notes'; + +// Initialiser MCPAuth en mode serveur de ressources +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], // Utilisation de la config de l’étape 1 + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +Pour plusieurs ressources, vous pouvez fournir un tableau de ressources protégées, chacune avec sa propre configuration de métadonnées. + +La configuration ci-dessus couvre la configuration de base. Pour des paramètres de métadonnées plus avancés, voir [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata). + +## Étape 3 : Monter le point de terminaison des métadonnées de la ressource protégée \{#mount-the-protected-resource-metadata-endpoint} + +Montez le routeur pour servir le point de terminaison des métadonnées de la ressource protégée. Le chemin du point de terminaison est automatiquement déterminé par le composant chemin de votre identifiant de ressource : + +- **Sans chemin** : `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **Avec chemin** : `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + + + + +```python +from starlette.applications import Starlette +from mcpauth import MCPAuth + +mcp_auth = MCPAuth({/* ... */}) + +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +const mcpAuth = new MCPAuth({/* ... */}); + +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/README.md new file mode 100644 index 0000000..8db5041 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/README.md @@ -0,0 +1,59 @@ +--- +sidebar_label: SDK Node.js +--- + +# Référence du SDK MCP Auth Node.js + +## Classes {#classes} + +- [MCPAuth](/references/js/classes/MCPAuth.md) +- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) +- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) +- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) +- [MCPAuthError](/references/js/classes/MCPAuthError.md) +- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) + +## Alias de types {#type-aliases} + +- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) +- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) +- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) +- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) +- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) +- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) +- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) +- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) +- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) +- [AuthServerType](/references/js/type-aliases/AuthServerType.md) +- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) +- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) +- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) +- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) +- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) +- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) +- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) +- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) +- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) +- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) +- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) +- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) + +## Variables {#variables} + +- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) +- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) +- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) +- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) +- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) +- [defaultValues](/references/js/variables/defaultValues.md) +- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) +- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) +- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) +- [validateServerConfig](/references/js/variables/validateServerConfig.md) + +## Fonctions {#functions} + +- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) +- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) +- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) +- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md new file mode 100644 index 0000000..f26dd3f --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md @@ -0,0 +1,299 @@ +--- +sidebar_label: MCPAuth +--- + +# Classe : MCPAuth + +La classe principale de la bibliothèque mcp-auth. Elle agit comme une fabrique et un registre pour créer des politiques d’authentification pour vos ressources protégées. + +Elle est initialisée avec vos configurations serveur et fournit une méthode `bearerAuth` pour générer un middleware Express pour l’authentification basée sur les jetons. + +## Exemple {#example} + +### Utilisation en mode `resource server` {#usage-in-resource-server-mode} + +C’est l’approche recommandée pour les nouvelles applications. + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); + +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +const mcpAuth = new MCPAuth({ + // `protectedResources` peut être un seul objet de configuration ou un tableau de ceux-ci. + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); + +// Monter le routeur pour gérer les métadonnées des ressources protégées +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Protéger un point de terminaison API pour la ressource configurée +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, // Spécifiez à quelle ressource ce point de terminaison appartient + audience: resourceIdentifier, // Facultatif, valider la revendication 'aud' + requiredScopes: ['read:notes'], + }), + (req, res) => { + console.log('Infos Auth :', req.auth); + res.json({ notes: [] }); + }, +); +``` + +### Utilisation héritée en mode `authorization server` (Obsolète) {#legacy-usage-in-authorization-server-mode-deprecated} + +Cette approche est prise en charge pour la rétrocompatibilité. + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + server: await fetchServerConfig( + 'https://auth.logto.io/oidc', + { type: 'oidc' } + ), +}); + +// Monter le routeur pour gérer les métadonnées héritées du serveur d’autorisation +app.use(mcpAuth.delegatedRouter()); + +// Protéger un point de terminaison en utilisant la politique par défaut +app.get( + '/mcp', + mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), + (req, res) => { + console.log('Infos Auth :', req.auth); + // Traiter la requête MCP ici + }, +); +``` + +## Constructeurs {#constructors} + +### Constructeur {#constructor} + +```ts +new MCPAuth(config: MCPAuthConfig): MCPAuth; +``` + +Crée une instance de MCPAuth. +Elle valide toute la configuration en amont pour échouer rapidement en cas d’erreur. + +#### Paramètres {#parameters} + +##### config {#config} + +[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) + +La configuration d’authentification. + +#### Retourne {#returns} + +`MCPAuth` + +## Propriétés {#properties} + +### config {#config} + +```ts +readonly config: MCPAuthConfig; +``` + +La configuration d’authentification. + +## Méthodes {#methods} + +### bearerAuth() {#bearerauth} + +#### Signature d’appel {#call-signature} + +```ts +bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; +``` + +Crée un gestionnaire d’authentification Bearer (middleware Express) qui vérifie le jeton d’accès dans l’en-tête +`Authorization` de la requête. + +##### Paramètres {#parameters} + +###### verifyAccessToken {#verifyaccesstoken} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +Une fonction qui vérifie le jeton d’accès. Elle doit accepter le +jeton d’accès sous forme de chaîne et retourner une promesse (ou une valeur) qui se résout avec le résultat de la vérification. + +**Voir** + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) pour la définition du type de la fonction +`verifyAccessToken`. + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> + +Configuration optionnelle pour le gestionnaire d’authentification Bearer. + +**Voir** + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) pour les options de configuration disponibles (à l’exception de +`verifyAccessToken` et `issuer`). + +##### Retourne {#returns} + +`RequestHandler` + +Une fonction middleware Express qui vérifie le jeton d’accès et ajoute le +résultat de la vérification à l’objet requête (`req.auth`). + +##### Voir {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) pour les détails d’implémentation et les types étendus de l’objet +`req.auth` (`AuthInfo`). + +#### Signature d’appel {#call-signature} + +```ts +bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; +``` + +Crée un gestionnaire d’authentification Bearer (middleware Express) qui vérifie le jeton d’accès dans l’en-tête +`Authorization` de la requête en utilisant un mode de vérification prédéfini. + +En mode `'jwt'`, le gestionnaire créera une fonction de vérification JWT en utilisant le JWK Set +depuis l’URI JWKS du serveur d’autorisation. + +##### Paramètres {#parameters} + +###### mode {#mode} + +`"jwt"` + +Le mode de vérification pour le jeton d’accès. Actuellement, seul 'jwt' est pris en charge. + +**Voir** + +[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) pour les modes disponibles. + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` + +Configuration optionnelle pour le gestionnaire d’authentification Bearer, incluant les options de vérification JWT et +les options du JWK Set distant. + +**Voir** + + - VerifyJwtConfig pour les options de configuration disponibles pour la +vérification JWT. + - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) pour les options de configuration disponibles (à l’exception de +`verifyAccessToken` et `issuer`). + +##### Retourne {#returns} + +`RequestHandler` + +Une fonction middleware Express qui vérifie le jeton d’accès et ajoute le +résultat de la vérification à l’objet requête (`req.auth`). + +##### Voir {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) pour les détails d’implémentation et les types étendus de l’objet +`req.auth` (`AuthInfo`). + +##### Lève {#throws} + +si l’URI JWKS n’est pas fourni dans les métadonnées du serveur lors de +l’utilisation du mode `'jwt'`. + +*** + +### ~~delegatedRouter()~~ {#delegatedrouter} + +```ts +delegatedRouter(): Router; +``` + +Crée un routeur délégué pour servir le point de terminaison hérité OAuth 2.0 Authorization Server Metadata +(`/.well-known/oauth-authorization-server`) avec les métadonnées fournies à l’instance. + +#### Retourne {#returns} + +`Router` + +Un routeur qui sert le point de terminaison OAuth 2.0 Authorization Server Metadata avec les +métadonnées fournies à l’instance. + +#### Obsolète {#deprecated} + +Utilisez [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) à la place. + +#### Exemple {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth: MCPAuth; // Supposons que ceci est initialisé +app.use(mcpAuth.delegatedRouter()); +``` + +#### Lève {#throws} + +Si appelé en mode `resource server`. + +*** + +### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} + +```ts +protectedResourceMetadataRouter(): Router; +``` + +Crée un routeur qui sert le point de terminaison OAuth 2.0 Protected Resource Metadata +pour toutes les ressources configurées. + +Ce routeur crée automatiquement les bons points de terminaison `.well-known` pour chaque +identifiant de ressource fourni dans votre configuration. + +#### Retourne {#returns} + +`Router` + +Un routeur qui sert le point de terminaison OAuth 2.0 Protected Resource Metadata. + +#### Lève {#throws} + +Si appelé en mode `authorization server`. + +#### Exemple {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +// Supposons que mcpAuth est initialisé avec une ou plusieurs configurations `protectedResources` +const mcpAuth: MCPAuth; +const app = express(); + +// Cela servira les métadonnées à `/.well-known/oauth-protected-resource/...` +// selon vos identifiants de ressources. +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md new file mode 100644 index 0000000..4709191 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthAuthServerError +--- + +# Classe : MCPAuthAuthServerError + +Erreur levée lorsqu'il y a un problème avec le serveur d'autorisation distant. + +## Hérite de {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Constructeurs {#constructors} + +### Constructeur {#constructor} + +```ts +new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; +``` + +#### Paramètres {#parameters} + +##### code {#code} + +[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) + +##### cause ? {#cause} + +`unknown` + +#### Retourne {#returns} + +`MCPAuthAuthServerError` + +#### Redéfinit {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propriétés {#properties} + +### cause ? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: AuthServerErrorCode; +``` + +Le code d'erreur au format snake_case. + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthAuthServerError'; +``` + +#### Redéfinit {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack ? {#stack} + +```ts +optional stack: string; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +La propriété `Error.stackTraceLimit` spécifie le nombre de frames de pile +collectés par une trace de pile (qu'elle soit générée par `new Error().stack` ou +`Error.captureStackTrace(obj)`). + +La valeur par défaut est `10` mais peut être définie sur n'importe quel nombre JavaScript valide. Les modifications +affecteront toute trace de pile capturée _après_ que la valeur ait été modifiée. + +Si elle est définie sur une valeur non numérique, ou sur un nombre négatif, les traces de pile +ne captureront aucune frame. + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Méthodes {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Convertit l'erreur en un format JSON adapté à une réponse HTTP. + +#### Paramètres {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Indique s'il faut inclure la cause de l'erreur dans la réponse JSON. +La valeur par défaut est `false`. + +#### Retourne {#returns} + +`Record`\<`string`, `unknown`\> + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Crée une propriété `.stack` sur `targetObject`, qui, lorsqu'elle est accédée, retourne +une chaîne représentant l'emplacement dans le code où +`Error.captureStackTrace()` a été appelé. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Similaire à `new Error().stack` +``` + +La première ligne de la trace sera préfixée par +`${myObject.name}: ${myObject.message}`. + +L'argument optionnel `constructorOpt` accepte une fonction. Si fourni, toutes les frames +au-dessus de `constructorOpt`, y compris `constructorOpt`, seront omises de la +trace de pile générée. + +L'argument `constructorOpt` est utile pour masquer les détails d'implémentation +de la génération d'erreur à l'utilisateur. Par exemple : + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Créer une erreur sans trace de pile pour éviter de calculer la trace deux fois. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Capturer la trace de pile au-dessus de la fonction b + Error.captureStackTrace(error, b); // Ni la fonction c, ni b ne sont incluses dans la trace de pile + throw error; +} + +a(); +``` + +#### Paramètres {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt ? {#constructoropt} + +`Function` + +#### Retourne {#returns} + +`void` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Paramètres {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Retourne {#returns} + +`any` + +#### Voir {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md new file mode 100644 index 0000000..730893e --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthBearerAuthError +--- + +# Classe : MCPAuthBearerAuthError + +Erreur levée lorsqu'il y a un problème lors de l'authentification avec des jetons Bearer. + +## Hérite de {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Constructeurs {#constructors} + +### Constructeur {#constructor} + +```ts +new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; +``` + +#### Paramètres {#parameters} + +##### code {#code} + +[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) + +##### cause ? {#cause} + +[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) + +#### Retourne {#returns} + +`MCPAuthBearerAuthError` + +#### Redéfinit {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propriétés {#properties} + +### cause ? {#cause} + +```ts +readonly optional cause: MCPAuthBearerAuthErrorDetails; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: BearerAuthErrorCode; +``` + +Le code d'erreur au format snake_case. + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthBearerAuthError'; +``` + +#### Redéfinit {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack ? {#stack} + +```ts +optional stack: string; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +La propriété `Error.stackTraceLimit` spécifie le nombre de frames de pile +collectés par une trace de pile (qu'elle soit générée par `new Error().stack` ou +`Error.captureStackTrace(obj)`). + +La valeur par défaut est `10` mais peut être définie sur n'importe quel nombre JavaScript valide. Les modifications +affecteront toute trace de pile capturée _après_ que la valeur ait été modifiée. + +Si elle est définie sur une valeur non numérique, ou sur un nombre négatif, les traces de pile +ne captureront aucune frame. + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Méthodes {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Convertit l'erreur en un format JSON adapté à une réponse HTTP. + +#### Paramètres {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Indique s'il faut inclure la cause de l'erreur dans la réponse JSON. +La valeur par défaut est `false`. + +#### Retourne {#returns} + +`Record`\<`string`, `unknown`\> + +#### Redéfinit {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Crée une propriété `.stack` sur `targetObject`, qui, lorsqu'elle est accédée, retourne +une chaîne représentant l'emplacement dans le code où +`Error.captureStackTrace()` a été appelé. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Similaire à `new Error().stack` +``` + +La première ligne de la trace sera préfixée par +`${myObject.name}: ${myObject.message}`. + +L'argument optionnel `constructorOpt` accepte une fonction. Si fourni, toutes les frames +au-dessus de `constructorOpt`, y compris `constructorOpt`, seront omises de la +trace de pile générée. + +L'argument `constructorOpt` est utile pour masquer les détails d'implémentation +de la génération d'erreur à l'utilisateur. Par exemple : + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Créer une erreur sans trace de pile pour éviter de calculer la trace deux fois. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Capturer la trace de pile au-dessus de la fonction b + Error.captureStackTrace(error, b); // Ni la fonction c, ni b ne sont incluses dans la trace de pile + throw error; +} + +a(); +``` + +#### Paramètres {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt ? {#constructoropt} + +`Function` + +#### Retourne {#returns} + +`void` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Paramètres {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Retourne {#returns} + +`any` + +#### Voir {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md new file mode 100644 index 0000000..a71d86e --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md @@ -0,0 +1,252 @@ +--- +sidebar_label: MCPAuthConfigError +--- + +# Classe : MCPAuthConfigError + +Erreur levée lorsqu'il y a un problème de configuration avec mcp-auth. + +## Hérite de {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Constructeurs {#constructors} + +### Constructeur {#constructor} + +```ts +new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; +``` + +#### Paramètres {#parameters} + +##### code {#code} + +`string` + +Le code d'erreur au format snake_case. + +##### message {#message} + +`string` + +Une description lisible de l'erreur. + +#### Retourne {#returns} + +`MCPAuthConfigError` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propriétés {#properties} + +### cause ? {#cause} + +```ts +optional cause: unknown; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +Le code d'erreur au format snake_case. + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthConfigError'; +``` + +#### Redéfinit {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack ? {#stack} + +```ts +optional stack: string; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +La propriété `Error.stackTraceLimit` spécifie le nombre de frames de pile +collectés par une trace de pile (qu'elle soit générée par `new Error().stack` ou +`Error.captureStackTrace(obj)`). + +La valeur par défaut est `10` mais peut être définie sur n'importe quel nombre JavaScript valide. Les modifications +affecteront toute trace de pile capturée _après_ que la valeur ait été modifiée. + +Si elle est définie sur une valeur non numérique, ou sur un nombre négatif, les traces de pile +ne captureront aucune frame. + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Méthodes {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Convertit l'erreur en un format JSON adapté à une réponse HTTP. + +#### Paramètres {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Indique s'il faut inclure la cause de l'erreur dans la réponse JSON. +Par défaut à `false`. + +#### Retourne {#returns} + +`Record`\<`string`, `unknown`\> + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Crée une propriété `.stack` sur `targetObject`, qui, lorsqu'elle est accédée, retourne +une chaîne représentant l'emplacement dans le code où +`Error.captureStackTrace()` a été appelé. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Similaire à `new Error().stack` +``` + +La première ligne de la trace sera préfixée par +`${myObject.name}: ${myObject.message}`. + +L'argument optionnel `constructorOpt` accepte une fonction. Si fourni, toutes les frames +au-dessus de `constructorOpt`, y compris `constructorOpt`, seront omises de la +trace de pile générée. + +L'argument `constructorOpt` est utile pour masquer les détails d'implémentation +de la génération d'erreur à l'utilisateur. Par exemple : + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Créer une erreur sans trace de pile pour éviter de calculer la trace deux fois. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Capturer la trace de pile au-dessus de la fonction b + Error.captureStackTrace(error, b); // Ni la fonction c, ni b ne sont incluses dans la trace de pile + throw error; +} + +a(); +``` + +#### Paramètres {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt ? {#constructoropt} + +`Function` + +#### Retourne {#returns} + +`void` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Paramètres {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Retourne {#returns} + +`any` + +#### Voir {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md new file mode 100644 index 0000000..9886482 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md @@ -0,0 +1,269 @@ +--- +sidebar_label: MCPAuthError +--- + +# Classe : MCPAuthError + +Classe de base pour toutes les erreurs mcp-auth. + +Elle fournit un moyen standardisé de gérer les erreurs liées à l’authentification (Authentication) et à l’autorisation (Authorization) MCP. + +## Hérite de {#extends} + +- `Error` + +## Étendue par {#extended-by} + +- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) +- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) +- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) +- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) + +## Constructeurs {#constructors} + +### Constructeur {#constructor} + +```ts +new MCPAuthError(code: string, message: string): MCPAuthError; +``` + +#### Paramètres {#parameters} + +##### code {#code} + +`string` + +Le code d’erreur au format snake_case. + +##### message {#message} + +`string` + +Une description lisible de l’erreur. + +#### Retourne {#returns} + +`MCPAuthError` + +#### Redéfinit {#overrides} + +```ts +Error.constructor +``` + +## Propriétés {#properties} + +### cause ? {#cause} + +```ts +optional cause: unknown; +``` + +#### Hérité de {#inherited-from} + +```ts +Error.cause +``` + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +Le code d’erreur au format snake_case. + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Hérité de {#inherited-from} + +```ts +Error.message +``` + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthError'; +``` + +#### Redéfinit {#overrides} + +```ts +Error.name +``` + +*** + +### stack ? {#stack} + +```ts +optional stack: string; +``` + +#### Hérité de {#inherited-from} + +```ts +Error.stack +``` + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +La propriété `Error.stackTraceLimit` spécifie le nombre de frames de pile +collectés par une trace de pile (qu’elle soit générée par `new Error().stack` ou +`Error.captureStackTrace(obj)`). + +La valeur par défaut est `10` mais peut être définie sur n’importe quel nombre JavaScript valide. Les modifications +affecteront toute trace de pile capturée _après_ le changement de valeur. + +Si elle est définie sur une valeur non numérique, ou sur un nombre négatif, les traces de pile +ne captureront aucune frame. + +#### Hérité de {#inherited-from} + +```ts +Error.stackTraceLimit +``` + +## Méthodes {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Convertit l’erreur en un format JSON adapté à une réponse HTTP. + +#### Paramètres {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Indique s’il faut inclure la cause de l’erreur dans la réponse JSON. +Par défaut à `false`. + +#### Retourne {#returns} + +`Record`\<`string`, `unknown`\> + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Crée une propriété `.stack` sur `targetObject`, qui, lorsqu’elle est accédée, retourne +une chaîne représentant l’emplacement dans le code où +`Error.captureStackTrace()` a été appelé. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Similaire à `new Error().stack` +``` + +La première ligne de la trace sera préfixée par +`${myObject.name}: ${myObject.message}`. + +L’argument optionnel `constructorOpt` accepte une fonction. Si fourni, toutes les frames +au-dessus de `constructorOpt`, y compris `constructorOpt`, seront omises de la +trace de pile générée. + +L’argument `constructorOpt` est utile pour masquer les détails d’implémentation +de la génération d’erreur à l’utilisateur. Par exemple : + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Créer une erreur sans trace de pile pour éviter de calculer la trace deux fois. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Capturer la trace de pile au-dessus de la fonction b + Error.captureStackTrace(error, b); // Ni la fonction c, ni b ne sont incluses dans la trace de pile + throw error; +} + +a(); +``` + +#### Paramètres {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt ? {#constructoropt} + +`Function` + +#### Retourne {#returns} + +`void` + +#### Hérité de {#inherited-from} + +```ts +Error.captureStackTrace +``` + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Paramètres {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Retourne {#returns} + +`any` + +#### Voir {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Hérité de {#inherited-from} + +```ts +Error.prepareStackTrace +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md new file mode 100644 index 0000000..ecd5125 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthTokenVerificationError +--- + +# Classe : MCPAuthTokenVerificationError + +Erreur levée lorsqu'il y a un problème lors de la vérification des jetons. + +## Hérite de {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Constructeurs {#constructors} + +### Constructeur {#constructor} + +```ts +new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; +``` + +#### Paramètres {#parameters} + +##### code {#code} + +[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) + +##### cause ? {#cause} + +`unknown` + +#### Retourne {#returns} + +`MCPAuthTokenVerificationError` + +#### Redéfinit {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propriétés {#properties} + +### cause ? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: MCPAuthTokenVerificationErrorCode; +``` + +Le code d'erreur au format snake_case. + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthTokenVerificationError'; +``` + +#### Redéfinit {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack ? {#stack} + +```ts +optional stack: string; +``` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +La propriété `Error.stackTraceLimit` spécifie le nombre de frames de pile +collectés par une trace de pile (qu'elle soit générée par `new Error().stack` ou +`Error.captureStackTrace(obj)`). + +La valeur par défaut est `10` mais peut être définie sur n'importe quel nombre JavaScript valide. Les modifications +affecteront toute trace de pile capturée _après_ que la valeur ait été modifiée. + +Si elle est définie sur une valeur non numérique, ou sur un nombre négatif, les traces de pile +ne captureront aucune frame. + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Méthodes {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Convertit l'erreur en un format JSON adapté à une réponse HTTP. + +#### Paramètres {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Indique s'il faut inclure la cause de l'erreur dans la réponse JSON. +La valeur par défaut est `false`. + +#### Retourne {#returns} + +`Record`\<`string`, `unknown`\> + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Crée une propriété `.stack` sur `targetObject`, qui, lorsqu'elle est accédée, retourne +une chaîne représentant l'emplacement dans le code où +`Error.captureStackTrace()` a été appelé. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Similaire à `new Error().stack` +``` + +La première ligne de la trace sera préfixée par +`${myObject.name}: ${myObject.message}`. + +L'argument optionnel `constructorOpt` accepte une fonction. Si fourni, toutes les frames +au-dessus de `constructorOpt`, y compris `constructorOpt`, seront omises de la +trace de pile générée. + +L'argument `constructorOpt` est utile pour masquer les détails d'implémentation +de la génération d'erreur à l'utilisateur. Par exemple : + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Créer une erreur sans trace de pile pour éviter de calculer la trace deux fois. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Capturer la trace de pile au-dessus de la fonction b + Error.captureStackTrace(error, b); // Ni la fonction c, ni b ne sont incluses dans la trace de pile + throw error; +} + +a(); +``` + +#### Paramètres {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt ? {#constructoropt} + +`Function` + +#### Retourne {#returns} + +`void` + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Paramètres {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Retourne {#returns} + +`any` + +#### Voir {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Hérité de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md new file mode 100644 index 0000000..c5afbf4 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md @@ -0,0 +1,43 @@ +--- +sidebar_label: createVerifyJwt +--- + +# Fonction : createVerifyJwt() + +```ts +function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; +``` + +Crée une fonction pour vérifier les jetons d’accès JWT (Access token) en utilisant la fonction de récupération de clé fournie et les options. + +## Paramètres {#parameters} + +### getKey {#getkey} + +`JWTVerifyGetKey` + +La fonction permettant de récupérer la clé utilisée pour vérifier le JWT. + +**Voir** + +JWTVerifyGetKey pour la définition du type de la fonction de récupération de clé. + +### options? {#options} + +`JWTVerifyOptions` + +Options de vérification JWT facultatives. + +**Voir** + +JWTVerifyOptions pour la définition du type des options. + +## Retourne {#returns} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +Une fonction qui vérifie les jetons d’accès JWT (Access token) et retourne un objet AuthInfo si le jeton est valide. Elle exige que le JWT contienne les champs `iss`, `client_id` et `sub` dans sa charge utile, et peut éventuellement contenir les champs `scope` ou `scopes`. La fonction utilise la bibliothèque `jose` en interne pour effectuer la vérification du JWT. + +## Voir {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) pour la définition du type de la fonction retournée. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md new file mode 100644 index 0000000..138e73c --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md @@ -0,0 +1,60 @@ +--- +sidebar_label: fetchServerConfig +--- + +# Fonction : fetchServerConfig() + +```ts +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +``` + +Récupère la configuration du serveur selon l’émetteur (Issuer) et le type de serveur d’autorisation (Authorization). + +Cette fonction détermine automatiquement l’URL well-known en fonction du type de serveur, car les serveurs OAuth et OpenID Connect ont des conventions différentes pour leurs points de terminaison de métadonnées. + +## Paramètres {#parameters} + +### issuer {#issuer} + +`string` + +L’URL de l’émetteur (Issuer) du serveur d’autorisation (Authorization). + +### config {#config} + +`ServerMetadataConfig` + +L’objet de configuration contenant le type de serveur et une fonction de transpilation optionnelle. + +## Retourne {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +Une promesse qui se résout avec la configuration du serveur. + +## Voir {#see} + + - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) pour l’implémentation sous-jacente. + - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) pour la spécification OAuth 2.0 Authorization Server Metadata. + - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) pour la spécification OpenID Connect Discovery. + +## Exemple {#example} + +```ts +import { fetchServerConfig } from 'mcp-auth'; +// Récupération de la configuration du serveur OAuth +// Cela va récupérer les métadonnées depuis `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` +const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); + +// Récupération de la configuration du serveur OpenID Connect +// Cela va récupérer les métadonnées depuis `https://auth.logto.io/oidc/.well-known/openid-configuration` +const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); +``` + +## Exceptions {#throws} + +si l’opération de récupération échoue. + +## Exceptions {#throws} + +si les métadonnées du serveur sont invalides ou ne correspondent pas à la spécification MCP. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md new file mode 100644 index 0000000..248e10a --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md @@ -0,0 +1,41 @@ +--- +sidebar_label: fetchServerConfigByWellKnownUrl +--- + +# Fonction : fetchServerConfigByWellKnownUrl() + +```ts +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +``` + +Récupère la configuration du serveur à partir de l’URL bien connue fournie et la valide par rapport à la spécification MCP. + +Si les métadonnées du serveur ne sont pas conformes au schéma attendu, mais que vous êtes certain qu’elles sont compatibles, vous pouvez définir une fonction `transpileData` pour transformer les métadonnées dans le format attendu. + +## Paramètres {#parameters} + +### wellKnownUrl {#wellknownurl} + +L’URL bien connue à partir de laquelle récupérer la configuration du serveur. Cela peut être une chaîne de caractères ou un objet URL. + +`string` | `URL` + +### config {#config} + +`ServerMetadataConfig` + +L’objet de configuration contenant le type de serveur et éventuellement la fonction de transpilation. + +## Retourne {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +Une promesse qui se résout avec la configuration du serveur. + +## Déclenche une exception {#throws} + +si l’opération de récupération échoue. + +## Déclenche une exception {#throws} + +si les métadonnées du serveur sont invalides ou ne correspondent pas à la spécification MCP. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md new file mode 100644 index 0000000..436c754 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md @@ -0,0 +1,41 @@ +--- +sidebar_label: handleBearerAuth +--- + +# Fonction : handleBearerAuth() + +```ts +function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; +``` + +Crée une fonction middleware pour gérer l’authentification Bearer dans une application Express. + +Ce middleware extrait le jeton Bearer de l’en-tête `Authorization`, le vérifie à l’aide de la fonction +`verifyAccessToken` fournie, et contrôle l’Émetteur (Issuer), l’Audience (Audience) et les Portées (Scopes) requises. + +- Si le jeton est valide, il ajoute les informations d’authentification à la propriété `request.auth` ; +sinon, il répond avec un message d’erreur approprié. +- Si la vérification du Jeton d’accès (Access token) échoue, il répond avec une erreur 401 Non autorisé. +- Si le jeton ne possède pas les Portées (Scopes) requises, il répond avec une erreur 403 Interdit. +- Si des erreurs inattendues surviennent lors du processus d’authentification, le middleware les relancera. + +**Remarque :** L’objet `request.auth` contiendra des champs étendus par rapport à l’interface standard +AuthInfo définie dans le module `@modelcontextprotocol/sdk`. Voir l’interface étendue dans ce fichier pour plus de détails. + +## Paramètres {#parameters} + +### param0 {#param0} + +[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) + +Configuration pour le gestionnaire d’authentification Bearer. + +## Retourne {#returns} + +`RequestHandler` + +Une fonction middleware pour Express qui gère l’authentification Bearer. + +## Voir aussi {#see} + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) pour les options de configuration. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md new file mode 100644 index 0000000..e6dbd10 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md @@ -0,0 +1,50 @@ +--- +sidebar_label: AuthServerConfig +--- + +# Alias de type : AuthServerConfig + +```ts +type AuthServerConfig = { + metadata: CamelCaseAuthorizationServerMetadata; + type: AuthServerType; +}; +``` + +Configuration pour le serveur d'autorisation distant intégré avec le serveur MCP. + +## Propriétés {#properties} + +### metadata {#metadata} + +```ts +metadata: CamelCaseAuthorizationServerMetadata; +``` + +Les métadonnées du serveur d'autorisation (Authorization Server), qui doivent être conformes à la spécification MCP +(basée sur les métadonnées du serveur d'autorisation OAuth 2.0). + +Ces métadonnées sont généralement récupérées à partir du point de terminaison well-known du serveur (OAuth 2.0 +Authorization Server Metadata ou OpenID Connect Discovery) ; elles peuvent également être fournies +directement dans la configuration si le serveur ne prend pas en charge de tels points de terminaison. + +**Remarque :** Les métadonnées doivent être au format camelCase comme préféré par la bibliothèque mcp-auth. + +#### Voir {#see} + + - [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) + - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +*** + +### type {#type} + +```ts +type: AuthServerType; +``` + +Le type du serveur d'autorisation (Authorization Server). + +#### Voir {#see} + +[AuthServerType](/references/js/type-aliases/AuthServerType.md) pour les valeurs possibles. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md new file mode 100644 index 0000000..7e48430 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md @@ -0,0 +1,45 @@ +--- +sidebar_label: AuthServerConfigError +--- + +# Alias de type : AuthServerConfigError + +```ts +type AuthServerConfigError = { + cause?: Error; + code: AuthServerConfigErrorCode; + description: string; +}; +``` + +Représente une erreur qui se produit lors de la validation des métadonnées du serveur d’autorisation (authorization server). + +## Propriétés {#properties} + +### cause ? {#cause} + +```ts +optional cause: Error; +``` + +Une cause optionnelle de l’erreur, généralement une instance de `Error` qui fournit plus de contexte. + +*** + +### code {#code} + +```ts +code: AuthServerConfigErrorCode; +``` + +Le code représentant l’erreur de validation spécifique. + +*** + +### description {#description} + +```ts +description: string; +``` + +Une description lisible par l’humain de l’erreur. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md new file mode 100644 index 0000000..06ada65 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: AuthServerConfigErrorCode +--- + +# Alias de type : AuthServerConfigErrorCode + +```ts +type AuthServerConfigErrorCode = + | "invalid_server_metadata" + | "code_response_type_not_supported" + | "authorization_code_grant_not_supported" + | "pkce_not_supported" + | "s256_code_challenge_method_not_supported"; +``` + +Les codes des erreurs pouvant survenir lors de la validation des métadonnées du serveur d’autorisation. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md new file mode 100644 index 0000000..df2408e --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md @@ -0,0 +1,34 @@ +--- +sidebar_label: AuthServerConfigWarning +--- + +# Alias de type : AuthServerConfigWarning + +```ts +type AuthServerConfigWarning = { + code: AuthServerConfigWarningCode; + description: string; +}; +``` + +Représente un avertissement qui survient lors de la validation des métadonnées du serveur d’autorisation. + +## Propriétés {#properties} + +### code {#code} + +```ts +code: AuthServerConfigWarningCode; +``` + +Le code représentant l’avertissement de validation spécifique. + +*** + +### description {#description} + +```ts +description: string; +``` + +Une description lisible par l’humain de l’avertissement. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md new file mode 100644 index 0000000..375439b --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerConfigWarningCode +--- + +# Alias de type : AuthServerConfigWarningCode + +```ts +type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; +``` + +Les codes des avertissements pouvant survenir lors de la validation des métadonnées du serveur d’autorisation. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md new file mode 100644 index 0000000..64c30a9 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md @@ -0,0 +1,12 @@ +--- +sidebar_label: AuthServerErrorCode +--- + +# Alias de type : AuthServerErrorCode + +```ts +type AuthServerErrorCode = + | "invalid_server_metadata" + | "invalid_server_config" + | "missing_jwks_uri"; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md new file mode 100644 index 0000000..91659c0 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md @@ -0,0 +1,31 @@ +--- +sidebar_label: AuthServerModeConfig +--- + +# Alias de type : ~~AuthServerModeConfig~~ + +```ts +type AuthServerModeConfig = { + server: AuthServerConfig; +}; +``` + +Configuration pour le mode serveur d'autorisation hérité, MCP. + +## Obsolète {#deprecated} + +Utilisez la configuration `ResourceServerModeConfig` à la place. + +## Propriétés {#properties} + +### ~~server~~ {#server} + +```ts +server: AuthServerConfig; +``` + +La configuration du serveur d'autorisation unique. + +#### Obsolète {#deprecated} + +Utilisez la configuration `protectedResources` à la place. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md new file mode 100644 index 0000000..f1bcc6c --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md @@ -0,0 +1,17 @@ +--- +sidebar_label: AuthServerSuccessCode +--- + +# Alias de type : AuthServerSuccessCode + +```ts +type AuthServerSuccessCode = + | "server_metadata_valid" + | "dynamic_registration_supported" + | "pkce_supported" + | "s256_code_challenge_method_supported" + | "authorization_code_grant_supported" + | "code_response_type_supported"; +``` + +Les codes pour la validation réussie des métadonnées du serveur d’autorisation. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md new file mode 100644 index 0000000..794cfae --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerType +--- + +# Alias de type : AuthServerType + +```ts +type AuthServerType = "oauth" | "oidc"; +``` + +Le type du serveur d’autorisation (authorization server). Cette information doit être fournie par la configuration du serveur et indique si le serveur est un serveur d’autorisation OAuth 2.0 ou OpenID Connect (OIDC). diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md new file mode 100644 index 0000000..9073e68 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md @@ -0,0 +1,238 @@ +--- +sidebar_label: AuthorizationServerMetadata +--- + +# Alias de type : AuthorizationServerMetadata + +```ts +type AuthorizationServerMetadata = { + authorization_endpoint: string; + code_challenge_methods_supported?: string[]; + grant_types_supported?: string[]; + introspection_endpoint?: string; + introspection_endpoint_auth_methods_supported?: string[]; + introspection_endpoint_auth_signing_alg_values_supported?: string[]; + issuer: string; + jwks_uri?: string; + op_policy_uri?: string; + op_tos_uri?: string; + registration_endpoint?: string; + response_modes_supported?: string[]; + response_types_supported: string[]; + revocation_endpoint?: string; + revocation_endpoint_auth_methods_supported?: string[]; + revocation_endpoint_auth_signing_alg_values_supported?: string[]; + scopes_supported?: string[]; + service_documentation?: string; + token_endpoint: string; + token_endpoint_auth_methods_supported?: string[]; + token_endpoint_auth_signing_alg_values_supported?: string[]; + ui_locales_supported?: string[]; + userinfo_endpoint?: string; +}; +``` + +Schéma pour les métadonnées du serveur d’autorisation OAuth 2.0 tel que défini dans la RFC 8414. + +## Déclaration du type {#type-declaration} + +### authorization\_endpoint {#authorization-endpoint} + +```ts +authorization_endpoint: string; +``` + +URL du point de terminaison d’autorisation du serveur d’autorisation [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. +Ceci est OBLIGATOIRE sauf si aucun type d’octroi n’est pris en charge utilisant le point de terminaison d’autorisation. + +#### Voir {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.1 + +### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} + +```ts +optional code_challenge_methods_supported: string[]; +``` + +Tableau JSON contenant une liste des méthodes de challenge de code Proof Key for Code Exchange (PKCE) +[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] prises en charge par ce serveur d’autorisation. + +### grant\_types\_supported? {#grant-types-supported} + +```ts +optional grant_types_supported: string[]; +``` + +Tableau JSON contenant une liste des valeurs de type d’octroi OAuth 2.0 que ce serveur d’autorisation +prend en charge. Les valeurs du tableau utilisées sont les mêmes que celles utilisées avec le paramètre `grant_types` +défini par le "Protocole d’enregistrement dynamique du client OAuth 2.0" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. +Si omis, la valeur par défaut est `["authorization_code", "implicit"]`. + +### introspection\_endpoint? {#introspection-endpoint} + +```ts +optional introspection_endpoint: string; +``` + +URL du point de terminaison d’introspection OAuth 2.0 du serveur d’autorisation +[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. + +### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} + +```ts +optional introspection_endpoint_auth_methods_supported: string[]; +``` + +### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} + +```ts +optional introspection_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +Identifiant de l’émetteur (Issuer) du serveur d’autorisation, qui est une URL utilisant le schéma `https` et +ne comportant pas de composants de requête ou de fragment. + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +URL du document JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] +du serveur d’autorisation. Le document référencé contient la/les clé(s) de signature que le client utilise pour valider +les signatures du serveur d’autorisation. Cette URL DOIT utiliser le schéma `https`. + +### op\_policy\_uri? {#op-policy-uri} + +```ts +optional op_policy_uri: string; +``` + +### op\_tos\_uri? {#op-tos-uri} + +```ts +optional op_tos_uri: string; +``` + +### registration\_endpoint? {#registration-endpoint} + +```ts +optional registration_endpoint: string; +``` + +URL du point de terminaison d’enregistrement dynamique du client OAuth 2.0 du serveur d’autorisation +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. + +### response\_modes\_supported? {#response-modes-supported} + +```ts +optional response_modes_supported: string[]; +``` + +Tableau JSON contenant une liste des valeurs `response_mode` OAuth 2.0 que ce +serveur d’autorisation prend en charge, comme spécifié dans "OAuth 2.0 Multiple Response +Type Encoding Practices" +[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]. + +Si omis, la valeur par défaut est `["query", "fragment"]`. La valeur de mode de réponse `"form_post"` est +également définie dans "OAuth 2.0 Form Post Response Mode" +[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]. + +### response\_types\_supported {#response-types-supported} + +```ts +response_types_supported: string[]; +``` + +Tableau JSON contenant une liste des valeurs `response_type` OAuth 2.0 que ce serveur d’autorisation +prend en charge. Les valeurs du tableau utilisées sont les mêmes que celles utilisées avec le paramètre `response_types` +défini par le "Protocole d’enregistrement dynamique du client OAuth 2.0" +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. + +### revocation\_endpoint? {#revocation-endpoint} + +```ts +optional revocation_endpoint: string; +``` + +URL du point de terminaison de révocation OAuth 2.0 du serveur d’autorisation +[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. + +### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} + +```ts +optional revocation_endpoint_auth_methods_supported: string[]; +``` + +### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} + +```ts +optional revocation_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +Tableau JSON contenant une liste des valeurs `scope` OAuth 2.0 que ce serveur d’autorisation +prend en charge. +[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] + +### service\_documentation? {#service-documentation} + +```ts +optional service_documentation: string; +``` + +### token\_endpoint {#token-endpoint} + +```ts +token_endpoint: string; +``` + +URL du point de terminaison de jeton du serveur d’autorisation [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. +Ceci est OBLIGATOIRE sauf si seul le type d’octroi implicite est pris en charge. + +#### Voir {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.2 + +### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} + +```ts +optional token_endpoint_auth_methods_supported: string[]; +``` + +### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} + +```ts +optional token_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### ui\_locales\_supported? {#ui-locales-supported} + +```ts +optional ui_locales_supported: string[]; +``` + +### userinfo\_endpoint? {#userinfo-endpoint} + +```ts +optional userinfo_endpoint: string; +``` + +URL du [point de terminaison userinfo](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) OpenID Connect. +Ce point de terminaison est utilisé pour récupérer les informations sur l’utilisateur authentifié. + +## Voir {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md new file mode 100644 index 0000000..67c16ca --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md @@ -0,0 +1,109 @@ +--- +sidebar_label: BearerAuthConfig +--- + +# Alias de type : BearerAuthConfig + +```ts +type BearerAuthConfig = { + audience?: string; + issuer: | string + | ValidateIssuerFunction; + requiredScopes?: string[]; + resource?: string; + showErrorDetails?: boolean; + verifyAccessToken: VerifyAccessTokenFunction; +}; +``` + +## Propriétés {#properties} + +### audience ? {#audience} + +```ts +optional audience: string; +``` + +L’audience attendue du jeton d’accès (Jeton d’accès (Access token)) (`aud` revendication (claim)). Il s’agit généralement du serveur de ressources (API) pour lequel le jeton est destiné. Si non fourni, la vérification de l’audience sera ignorée. + +**Remarque :** Si votre serveur d’autorisation ne prend pas en charge les indicateurs de ressource (Indicateurs de ressource (Resource indicators)) (RFC 8707), vous pouvez omettre ce champ car l’audience peut ne pas être pertinente. + +#### Voir {#see} + +https://datatracker.ietf.org/doc/html/rfc8707 + +*** + +### issuer {#issuer} + +```ts +issuer: + | string + | ValidateIssuerFunction; +``` + +Une chaîne représentant un émetteur (Émetteur (Issuer)) valide, ou une fonction pour valider l’émetteur du jeton d’accès (Jeton d’accès (Access token)). + +Si une chaîne est fournie, elle sera utilisée comme valeur d’émetteur attendue pour une comparaison directe. + +Si une fonction est fournie, elle doit valider l’émetteur selon les règles de +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md). + +#### Voir {#see} + +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) pour plus de détails sur la fonction de validation. + +*** + +### requiredScopes ? {#requiredscopes} + +```ts +optional requiredScopes: string[]; +``` + +Un tableau des portées (Portées (Scopes)) requises que le jeton d’accès (Jeton d’accès (Access token)) doit posséder. Si le jeton ne contient pas toutes ces portées, une erreur sera levée. + +**Remarque :** Le gestionnaire vérifiera la revendication (claim) `scope` dans le jeton, qui peut être une chaîne séparée par des espaces ou un tableau de chaînes, selon l’implémentation du serveur d’autorisation. Si la revendication `scope` n’est pas présente, le gestionnaire vérifiera la revendication `scopes` si elle est disponible. + +*** + +### resource ? {#resource} + +```ts +optional resource: string; +``` + +L’identifiant de la ressource protégée. Lorsqu’il est fourni, le gestionnaire utilisera les serveurs d’autorisation configurés pour cette ressource afin de valider le jeton reçu. +Ce champ est requis lors de l’utilisation du gestionnaire avec une configuration `protectedResources`. + +*** + +### showErrorDetails ? {#showerrordetails} + +```ts +optional showErrorDetails: boolean; +``` + +Indique s’il faut afficher des informations d’erreur détaillées dans la réponse. Ceci est utile pour le débogage pendant le développement, mais doit être désactivé en production pour éviter de divulguer des informations sensibles. + +#### Valeur par défaut {#default} + +```ts +false +``` + +*** + +### verifyAccessToken {#verifyaccesstoken} + +```ts +verifyAccessToken: VerifyAccessTokenFunction; +``` + +Type de fonction pour vérifier un jeton d’accès (Jeton d’accès (Access token)). + +Cette fonction doit lever une [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) si le jeton est invalide, ou retourner un objet AuthInfo si le jeton est valide. + +#### Voir {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) pour plus de détails. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md new file mode 100644 index 0000000..5a5207c --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: BearerAuthErrorCode +--- + +# Alias de type : BearerAuthErrorCode + +```ts +type BearerAuthErrorCode = + | "missing_auth_header" + | "invalid_auth_header_format" + | "missing_bearer_token" + | "invalid_issuer" + | "invalid_audience" + | "missing_required_scopes" + | "invalid_token"; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md new file mode 100644 index 0000000..7f7bd49 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md @@ -0,0 +1,179 @@ +--- +sidebar_label: CamelCaseAuthorizationServerMetadata +--- + +# Alias de type : CamelCaseAuthorizationServerMetadata + +```ts +type CamelCaseAuthorizationServerMetadata = { + authorizationEndpoint: string; + codeChallengeMethodsSupported?: string[]; + grantTypesSupported?: string[]; + introspectionEndpoint?: string; + introspectionEndpointAuthMethodsSupported?: string[]; + introspectionEndpointAuthSigningAlgValuesSupported?: string[]; + issuer: string; + jwksUri?: string; + opPolicyUri?: string; + opTosUri?: string; + registrationEndpoint?: string; + responseModesSupported?: string[]; + responseTypesSupported: string[]; + revocationEndpoint?: string; + revocationEndpointAuthMethodsSupported?: string[]; + revocationEndpointAuthSigningAlgValuesSupported?: string[]; + scopesSupported?: string[]; + serviceDocumentation?: string; + tokenEndpoint: string; + tokenEndpointAuthMethodsSupported?: string[]; + tokenEndpointAuthSigningAlgValuesSupported?: string[]; + uiLocalesSupported?: string[]; + userinfoEndpoint?: string; +}; +``` + +La version camelCase du type Metadata du serveur d’Autorisation (Authorization Server Metadata) OAuth 2.0. + +## Déclaration du type {#type-declaration} + +### authorizationEndpoint {#authorizationendpoint} + +```ts +authorizationEndpoint: string; +``` + +### codeChallengeMethodsSupported? {#codechallengemethodssupported} + +```ts +optional codeChallengeMethodsSupported: string[]; +``` + +### grantTypesSupported? {#granttypessupported} + +```ts +optional grantTypesSupported: string[]; +``` + +### introspectionEndpoint? {#introspectionendpoint} + +```ts +optional introspectionEndpoint: string; +``` + +### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} + +```ts +optional introspectionEndpointAuthMethodsSupported: string[]; +``` + +### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} + +```ts +optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### opPolicyUri? {#oppolicyuri} + +```ts +optional opPolicyUri: string; +``` + +### opTosUri? {#optosuri} + +```ts +optional opTosUri: string; +``` + +### registrationEndpoint? {#registrationendpoint} + +```ts +optional registrationEndpoint: string; +``` + +### responseModesSupported? {#responsemodessupported} + +```ts +optional responseModesSupported: string[]; +``` + +### responseTypesSupported {#responsetypessupported} + +```ts +responseTypesSupported: string[]; +``` + +### revocationEndpoint? {#revocationendpoint} + +```ts +optional revocationEndpoint: string; +``` + +### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} + +```ts +optional revocationEndpointAuthMethodsSupported: string[]; +``` + +### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} + +```ts +optional revocationEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### serviceDocumentation? {#servicedocumentation} + +```ts +optional serviceDocumentation: string; +``` + +### tokenEndpoint {#tokenendpoint} + +```ts +tokenEndpoint: string; +``` + +### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} + +```ts +optional tokenEndpointAuthMethodsSupported: string[]; +``` + +### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} + +```ts +optional tokenEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### uiLocalesSupported? {#uilocalessupported} + +```ts +optional uiLocalesSupported: string[]; +``` + +### userinfoEndpoint? {#userinfoendpoint} + +```ts +optional userinfoEndpoint: string; +``` + +## Voir aussi {#see} + +[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) pour le type original et les informations sur les champs. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md new file mode 100644 index 0000000..7c15ece --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md @@ -0,0 +1,123 @@ +--- +sidebar_label: CamelCaseProtectedResourceMetadata +--- + +# Alias de type : CamelCaseProtectedResourceMetadata + +```ts +type CamelCaseProtectedResourceMetadata = { + authorizationDetailsTypesSupported?: string[]; + authorizationServers?: string[]; + bearerMethodsSupported?: string[]; + dpopBoundAccessTokensRequired?: boolean; + dpopSigningAlgValuesSupported?: string[]; + jwksUri?: string; + resource: string; + resourceDocumentation?: string; + resourceName?: string; + resourcePolicyUri?: string; + resourceSigningAlgValuesSupported?: string[]; + resourceTosUri?: string; + scopesSupported?: string[]; + signedMetadata?: string; + tlsClientCertificateBoundAccessTokens?: boolean; +}; +``` + +La version camelCase du type OAuth 2.0 Protected Resource Metadata. + +## Déclaration du type {#type-declaration} + +### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} + +```ts +optional authorizationDetailsTypesSupported: string[]; +``` + +### authorizationServers? {#authorizationservers} + +```ts +optional authorizationServers: string[]; +``` + +### bearerMethodsSupported? {#bearermethodssupported} + +```ts +optional bearerMethodsSupported: string[]; +``` + +### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} + +```ts +optional dpopBoundAccessTokensRequired: boolean; +``` + +### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} + +```ts +optional dpopSigningAlgValuesSupported: string[]; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### resource {#resource} + +```ts +resource: string; +``` + +### resourceDocumentation? {#resourcedocumentation} + +```ts +optional resourceDocumentation: string; +``` + +### resourceName? {#resourcename} + +```ts +optional resourceName: string; +``` + +### resourcePolicyUri? {#resourcepolicyuri} + +```ts +optional resourcePolicyUri: string; +``` + +### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} + +```ts +optional resourceSigningAlgValuesSupported: string[]; +``` + +### resourceTosUri? {#resourcetosuri} + +```ts +optional resourceTosUri: string; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### signedMetadata? {#signedmetadata} + +```ts +optional signedMetadata: string; +``` + +### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} + +```ts +optional tlsClientCertificateBoundAccessTokens: boolean; +``` + +## Voir aussi {#see} + +[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) pour le type original et les informations sur les champs. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md new file mode 100644 index 0000000..80c12da --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md @@ -0,0 +1,55 @@ +--- +sidebar_label: MCPAuthBearerAuthErrorDetails +--- + +# Alias de type : MCPAuthBearerAuthErrorDetails + +```ts +type MCPAuthBearerAuthErrorDetails = { + actual?: unknown; + cause?: unknown; + expected?: unknown; + missingScopes?: string[]; + uri?: URL; +}; +``` + +## Propriétés {#properties} + +### actual ? {#actual} + +```ts +optional actual: unknown; +``` + +*** + +### cause ? {#cause} + +```ts +optional cause: unknown; +``` + +*** + +### expected ? {#expected} + +```ts +optional expected: unknown; +``` + +*** + +### missingScopes ? {#missingscopes} + +```ts +optional missingScopes: string[]; +``` + +*** + +### uri ? {#uri} + +```ts +optional uri: URL; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md new file mode 100644 index 0000000..dc62bfb --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md @@ -0,0 +1,13 @@ +--- +sidebar_label: MCPAuthConfig +--- + +# Alias de type : MCPAuthConfig + +```ts +type MCPAuthConfig = + | AuthServerModeConfig + | ResourceServerModeConfig; +``` + +Configuration pour la classe [MCPAuth](/references/js/classes/MCPAuth.md), prenant en charge soit un unique `authorization server` hérité, soit la configuration du `resource server`. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md new file mode 100644 index 0000000..083a31d --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md @@ -0,0 +1,9 @@ +--- +sidebar_label: MCPAuthTokenVerificationErrorCode +--- + +# Alias de type : MCPAuthTokenVerificationErrorCode + +```ts +type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md new file mode 100644 index 0000000..cf5bc88 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md @@ -0,0 +1,157 @@ +--- +sidebar_label: ProtectedResourceMetadata +--- + +# Alias de type : ProtectedResourceMetadata + +```ts +type ProtectedResourceMetadata = { + authorization_details_types_supported?: string[]; + authorization_servers?: string[]; + bearer_methods_supported?: string[]; + dpop_bound_access_tokens_required?: boolean; + dpop_signing_alg_values_supported?: string[]; + jwks_uri?: string; + resource: string; + resource_documentation?: string; + resource_name?: string; + resource_policy_uri?: string; + resource_signing_alg_values_supported?: string[]; + resource_tos_uri?: string; + scopes_supported?: string[]; + signed_metadata?: string; + tls_client_certificate_bound_access_tokens?: boolean; +}; +``` + +Schéma pour les métadonnées de ressource protégée OAuth 2.0. + +## Déclaration du type {#type-declaration} + +### authorization\_details\_types\_supported? {#authorization-details-types-supported} + +```ts +optional authorization_details_types_supported: string[]; +``` + +Types de détails d'autorisation pris en charge lors de l'utilisation du paramètre de requête authorization_details. + +### authorization\_servers? {#authorization-servers} + +```ts +optional authorization_servers: string[]; +``` + +Liste des identifiants d'émetteur du serveur d'autorisation OAuth pouvant être utilisés avec cette ressource protégée. + +### bearer\_methods\_supported? {#bearer-methods-supported} + +```ts +optional bearer_methods_supported: string[]; +``` + +Méthodes prises en charge pour l'envoi de jetons porteurs OAuth 2.0. Valeurs : ["header", "body", "query"]. + +### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} + +```ts +optional dpop_bound_access_tokens_required: boolean; +``` + +Indique si la ressource protégée exige toujours des jetons d’accès liés à DPoP. + +### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} + +```ts +optional dpop_signing_alg_values_supported: string[]; +``` + +Algorithmes JWS pris en charge pour la validation des preuves JWT DPoP. + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +URL du document JSON Web Key (JWK) Set de la ressource protégée. Ce document contient les clés publiques +qui peuvent être utilisées pour vérifier les signatures numériques des réponses ou des données renvoyées par cette ressource protégée. +Ceci diffère du jwks_uri du serveur d'autorisation qui est utilisé pour la validation des jetons. Lorsque la ressource protégée +signe ses réponses, les clients peuvent récupérer ces clés publiques pour vérifier l'authenticité et l'intégrité +des données reçues. + +### resource {#resource} + +```ts +resource: string; +``` + +Identifiant de la ressource protégée. + +### resource\_documentation? {#resource-documentation} + +```ts +optional resource_documentation: string; +``` + +URL contenant la documentation développeur pour l'utilisation de la ressource protégée. + +### resource\_name? {#resource-name} + +```ts +optional resource_name: string; +``` + +Nom lisible par l'utilisateur de la ressource protégée pour l'affichage aux utilisateurs finaux. + +### resource\_policy\_uri? {#resource-policy-uri} + +```ts +optional resource_policy_uri: string; +``` + +URL contenant des informations sur les exigences d'utilisation des données de la ressource protégée. + +### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} + +```ts +optional resource_signing_alg_values_supported: string[]; +``` + +Algorithmes de signature JWS pris en charge par la ressource protégée pour la signature des réponses de ressource. + +### resource\_tos\_uri? {#resource-tos-uri} + +```ts +optional resource_tos_uri: string; +``` + +URL contenant les conditions d'utilisation de la ressource protégée. + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +Liste des valeurs de portée utilisées dans les requêtes d'autorisation pour accéder à cette ressource protégée. + +### signed\_metadata? {#signed-metadata} + +```ts +optional signed_metadata: string; +``` + +Un JWT signé contenant les paramètres de métadonnées en tant que revendications (claims). Le JWT doit être signé à l'aide de JWS et inclure +une revendication 'iss'. Ce champ fournit un moyen de vérifier cryptographiquement l'authenticité des métadonnées +elles-mêmes. La signature peut être vérifiée à l'aide des clés publiques disponibles à l'endpoint `jwks_uri`. +Lorsqu'il est présent, les valeurs de ces métadonnées signées prévalent sur les valeurs JSON simples +correspondantes dans ce document de métadonnées. Cela aide à prévenir la falsification des métadonnées de la ressource. + +### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} + +```ts +optional tls_client_certificate_bound_access_tokens: boolean; +``` + +Indique si la ressource protégée prend en charge les jetons d’accès liés à un certificat client mutual-TLS. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md new file mode 100644 index 0000000..69361eb --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md @@ -0,0 +1,23 @@ +--- +sidebar_label: ResourceServerModeConfig +--- + +# Alias de type : ResourceServerModeConfig + +```ts +type ResourceServerModeConfig = { + protectedResources: ResourceServerConfig | ResourceServerConfig[]; +}; +``` + +Configuration pour le serveur MCP en mode serveur de ressources. + +## Propriétés {#properties} + +### protectedResources {#protectedresources} + +```ts +protectedResources: ResourceServerConfig | ResourceServerConfig[]; +``` + +Une configuration unique de serveur de ressources ou un tableau de celles-ci. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md new file mode 100644 index 0000000..7e80675 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md @@ -0,0 +1,31 @@ +--- +sidebar_label: ValidateIssuerFunction +--- + +# Alias de type : ValidateIssuerFunction() + +```ts +type ValidateIssuerFunction = (tokenIssuer: string) => void; +``` + +Type de fonction pour valider l’émetteur (Issuer) du jeton d’accès (Access token). + +Cette fonction doit lever une [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) avec le code 'invalid_issuer' si l’émetteur +n’est pas valide. L’émetteur doit être validé par rapport à : + +1. Les serveurs d’autorisation configurés dans les métadonnées du serveur d’authentification MCP-Auth +2. Les serveurs d’autorisation listés dans les métadonnées de la ressource protégée + +## Paramètres {#parameters} + +### tokenIssuer {#tokenissuer} + +`string` + +## Retourne {#returns} + +`void` + +## Lève une exception {#throws} + +Lorsque l’émetteur n’est pas reconnu ou invalide. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md new file mode 100644 index 0000000..4a43c15 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md @@ -0,0 +1,39 @@ +--- +sidebar_label: VerifyAccessTokenFunction +--- + +# Alias de type : VerifyAccessTokenFunction() + +```ts +type VerifyAccessTokenFunction = (token: string) => MaybePromise; +``` + +Type de fonction pour vérifier un jeton d’accès (Access token). + +Cette fonction doit lever une [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) si le jeton est invalide, +ou retourner un objet AuthInfo si le jeton est valide. + +Par exemple, si vous disposez d'une fonction de vérification JWT, elle doit au minimum vérifier la signature du jeton, +valider son expiration et extraire les revendications (Claims) nécessaires pour retourner un objet `AuthInfo`. + +**Remarque :** Il n'est pas nécessaire de vérifier les champs suivants dans le jeton, car ils seront contrôlés +par le gestionnaire : + +- `iss` (Émetteur / Issuer) +- `aud` (Audience) +- `scope` (Portées / Scopes) + +## Paramètres {#parameters} + +### token {#token} + +`string` + +La chaîne du jeton d’accès (Access token) à vérifier. + +## Retourne {#returns} + +`MaybePromise`\<`AuthInfo`\> + +Une promesse qui se résout en un objet AuthInfo ou une valeur synchrone si le +jeton est valide. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md new file mode 100644 index 0000000..b06a1fb --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: VerifyAccessTokenMode +--- + +# Alias de type : VerifyAccessTokenMode + +```ts +type VerifyAccessTokenMode = "jwt"; +``` + +Les modes de vérification intégrés pris en charge par `bearerAuth`. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md new file mode 100644 index 0000000..9001d1d --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: authServerErrorDescription +--- + +# Variable : authServerErrorDescription + +```ts +const authServerErrorDescription: Readonly>; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md new file mode 100644 index 0000000..5d2c0e8 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: authorizationServerMetadataSchema +--- + +# Variable : authorizationServerMetadataSchema + +```ts +const authorizationServerMetadataSchema: ZodObject; +``` + +Schéma Zod pour les métadonnées du serveur d’autorisation OAuth 2.0 telles que définies dans la RFC 8414. + +## Voir aussi {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md new file mode 100644 index 0000000..2a5bbc0 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: bearerAuthErrorDescription +--- + +# Variable : bearerAuthErrorDescription + +```ts +const bearerAuthErrorDescription: Readonly>; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md new file mode 100644 index 0000000..12b6f3f --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseAuthorizationServerMetadataSchema +--- + +# Variable : camelCaseAuthorizationServerMetadataSchema + +```ts +const camelCaseAuthorizationServerMetadataSchema: ZodObject; +``` + +La version camelCase du schéma Zod des métadonnées du serveur d’autorisation OAuth 2.0. + +## Voir aussi {#see} + +[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) pour le schéma original et les informations sur les champs. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md new file mode 100644 index 0000000..35740e9 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseProtectedResourceMetadataSchema +--- + +# Variable : camelCaseProtectedResourceMetadataSchema + +```ts +const camelCaseProtectedResourceMetadataSchema: ZodObject; +``` + +La version camelCase du schéma Zod des métadonnées de ressource protégée OAuth 2.0. + +## Voir aussi {#see} + +[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) pour le schéma original et les informations sur les champs. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md new file mode 100644 index 0000000..ec267a0 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md @@ -0,0 +1,9 @@ +--- +sidebar_label: defaultValues +--- + +# Variable : defaultValues + +```ts +const defaultValues: Readonly>; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md new file mode 100644 index 0000000..afdc590 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md @@ -0,0 +1,11 @@ +--- +sidebar_label: protectedResourceMetadataSchema +--- + +# Variable : protectedResourceMetadataSchema + +```ts +const protectedResourceMetadataSchema: ZodObject; +``` + +Schéma Zod pour les métadonnées de ressource protégée OAuth 2.0. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md new file mode 100644 index 0000000..33d94c8 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md @@ -0,0 +1,12 @@ +--- +sidebar_label: serverMetadataPaths +--- + +# Variable : serverMetadataPaths + +```ts +const serverMetadataPaths: Readonly<{ + oauth: "/.well-known/oauth-authorization-server"; + oidc: "/.well-known/openid-configuration"; +}>; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md new file mode 100644 index 0000000..b614049 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: tokenVerificationErrorDescription +--- + +# Variable : tokenVerificationErrorDescription + +```ts +const tokenVerificationErrorDescription: Readonly>; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md new file mode 100644 index 0000000..a307d3a --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md @@ -0,0 +1,9 @@ +--- +sidebar_label: validateServerConfig +--- + +# Variable : validateServerConfig + +```ts +const validateServerConfig: ValidateServerConfig; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx b/i18n/fr/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx new file mode 100644 index 0000000..00f677a --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx @@ -0,0 +1,73 @@ +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + + + + +```python +mcp = FastMCP("MyMCPServer") +resource_identifier = "https://api.example.com" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_identifier, + authorization_servers=[fetch_server_config('', AuthServerType.OIDC)], + scopes_supported=["read", "write"], + ) + ) +) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + Mount('/', app=mcp.sse_app(), middleware=[Middleware( + mcp_auth.bearer_auth_middleware("jwt", + resource=resource_identifier, + audience=resource_identifier, + required_scopes=["read", "write"] + ) + )]) + ] +) + +@mcp.tool() +def whoami(): + return mcp_auth.auth_info.claims +``` + + + + +```ts +const server = new McpServer(/* ... */); +const resourceIdentifier = 'https://api.example.com'; + +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceIdentifier, + authorizationServers: [await fetchServerConfig('', { type: 'oidc' })], + scopesSupported: ['read', 'write'], + } + } +}); + +const app = express(); + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +app.use(mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, + requiredScopes: ['read', 'write'] +})); + +server.tool('whoami', ({ authInfo }) => { + return authInfo.claims; +}); +``` + + + diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx b/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx new file mode 100644 index 0000000..1579749 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx @@ -0,0 +1,1396 @@ +--- +sidebar_position: 2 +sidebar_label: 'Tutoriel : Créer un gestionnaire de tâches' +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + +# Tutoriel : Créer un gestionnaire de tâches + +Dans ce tutoriel, nous allons construire un serveur MCP de gestionnaire de tâches avec authentification et autorisation des utilisateurs. En suivant la dernière spécification MCP, notre serveur MCP agira comme un **Serveur de ressources** OAuth 2.0 qui valide les jetons d’accès et applique les permissions basées sur les portées (scopes). + +Après avoir terminé ce tutoriel, vous aurez : + +- ✅ Une compréhension de base de la configuration du contrôle d’accès basé sur les rôles (RBAC) dans votre serveur MCP. +- ✅ Un serveur MCP qui agit comme un Serveur de ressources, consommant des jetons d’accès émis par un Serveur d’autorisation. +- ✅ Une implémentation fonctionnelle de l’application des permissions basées sur les portées pour les opérations sur les tâches. + +## Vue d’ensemble \{#overview} + +Le tutoriel impliquera les composants suivants : + +- **Client MCP (MCP Inspector)** : Un outil visuel de test pour les serveurs MCP qui agit comme un client OAuth 2.0/OIDC. Il initie le flux d’autorisation avec le serveur d’autorisation et obtient des jetons d’accès pour authentifier les requêtes vers le serveur MCP. +- **Serveur d’autorisation** : Un fournisseur OAuth 2.1 ou OpenID Connect qui gère les identités des utilisateurs, authentifie les utilisateurs et émet des jetons d’accès avec les portées appropriées aux clients autorisés. +- **Serveur MCP (Serveur de ressources)** : Selon la dernière spécification MCP, le serveur MCP agit comme un Serveur de ressources dans le cadre OAuth 2.0. Il valide les jetons d’accès émis par le serveur d’autorisation et applique les permissions basées sur les portées pour les opérations sur les tâches. + +Cette architecture suit le flux standard OAuth 2.0 où : +- Le **MCP Inspector** demande des ressources protégées au nom de l’utilisateur +- Le **Serveur d’autorisation** authentifie l’utilisateur et émet des jetons d’accès +- Le **Serveur MCP** valide les jetons et sert les ressources protégées selon les permissions accordées + +Voici un schéma de haut niveau de l’interaction entre ces composants : + +```mermaid +sequenceDiagram + autonumber + participant Client as MCP Inspector
(Client OAuth) + participant RS as Serveur MCP
(Serveur de ressources) + participant AS as Serveur d’autorisation + + Client->>RS: Requête MCP (pas de jeton) + RS-->>Client: 401 Non autorisé (WWW-Authenticate) + Note over Client: Extraire l’URL resource_metadata
depuis l’en-tête WWW-Authenticate + + Client->>RS: GET /.well-known/oauth-protected-resource (resource_metadata) + RS-->>Client: Métadonnées de la ressource protégée
(inclut l’URL du serveur d’autorisation) + + Client->>AS: GET /.well-known/oauth-authorization-server + AS-->>Client: Métadonnées du serveur d’autorisation + Client->>AS: Autorisation OAuth (connexion & consentement) + AS-->>Client: Jeton d’accès + + Client->>RS: Requête MCP (Authorization: Bearer ) + RS->>RS: Valider que le jeton d’accès est valide et autorisé + RS-->>Client: Réponse MCP +``` + +## Comprendre votre serveur d’autorisation \{#understand-your-authorization-server} + +### Jetons d’accès avec portées \{#access-tokens-with-scopes} + +Pour mettre en œuvre le [contrôle d’accès basé sur les rôles (RBAC)](https://auth.wiki/rbac) dans votre serveur MCP, votre serveur d’autorisation doit prendre en charge l’émission de jetons d’accès avec des portées. Les portées représentent les permissions accordées à un utilisateur. + + + + +[Logto](https://logto.io) propose la prise en charge du RBAC via ses ressources API (conformes à [RFC 8707 : Indicateurs de ressource pour OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707)) et ses fonctionnalités de rôles. Voici comment le configurer : + +1. Connectez-vous à [Logto Console](https://cloud.logto.io) (ou à votre propre instance Logto Console) + +2. Créez une ressource API et des portées : + + - Allez dans "Ressources API" + - Créez une nouvelle ressource API nommée "Gestionnaire de tâches" + - Ajoutez les portées suivantes : + - `create:todos` : "Créer de nouvelles tâches" + - `read:todos` : "Lire toutes les tâches" + - `delete:todos` : "Supprimer n’importe quelle tâche" + +3. Créez des rôles (recommandé pour une gestion plus facile) : + + - Allez dans "Rôles" + - Créez un rôle "Admin" et assignez toutes les portées (`create:todos`, `read:todos`, `delete:todos`) + - Créez un rôle "User" et assignez uniquement la portée `create:todos` + +4. Attribuez les permissions : + - Allez dans "Utilisateurs" + - Sélectionnez un utilisateur + - Vous pouvez soit : + - Attribuer des rôles dans l’onglet "Rôles" (recommandé) + - Ou attribuer directement des portées dans l’onglet "Permissions" + +Les portées seront incluses dans la revendication `scope` du jeton d’accès JWT sous forme de chaîne séparée par des espaces. + + + + +Les fournisseurs OAuth 2.0 / OIDC prennent généralement en charge le contrôle d’accès basé sur les portées. Lors de la mise en œuvre du RBAC : + +1. Définissez les portées requises dans votre serveur d’autorisation +2. Configurez votre client pour demander ces portées lors du flux d’autorisation +3. Assurez-vous que votre serveur d’autorisation inclut les portées accordées dans le jeton d’accès +4. Les portées sont généralement incluses dans la revendication `scope` du jeton d’accès JWT + +Consultez la documentation de votre fournisseur pour plus de détails sur : + +- Comment définir et gérer les portées +- Comment les portées sont incluses dans le jeton d’accès +- Toutes fonctionnalités RBAC supplémentaires comme la gestion des rôles + + + + +### Validation des jetons et vérification des permissions \{#validating-tokens-and-checking-permissions} + +Selon la dernière spécification MCP, le serveur MCP agit comme un **Serveur de ressources** dans le cadre OAuth 2.0. En tant que Serveur de ressources, le serveur MCP a les responsabilités suivantes : + +1. **Validation du jeton** : Vérifier l’authenticité et l’intégrité des jetons d’accès reçus des clients MCP +2. **Application des portées** : Extraire et valider les portées du jeton d’accès pour déterminer quelles opérations le client est autorisé à effectuer +3. **Protection des ressources** : Ne servir les ressources protégées (exécuter les outils) que lorsque le client présente des jetons valides avec des permissions suffisantes + +Lorsque votre serveur MCP reçoit une requête, il effectue le processus de validation suivant : + +1. Extraire le jeton d’accès de l’en-tête `Authorization` (format Bearer token) +2. Valider la signature et l’expiration du jeton d’accès +3. Extraire les portées et les informations utilisateur du jeton validé +4. Vérifier si le jeton possède les portées requises pour l’opération demandée + +Par exemple, si un utilisateur souhaite créer une nouvelle tâche, son jeton d’accès doit inclure la portée `create:todos`. Voici comment fonctionne le flux de validation côté Serveur de ressources : + +```mermaid +sequenceDiagram + participant Client as Client MCP + participant Server as Serveur MCP
(Serveur de ressources) + participant Auth as Serveur d’autorisation + + Client->>Server: Requête avec jeton d’accès
(Authorization: Bearer ) + + alt Validation JWT (Préféré) + Server->>Auth: Récupérer JWKS (si non mis en cache) + Auth-->>Server: Retourner JWKS + Server->>Server: Valider la signature JWT & les revendications localement + else Introspection du jeton (Fallback) + Server->>Auth: POST /introspect
(token=access_token) + Auth-->>Server: Retourner les infos du jeton
(active, scope, user_id, etc.) + end + + Server->>Server: Extraire les portées & le contexte utilisateur
du jeton validé + + alt Possède les portées requises + Server->>Server: Exécuter l’opération demandée + Server->>Client: Retourner le résultat de l’opération + else Portées requises manquantes + Server->>Client: Retourner 403 Interdit
(erreur insufficient_scope) + end +``` + +### Enregistrement dynamique de client \{#dynamic-client-registration} + +L’enregistrement dynamique de client n’est pas requis pour ce tutoriel, mais il peut être utile si vous souhaitez automatiser le processus d’enregistrement du client MCP auprès de votre serveur d’autorisation. Consultez [L’enregistrement dynamique de client est-il requis ?](/provider-list#is-dcr-required) pour plus de détails. + +## Comprendre le RBAC dans le gestionnaire de tâches \{#understand-rbac-in-todo-manager} + +À des fins de démonstration, nous allons implémenter un système simple de contrôle d’accès basé sur les rôles (RBAC) dans notre serveur MCP gestionnaire de tâches. Cela vous montrera les principes de base du RBAC tout en gardant l’implémentation simple. + +:::note +Bien que ce tutoriel démontre la gestion des portées basée sur le RBAC, il est important de noter que tous les fournisseurs d’authentification n’implémentent pas la gestion des portées via les rôles. Certains fournisseurs peuvent avoir leurs propres mécanismes uniques pour gérer le contrôle d’accès et les permissions. +::: + +### Outils et portées \{#tools-and-scopes} + +Notre serveur MCP gestionnaire de tâches fournit trois outils principaux : + +- `create-todo` : Créer une nouvelle tâche +- `get-todos` : Lister toutes les tâches +- `delete-todo` : Supprimer une tâche par ID + +Pour contrôler l’accès à ces outils, nous définissons les portées suivantes : + +- `create:todos` : Autorise la création de nouvelles tâches +- `delete:todos` : Autorise la suppression de tâches existantes +- `read:todos` : Autorise la consultation et la récupération de la liste de toutes les tâches + +### Rôles et permissions \{#roles-and-permissions} + +Nous définirons deux rôles avec différents niveaux d’accès : + +| Rôle | create:todos | read:todos | delete:todos | +| ----- | ------------ | ---------- | ------------ | +| Admin | ✅ | ✅ | ✅ | +| User | ✅ | | | + +- **User** : Un utilisateur standard qui peut créer des tâches et voir ou supprimer uniquement ses propres tâches +- **Admin** : Un administrateur qui peut créer, voir et supprimer toutes les tâches, quel que soit le propriétaire + +### Propriété des ressources \{#resource-ownership} + +Bien que le tableau des permissions ci-dessus montre les portées explicites attribuées à chaque rôle, il y a un principe important de propriété des ressources à considérer : + +- **Les utilisateurs** n’ont pas les portées `read:todos` ou `delete:todos`, mais ils peuvent quand même : + - Lire leurs propres tâches + - Supprimer leurs propres tâches +- **Les admins** ont toutes les permissions (`read:todos` et `delete:todos`), ce qui leur permet de : + - Voir toutes les tâches du système + - Supprimer n’importe quelle tâche, quel que soit le propriétaire + +Cela illustre un schéma courant dans les systèmes RBAC où la propriété d’une ressource accorde des permissions implicites aux utilisateurs pour leurs propres ressources, tandis que les rôles administratifs reçoivent des permissions explicites pour toutes les ressources. + +:::tip En savoir plus +Pour approfondir les concepts et bonnes pratiques du RBAC, consultez [Maîtriser le RBAC : Un exemple complet et réel](https://blog.logto.io/mastering-rbac). +::: + +## Configurer l’autorisation dans votre fournisseur \{#configure-authorization-in-your-provider} + +Pour mettre en œuvre le système de contrôle d’accès décrit précédemment, vous devrez configurer votre serveur d’autorisation pour prendre en charge les portées requises. Voici comment faire avec différents fournisseurs : + + + + +[Logto](https://logto.io) propose la prise en charge du RBAC via ses ressources API et ses fonctionnalités de rôles. Voici comment le configurer : + +1. Connectez-vous à [Logto Console](https://cloud.logto.io) (ou à votre propre instance Logto Console) + +2. Créez une ressource API et des portées : + + - Allez dans "Ressources API" + - Créez une nouvelle ressource API nommée "Gestionnaire de tâches" et utilisez `http://localhost:3001` comme indicateur de ressource. + - **Important** : L’indicateur de ressource doit correspondre à l’URL de votre serveur MCP. Pour ce tutoriel, nous utilisons `http://localhost:3001` puisque notre serveur MCP fonctionne sur le port 3001. En production, utilisez l’URL réelle de votre serveur MCP (par exemple, `https://votre-mcp-server.example.com`). + - Créez les portées suivantes : + - `create:todos` : "Créer de nouvelles tâches" + - `read:todos` : "Lire toutes les tâches" + - `delete:todos` : "Supprimer n’importe quelle tâche" + +3. Créez des rôles (recommandé pour une gestion plus facile) : + + - Allez dans "Rôles" + - Créez un rôle "Admin" et assignez toutes les portées (`create:todos`, `read:todos`, `delete:todos`) + - Créez un rôle "User" et assignez uniquement la portée `create:todos` + - Dans la page de détails du rôle "User", passez à l’onglet "Général" et définissez le rôle "User" comme "Rôle par défaut". + +4. Gérez les rôles et permissions des utilisateurs : + - Pour les nouveaux utilisateurs : + - Ils recevront automatiquement le rôle "User" puisque nous l’avons défini comme rôle par défaut + - Pour les utilisateurs existants : + - Allez dans "Gestion des utilisateurs" + - Sélectionnez un utilisateur + - Attribuez des rôles à l’utilisateur dans l’onglet "Rôles" + +:::tip Gestion programmatique des rôles +Vous pouvez également utiliser la [Management API](https://docs.logto.io/integrate-logto/interact-with-management-api) de Logto pour gérer les rôles des utilisateurs de manière programmatique. Ceci est particulièrement utile pour la gestion automatisée des utilisateurs ou lors de la création de panneaux d’administration. +::: + +Lors de la demande d’un jeton d’accès, Logto inclura les portées dans la revendication `scope` du jeton en fonction des permissions de rôle de l’utilisateur. + + + + +Pour les fournisseurs OAuth 2.0 ou OpenID Connect, vous devrez configurer les portées qui représentent différentes permissions. Les étapes exactes dépendront de votre fournisseur, mais généralement : + +1. Définissez les portées : + + - Configurez votre serveur d’autorisation pour prendre en charge : + - `create:todos` + - `read:todos` + - `delete:todos` + +2. Configurez le client : + + - Enregistrez ou mettez à jour votre client pour demander ces portées + - Assurez-vous que les portées sont incluses dans le jeton d’accès + +3. Attribuez les permissions : + - Utilisez l’interface de votre fournisseur pour accorder les portées appropriées aux utilisateurs + - Certains fournisseurs peuvent prendre en charge la gestion basée sur les rôles, tandis que d’autres utilisent des attributions directes de portées + - Consultez la documentation de votre fournisseur pour l’approche recommandée + +:::tip +La plupart des fournisseurs incluront les portées accordées dans la revendication `scope` du jeton d’accès. Le format est généralement une chaîne de valeurs de portées séparées par des espaces. +::: + + + + +Après avoir configuré votre serveur d’autorisation, les utilisateurs recevront des jetons d’accès contenant leurs portées accordées. Le serveur MCP utilisera ces portées pour déterminer : + +- Si un utilisateur peut créer de nouvelles tâches (`create:todos`) +- Si un utilisateur peut voir toutes les tâches (`read:todos`) ou seulement les siennes +- Si un utilisateur peut supprimer n’importe quelle tâche (`delete:todos`) ou seulement les siennes + +## Mettre en place le serveur MCP \{#set-up-the-mcp-server} + +Nous allons utiliser les [SDKs officiels MCP](https://github.com/modelcontextprotocol) pour créer notre serveur MCP gestionnaire de tâches. + +### Créer un nouveau projet \{#create-a-new-project} + + + + +Créez un nouveau projet Python : + +```bash +mkdir mcp-todo-server +cd mcp-todo-server + +# Initialiser un nouveau projet Python +uv init + +# Créer un nouvel environnement virtuel avec uv +uv venv + +# Activer l’environnement virtuel (optionnel avec 'uv run') +source .venv/bin/activate +``` + +:::note +Ce projet utilise `uv` pour la gestion des paquets, mais vous pouvez utiliser d’autres gestionnaires comme `pip`, `poetry` ou `conda` si vous préférez. +::: + + + + +Créez un nouveau projet Node.js : + +```bash +mkdir mcp-server +cd mcp-server +npm init -y # Ou utilisez `pnpm init` +npm pkg set type="module" +npm pkg set main="todo-manager.ts" +npm pkg set scripts.start="node --experimental-strip-types todo-manager.ts" +``` + +:::note +Nous utilisons TypeScript dans nos exemples car Node.js v22.6.0+ prend en charge l’exécution native de TypeScript avec l’option `--experimental-strip-types`. Si vous utilisez JavaScript, le code sera similaire - assurez-vous simplement d’utiliser Node.js v22.6.0 ou ultérieur. Voir la documentation Node.js pour plus de détails. +::: + + + + +### Installer le SDK MCP et les dépendances \{#install-the-mcp-sdk-and-dependencies} + + + + +Installez les dépendances requises : + +```bash +uv add "mcp[cli]" uvicorn starlette +``` + + + + +```bash +npm install @modelcontextprotocol/sdk express zod +``` + +Ou tout autre gestionnaire de paquets que vous préférez, comme `pnpm` ou `yarn`. + + + + +### Créer le serveur MCP \{#create-the-mcp-server} + +Commençons par créer un serveur MCP de base avec la définition des outils : + + + + +Créez un fichier nommé `server.py` et ajoutez le code suivant : + +```python +# server.py + +import contextlib +from typing import Any +from mcp.server.fastmcp import FastMCP +from starlette.applications import Starlette +from starlette.routing import Mount + +# Initialiser le serveur FastMCP +mcp = FastMCP(name="Gestionnaire de tâches", stateless_http=True, streamable_http_path='/') + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """Créer une nouvelle tâche. Nécessite la portée 'create:todos'.""" + return {"error": "Not implemented"} + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """Lister les tâches. Les utilisateurs avec la portée 'read:todos' peuvent voir toutes les tâches.""" + return {"error": "Not implemented"} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """Supprimer une tâche par id. Les utilisateurs peuvent supprimer leurs propres tâches.""" + return {"error": "Not implemented"} + +@contextlib.asynccontextmanager +async def lifespan(app: Starlette): + async with contextlib.AsyncExitStack() as stack: + await stack.enter_async_context(mcp.session_manager.run()) + yield + +# Créer l’application +app = Starlette( + routes=[ + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + +Lancez le serveur avec : + +```bash +# Démarrer le serveur Gestionnaire de tâches avec uvicorn +uvicorn server:app --host 127.0.0.1 --port 3001 + +# Ou avec uv : +# uv run uvicorn server:app --host 127.0.0.1 --port 3001 +``` + + + + +Créez un fichier nommé `todo-manager.ts` et ajoutez le code suivant : + +```ts +// todo-manager.ts + +import { z } from 'zod'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import express, { type Request, type Response } from 'express'; + +// Créer un serveur MCP +const server = new McpServer({ + name: 'Gestionnaire de tâches', + version: '0.0.0', +}); + +server.tool('create-todo', 'Créer une nouvelle tâche', { content: z.string() }, async ({ content }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('get-todos', 'Lister toutes les tâches', async () => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('delete-todo', 'Supprimer une tâche par id', { id: z.string() }, async ({ id }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +// Ci-dessous le code standard issu de la documentation du SDK MCP +const PORT = 3001; +const app = express(); + +app.post('/', async (request: Request, response: Response) => { + // En mode stateless, créez une nouvelle instance de transport et de serveur pour chaque requête + // afin d’assurer une isolation complète. Une seule instance provoquerait des collisions d’ID de requête + // lorsque plusieurs clients se connectent simultanément. + + try { + const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + }); + response.on('close', async () => { + console.log('Request closed'); + await transport.close(); + await server.close(); + }); + await server.connect(transport); + await transport.handleRequest(request, response, request.body); + } catch (error) { + console.error('Error handling MCP request:', error); + if (!response.headersSent) { + response.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32_603, + message: 'Internal server error', + }, + id: null, + }); + } + } +}); + +// Les notifications SSE ne sont pas prises en charge en mode stateless +app.get('/', async (request: Request, response: Response) => { + console.log('Received GET MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +// La terminaison de session n’est pas nécessaire en mode stateless +app.delete('/', async (request: Request, response: Response) => { + console.log('Received DELETE MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +app.listen(PORT); +``` + +Lancez le serveur avec : + +```bash +npm start +``` + + + + +## Inspecter le serveur MCP \{#inspect-the-mcp-server} + +### Cloner et lancer MCP inspector \{#clone-and-run-mcp-inspector} + +Maintenant que nous avons le serveur MCP en fonctionnement, nous pouvons utiliser le MCP inspector pour vérifier si les outils sont disponibles. + +La version officielle MCP inspector v0.16.2 présente certains bugs qui affectent la fonctionnalité d’authentification. Pour résoudre ces problèmes, nous avons créé une [version corrigée du MCP inspector](https://github.com/mcp-auth/inspector/tree/patch/0.16.2-fixes) qui inclut les correctifs nécessaires pour les flux d’authentification OAuth/OIDC. Nous avons également soumis des pull requests au dépôt officiel pour contribuer ces correctifs en amont. + +Pour lancer le MCP inspector, utilisez la commande suivante (Node.js requis) : + +```bash +git clone https://github.com/mcp-auth/inspector.git -b patch/0.16.2-fixes +cd inspector +npm install +npm run dev +``` + +Le MCP inspector s’ouvrira automatiquement dans votre navigateur par défaut, ou vous pouvez y accéder manuellement en cliquant sur le lien affiché dans le terminal (assurez-vous de cliquer sur le lien qui inclut le paramètre `MCP_PROXY_AUTH_TOKEN`, tel que `http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=458ae4a4...acab1907`). + +### Connecter MCP inspector au serveur MCP \{#connect-mcp-inspector-to-the-mcp-server} + +Avant de continuer, vérifiez la configuration suivante dans MCP inspector : + +- **Type de transport** : Définir sur `Streamable HTTP`. +- **URL** : Définir sur l’URL de votre serveur MCP. Dans notre cas, il s’agit de `http://localhost:3001`. + +Vous pouvez maintenant cliquer sur le bouton "Connect" pour voir si le MCP inspector peut se connecter au serveur MCP. Si tout est correct, vous devriez voir le statut "Connected" dans le MCP inspector. + +### Point de contrôle : Exécuter les outils du gestionnaire de tâches \{#checkpoint-run-todo-manager-tools} + +1. Dans le menu supérieur du MCP inspector, cliquez sur l’onglet "Tools". +2. Cliquez sur le bouton "List Tools". +3. Vous devriez voir les outils `create-todo`, `get-todos` et `delete-todo` listés sur la page. Cliquez dessus pour ouvrir les détails de l’outil. +4. Vous devriez voir le bouton "Run Tool" sur la droite. Cliquez dessus et saisissez les paramètres requis pour exécuter l’outil. +5. Vous devriez voir le résultat de l’outil avec la réponse JSON `{"error": "Not implemented"}`. + +![Premier lancement du MCP inspector](/docs-assets/images/tutorials/todo-manager/inspector-first-run.png) + +## Intégrer avec votre serveur d’autorisation \{#integrate-with-your-authorization-server} + +Pour compléter cette section, plusieurs points sont à prendre en compte : + +
+**L’URL de l’émetteur de votre serveur d’autorisation** + +Il s’agit généralement de l’URL de base de votre serveur d’autorisation, comme `https://auth.example.com`. Certains fournisseurs peuvent avoir un chemin comme `https://example.logto.app/oidc`, alors vérifiez la documentation de votre fournisseur. + +
+ +
+**Comment récupérer les métadonnées du serveur d’autorisation** + +- Si votre serveur d’autorisation est conforme à [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) ou [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html), vous pouvez utiliser les utilitaires intégrés de MCP Auth pour récupérer automatiquement les métadonnées. +- Si votre serveur d’autorisation n’est pas conforme à ces standards, vous devrez spécifier manuellement l’URL des métadonnées ou les points de terminaison dans la configuration du serveur MCP. Consultez la documentation de votre fournisseur pour les points de terminaison spécifiques. + +
+ +
+**Comment enregistrer le MCP inspector comme client dans votre serveur d’autorisation** + +- Si votre serveur d’autorisation prend en charge [l’enregistrement dynamique de client](https://datatracker.ietf.org/doc/html/rfc7591), vous pouvez passer cette étape car le MCP inspector s’enregistrera automatiquement comme client. +- Si votre serveur d’autorisation ne prend pas en charge l’enregistrement dynamique de client, vous devrez enregistrer manuellement le MCP inspector comme client dans votre serveur d’autorisation. + +
+ +
+**Comprendre les paramètres de la requête de jeton** + +Lorsque vous demandez des jetons d’accès à différents serveurs d’autorisation, vous rencontrerez diverses approches pour spécifier la ressource cible et les permissions. Voici les principaux schémas : + +- **Basé sur l’indicateur de ressource** : + + - Utilise le paramètre `resource` pour spécifier l’API cible (voir [RFC 8707 : Indicateurs de ressource pour OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707)) + - Courant dans les implémentations OAuth 2.0 modernes + - Exemple de requête : + ```json + { + "resource": "http://localhost:3001", + "scope": "create:todos read:todos" + } + ``` + - Le serveur émet des jetons liés spécifiquement à la ressource demandée + +- **Basé sur l’audience** : + + - Utilise le paramètre `audience` pour spécifier le destinataire prévu du jeton + - Semblable aux indicateurs de ressource mais avec des sémantiques différentes + - Exemple de requête : + ```json + { + "audience": "todo-api", + "scope": "create:todos read:todos" + } + ``` + +- **Basé uniquement sur les portées** : + - S’appuie uniquement sur les portées sans paramètres de ressource/audience + - Approche OAuth 2.0 traditionnelle + - Exemple de requête : + ```json + { + "scope": "todo-api:create todo-api:read openid profile" + } + ``` + - Utilise souvent des portées préfixées pour nommer les permissions + - Courant dans les implémentations OAuth 2.0 plus simples + +:::tip Bonnes pratiques + +- Consultez la documentation de votre fournisseur pour les paramètres pris en charge +- Certains fournisseurs prennent en charge plusieurs approches simultanément +- Les indicateurs de ressource offrent une meilleure sécurité via la restriction d’audience +- Envisagez d’utiliser les indicateurs de ressource lorsque c’est possible pour un meilleur contrôle d’accès + ::: + +
+ +Bien que chaque fournisseur puisse avoir ses propres exigences spécifiques, les étapes suivantes vous guideront dans l’intégration du MCP inspector et du serveur MCP avec des configurations spécifiques au fournisseur. + +### Enregistrer MCP inspector comme client \{#register-mcp-inspector-as-a-client} + + + + +L’intégration du gestionnaire de tâches avec [Logto](https://logto.io) est simple car il s’agit d’un fournisseur OpenID Connect qui prend en charge les indicateurs de ressource et les portées, ce qui vous permet de sécuriser votre API de tâches avec `http://localhost:3001` comme indicateur de ressource. + +Comme Logto ne prend pas encore en charge l’enregistrement dynamique de client, vous devrez enregistrer manuellement le MCP inspector comme client dans votre tenant Logto : + +1. Ouvrez votre MCP inspector, allez dans la configuration Authentification et cliquez sur la configuration "OAuth2.0 Flow". Copiez la valeur **Redirect URI**, qui devrait ressembler à `http://localhost:6274/oauth/callback`. +2. Connectez-vous à [Logto Console](https://cloud.logto.io) (ou à votre propre instance Logto Console). +3. Naviguez vers l’onglet "Applications", cliquez sur "Créer une application". En bas de la page, cliquez sur "Créer une application sans framework". +4. Remplissez les détails de l’application, puis cliquez sur "Créer une application" : + - **Sélectionnez un type d’application** : Choisissez "Application monopage". + - **Nom de l’application** : Saisissez un nom pour votre application, par exemple "MCP Inspector". +5. Dans la section "Paramètres / URI de redirection", collez la valeur **Redirect URI** copiée depuis le MCP inspector. Cliquez ensuite sur "Enregistrer les modifications" dans la barre inférieure. +6. Dans la carte supérieure, vous verrez la valeur "App ID". Copiez-la. +7. Retournez dans le MCP inspector et collez la valeur "App ID" dans la configuration Authentification sous "OAuth2.0 Flow" dans le champ "Client ID". +8. Dans le champ "Scope", saisissez : `create:todos read:todos delete:todos`. Cela garantira que le jeton d’accès retourné par Logto contient les portées nécessaires pour accéder au gestionnaire de tâches. + + + + +:::note +Ceci est un guide générique d’intégration pour les fournisseurs OAuth 2.0 / OpenID Connect. Les deux suivent des étapes similaires car OIDC est construit sur OAuth 2.0. Consultez la documentation de votre fournisseur pour les détails spécifiques. +::: + +Si votre fournisseur prend en charge l’enregistrement dynamique de client, vous pouvez passer directement à l’étape 8 ci-dessous pour configurer le MCP inspector ; sinon, vous devrez enregistrer manuellement le MCP inspector comme client : + +1. Ouvrez votre MCP inspector, allez dans la configuration Authentification et cliquez sur la configuration "OAuth2.0 Flow". Copiez la valeur **Redirect URI**, qui devrait ressembler à `http://localhost:6274/oauth/callback`. + +2. Connectez-vous à la console de votre fournisseur. + +3. Naviguez vers la section "Applications" ou "Clients", puis créez une nouvelle application ou client. + +4. Si votre fournisseur demande un type de client, sélectionnez "Application monopage" ou "Client public". + +5. Après avoir créé l’application, vous devrez configurer l’URI de redirection. Collez la valeur **Redirect URI** copiée depuis le MCP inspector. + +6. Trouvez le "Client ID" ou "Application ID" de la nouvelle application et copiez-le. + +7. Retournez dans le MCP inspector et collez la valeur "Client ID" dans la configuration Authentification sous "OAuth2.0 Flow" dans le champ "Client ID". + +8. Dans le champ "Scope", saisissez les portées suivantes pour demander les permissions nécessaires aux opérations sur les tâches : + +```text +create:todos read:todos delete:todos +``` + + + + +### Configurer MCP Auth \{#set-up-mcp-auth} + +Commencez par installer le SDK MCP Auth dans votre projet serveur MCP. + + + + +```bash +uv add mcpauth==0.2.0b1 +``` + + + + +```bash +npm install mcp-auth@0.2.0-beta.1 +``` + + + + +Nous devons maintenant initialiser MCP Auth dans votre serveur MCP. Cela implique deux étapes principales : + +1. **Récupération des métadonnées du serveur d’autorisation** : Utilisé pour la vérification ultérieure par MCP Auth des jetons d’accès émis par le Serveur d’autorisation, et pour inclure l’identifiant de l’émetteur du serveur d’auth dans les métadonnées de ressource +2. **Configurer les métadonnées de la ressource protégée** : Définir l’identifiant de ressource de votre serveur MCP et les portées prises en charge + +#### Étape 1 : Récupérer les métadonnées du serveur d’autorisation \{#step-1-fetch-authorization-server-metadata\} + +Selon la spécification OAuth / OIDC, nous pouvons récupérer les métadonnées du serveur d’autorisation à partir de l’URL de l’émetteur du serveur d’autorisation. + + + + + +Dans Logto, vous pouvez trouver l’URL de l’émetteur sur la page de détails de votre application dans Logto Console, sous la section "Endpoints & Credentials / Issuer endpoint". Elle devrait ressembler à `https://my-project.logto.app/oidc`. + + + + + +Pour les fournisseurs OAuth 2.0, vous devrez : + +1. Vérifier la documentation de votre fournisseur pour l’URL du serveur d’autorisation (souvent appelée URL de l’émetteur ou URL de base) +2. Certains fournisseurs l’exposent à `https://{votre-domaine}/.well-known/oauth-authorization-server` +3. Chercher dans la console d’administration de votre fournisseur sous les paramètres OAuth/API + + + + + +Maintenant, récupérez les métadonnées du serveur d’autorisation à l’aide de la fonction utilitaire MCP Auth pour obtenir la configuration du serveur : + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +issuer_url = "" # Remplacez par l’URL de l’émetteur de votre serveur d’autorisation + +# Récupérer la configuration du serveur d’autorisation +auth_server_config = fetch_server_config(issuer_url, AuthServerType.OIDC) # ou AuthServerType.OAUTH +``` + + + +```js +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const issuerUrl = ''; // Remplacez par l’URL de l’émetteur de votre serveur d’autorisation + +// Récupérer la configuration du serveur d’autorisation (OIDC Discovery) +const authServerConfig = await fetchServerConfig(issuerUrl, { type: 'oidc' }); // ou { type: 'oauth' } +``` + + + + +Si vous souhaitez d’autres moyens de récupérer les métadonnées du serveur d’autorisation ou personnaliser la configuration, veuillez consulter [d’autres façons de configurer les métadonnées du serveur d’autorisation](/docs/configure-server/mcp-auth#other-ways). + +#### Étape 2 : Configurer les métadonnées de la ressource protégée \{#step-2-configure-protected-resource-metadata} + +Ensuite, nous allons configurer les métadonnées de la ressource protégée lors de la création de l’instance MCP Auth. Par la suite, le serveur MCP exposera les métadonnées de ressource configurées dans MCP Auth. + + + + +```python +# server.py + +# autres imports... +from mcpauth.types import ResourceServerConfig, ResourceServerMetadata + +# Définir l’identifiant de ressource pour ce serveur MCP +resource_id = "http://localhost:3001" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + # Métadonnées du serveur d’autorisation récupérées à l’étape précédente + authorization_servers=[auth_server_config], + # Portées prises en charge par ce serveur MCP + scopes_supported=[ + "create:todos", + "read:todos", + "delete:todos" + ] + ) + ) +) +``` + + + +```js +// todo-manager.ts + +// Définir l’identifiant de ressource pour ce serveur MCP +const resourceId = 'http://localhost:3001'; + +// Configurer MCP Auth avec les métadonnées de la ressource protégée +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceId, + // Métadonnées du serveur d’autorisation récupérées à l’étape précédente + authorizationServers: [authServerConfig], + // Portées prises en charge par ce serveur MCP + scopesSupported: [ + "create:todos", + "read:todos", + "delete:todos" + ] + } + } +}); +``` + + + + +### Mettre à jour le serveur MCP \{#update-mcp-server} + +Nous y sommes presque ! Il est temps de mettre à jour le serveur MCP pour appliquer la route et la fonction middleware MCP Auth, puis d’implémenter le contrôle d’accès basé sur les permissions pour les outils du gestionnaire de tâches selon les portées de l’utilisateur. + +Appliquez maintenant les routes de métadonnées de ressource protégée afin que les clients MCP puissent récupérer les métadonnées attendues depuis le serveur MCP. + + + +```python +# server.py + +# ..autres codes + +app = Starlette( + routes=[ + # Mettre en place les routes de métadonnées de ressource protégée + # Cela expose les métadonnées de ce serveur de ressources pour les clients OAuth + *mcp_auth.resource_metadata_router().routes, + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +// Mettre en place les routes de métadonnées de ressource protégée +// Cela expose les métadonnées de ce serveur de ressources pour les clients OAuth +app.use(mcpAuth.protectedResourceMetadataRouter()); + +``` + + + +Ensuite, nous allons appliquer le middleware MCP Auth au serveur MCP. Ce middleware gérera l’authentification et l’autorisation des requêtes entrantes, garantissant que seuls les utilisateurs autorisés peuvent accéder aux outils du gestionnaire de tâches. + + + +```python +# server.py + +# autres imports... +from starlette.middleware import Middleware + +# autres codes... + +# Créer le middleware +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', resource=resource_id, audience=resource_id)) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # Appliquer le middleware MCP Auth + Mount("/", app=mcp.streamable_http_app(), middleware=[bearer_auth]), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Appliquer le middleware MCP Auth +app.use( + mcpAuth.bearerAuth('jwt', { + resource: resourceId, + audience: resourceId, + }) +); +``` + + + +À ce stade, nous pouvons mettre à jour les outils du gestionnaire de tâches pour exploiter le middleware MCP Auth pour l’authentification et l’autorisation. + +Mettons à jour l’implémentation des outils. + + + +```python +# server.py + +# autres imports... + +from typing import Any, List, Optional +from mcpauth.exceptions import MCPAuthBearerAuthException, BearerAuthExceptionCode +from mcpauth.types import AuthInfo, ResourceServerConfig, ResourceServerMetadata + +# Nous en parlerons dans la section suivante +from service import TodoService + +def assert_user_id(auth_info: Optional[AuthInfo]) -> str: + """Vérifie que auth_info contient un ID utilisateur valide et le retourne.""" + if not auth_info or not auth_info.subject: + raise Exception("Invalid auth info") + return auth_info.subject + +def has_required_scopes(user_scopes: List[str], required_scopes: List[str]) -> bool: + """Vérifie si l’utilisateur possède toutes les portées requises.""" + return all(scope in user_scopes for scope in required_scopes) + +# Créer l’instance TodoService +todo_service = TodoService() + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """Créer une nouvelle tâche. Nécessite la portée 'create:todos'.""" + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # Seuls les utilisateurs avec la portée 'create:todos' peuvent créer des tâches + user_scopes = auth_info.scopes if auth_info else [] + if not has_required_scopes(user_scopes, ["create:todos"]): + raise MCPAuthBearerAuthException(BearerAuthExceptionCode.MISSING_REQUIRED_SCOPES) + + created_todo = todo_service.create_todo(content=content, owner_id=user_id) + return created_todo + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """ + Lister les tâches. Les utilisateurs avec la portée 'read:todos' peuvent voir toutes les tâches, + sinon ils ne voient que leurs propres tâches. + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # Si l’utilisateur a la portée 'read:todos', il peut accéder à toutes les tâches + # Sinon, il ne peut accéder qu’à ses propres tâches + user_scopes = auth_info.scopes if auth_info else [] + todo_owner_id = None if has_required_scopes(user_scopes, ["read:todos"]) else user_id + + todos = todo_service.get_all_todos(todo_owner_id) + return {"todos": todos} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """ + Supprimer une tâche par id. Les utilisateurs peuvent supprimer leurs propres tâches. + Les utilisateurs avec la portée 'delete:todos' peuvent supprimer n’importe quelle tâche. + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + todo = todo_service.get_todo_by_id(id) + + if not todo: + return {"error": "Failed to delete todo"} + + # Les utilisateurs ne peuvent supprimer que leurs propres tâches + # Les utilisateurs avec la portée 'delete:todos' peuvent supprimer n’importe quelle tâche + user_scopes = auth_info.scopes if auth_info else [] + if todo.owner_id != user_id and not has_required_scopes(user_scopes, ["delete:todos"]): + return {"error": "Failed to delete todo"} + + deleted_todo = todo_service.delete_todo(id) + + if deleted_todo: + return { + "message": f"Todo {id} deleted", + "details": deleted_todo + } + else: + return {"error": "Failed to delete todo"} +``` + + + +```js +// todo-manager.ts + +// autres imports... +import assert from 'node:assert'; +import { fetchServerConfig, MCPAuth, MCPAuthBearerAuthError } from 'mcp-auth'; +import { type AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js'; + +// Nous en parlerons dans la section suivante +import { TodoService } from './todo-service.js'; + +const assertUserId = (authInfo?: AuthInfo) => { + const { subject } = authInfo ?? {}; + assert(subject, 'Invalid auth info'); + return subject; +}; + +const hasRequiredScopes = (userScopes: string[], requiredScopes: string[]): boolean => { + return requiredScopes.every((scope) => userScopes.includes(scope)); +}; + +const todoService = new TodoService(); + +server.tool( + 'create-todo', + 'Créer une nouvelle tâche', + { content: z.string() }, + ({ content }: { content: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * Seuls les utilisateurs avec la portée 'create:todos' peuvent créer des tâches + */ + if (!hasRequiredScopes(authInfo?.scopes ?? [], ['create:todos'])) { + throw new MCPAuthBearerAuthError('missing_required_scopes'); + } + + const createdTodo = todoService.createTodo({ content, ownerId: userId }); + + return { + content: [{ type: 'text', text: JSON.stringify(createdTodo) }], + }; + } +); + +server.tool('get-todos', 'Lister toutes les tâches', ({ authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * Si l’utilisateur a la portée 'read:todos', il peut accéder à toutes les tâches (todoOwnerId = undefined) + * Sinon, il ne peut accéder qu’à ses propres tâches (todoOwnerId = userId) + */ + const todoOwnerId = hasRequiredScopes(authInfo?.scopes ?? [], ['read:todos']) + ? undefined + : userId; + + const todos = todoService.getAllTodos(todoOwnerId); + + return { + content: [{ type: 'text', text: JSON.stringify(todos) }], + }; +}); + +server.tool( + 'delete-todo', + 'Supprimer une tâche par id', + { id: z.string() }, + ({ id }: { id: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + const todo = todoService.getTodoById(id); + + if (!todo) { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Failed to delete todo' }) }], + }; + } + + /** + * Les utilisateurs ne peuvent supprimer que leurs propres tâches + * Les utilisateurs avec la portée 'delete:todos' peuvent supprimer n’importe quelle tâche + */ + if (todo.ownerId !== userId && !hasRequiredScopes(authInfo?.scopes ?? [], ['delete:todos'])) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ error: 'Failed to delete todo' }), + }, + ], + }; + } + + const deletedTodo = todoService.deleteTodo(id); + + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + message: `Todo ${id} deleted`, + details: deletedTodo, + }), + }, + ], + }; + } +); +``` + + + +Créez maintenant le "service Todo" utilisé dans le code ci-dessus pour implémenter la fonctionnalité associée : + + + + +Créez le fichier `service.py` pour le service Todo : + +```python +""" +Un service Todo simple à des fins de démonstration. +Utilise une liste en mémoire pour stocker les tâches. +""" + +from datetime import datetime +from typing import List, Optional, Dict, Any +import random +import string + +class Todo: + """Représente une tâche.""" + + def __init__(self, id: str, content: str, owner_id: str, created_at: str): + self.id = id + self.content = content + self.owner_id = owner_id + self.created_at = created_at + + def to_dict(self) -> Dict[str, Any]: + """Convertit la tâche en dictionnaire pour la sérialisation JSON.""" + return { + "id": self.id, + "content": self.content, + "ownerId": self.owner_id, + "createdAt": self.created_at + } + + +class TodoService: + """Un service Todo simple à des fins de démonstration.""" + + def __init__(self): + self._todos: List[Todo] = [] + + def get_all_todos(self, owner_id: Optional[str] = None) -> List[Dict[str, Any]]: + """ + Récupère toutes les tâches, éventuellement filtrées par owner_id. + + Args: + owner_id: Si fourni, ne retourne que les tâches appartenant à cet utilisateur + + Returns: + Liste de dictionnaires de tâches + """ + if owner_id: + filtered_todos = [todo for todo in self._todos if todo.owner_id == owner_id] + return [todo.to_dict() for todo in filtered_todos] + return [todo.to_dict() for todo in self._todos] + + def get_todo_by_id(self, todo_id: str) -> Optional[Todo]: + """ + Récupère une tâche par son ID. + + Args: + todo_id: L’ID de la tâche à récupérer + + Returns: + Objet Todo si trouvé, None sinon + """ + for todo in self._todos: + if todo.id == todo_id: + return todo + return None + + def create_todo(self, content: str, owner_id: str) -> Dict[str, Any]: + """ + Crée une nouvelle tâche. + + Args: + content: Le contenu de la tâche + owner_id: L’ID de l’utilisateur propriétaire de cette tâche + + Returns: + Dictionnaire représentant la tâche créée + """ + todo = Todo( + id=self._generate_id(), + content=content, + owner_id=owner_id, + created_at=datetime.now().isoformat() + ) + self._todos.append(todo) + return todo.to_dict() + + def delete_todo(self, todo_id: str) -> Optional[Dict[str, Any]]: + """ + Supprime une tâche par son ID. + + Args: + todo_id: L’ID de la tâche à supprimer + + Returns: + Dictionnaire représentant la tâche supprimée si trouvée, None sinon + """ + for i, todo in enumerate(self._todos): + if todo.id == todo_id: + deleted_todo = self._todos.pop(i) + return deleted_todo.to_dict() + return None + + def _generate_id(self) -> str: + """Génère un ID aléatoire pour une tâche.""" + return ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)) +``` + + + + +Créez le fichier `todo-service.ts` pour le service Todo : + +```ts +// todo-service.ts + +type Todo = { + id: string; + content: string; + ownerId: string; + createdAt: string; +}; + +/** + * Un service Todo simple à des fins de démonstration. + * Utilise un tableau en mémoire pour stocker les tâches + */ +export class TodoService { + private readonly todos: Todo[] = []; + + getAllTodos(ownerId?: string): Todo[] { + if (ownerId) { + return this.todos.filter((todo) => todo.ownerId === ownerId); + } + return this.todos; + } + + getTodoById(id: string): Todo | undefined { + return this.todos.find((todo) => todo.id === id); + } + + createTodo({ content, ownerId }: { content: string; ownerId: string }): Todo { + const todo: Todo = { + id: this.genId(), + content, + ownerId, + createdAt: new Date().toISOString(), + }; + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + this.todos.push(todo); + return todo; + } + + deleteTodo(id: string): Todo | undefined { + const index = this.todos.findIndex((todo) => todo.id === id); + + if (index === -1) { + return undefined; + } + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + const [deleted] = this.todos.splice(index, 1); + return deleted; + } + + private genId(): string { + return Math.random().toString(36).slice(2, 10); + } +} +``` + + + + +🎉 Félicitations ! Nous avons implémenté avec succès un serveur MCP complet avec authentification et autorisation ! + +Vous pouvez également consulter notre code d’exemple pour référence : + + + + +:::info +Consultez le [dépôt du SDK MCP Auth Python](https://github.com/mcp-auth/python/tree/master/samples/current/todo-manager) pour le code complet du serveur MCP (version OIDC). +::: + + + + +:::info +Consultez le [dépôt du SDK MCP Auth Node.js](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) pour le code complet du serveur MCP (version OIDC). +::: + + + + +## Point de contrôle : Exécuter les outils `todo-manager` \{#checkpoint-run-the-todo-manager-tools} + +Redémarrez votre serveur MCP et ouvrez le MCP inspector dans votre navigateur. Lorsque vous cliquez sur le bouton "Connect", vous devriez être redirigé vers la page de connexion de votre serveur d’autorisation. + +Une fois connecté et de retour dans le MCP inspector, répétez les actions du point de contrôle précédent pour exécuter les outils du gestionnaire de tâches. Cette fois, vous pouvez utiliser ces outils avec votre identité utilisateur authentifiée. Le comportement des outils dépendra des rôles et permissions attribués à votre utilisateur : + +- Si vous êtes connecté en tant que **User** (avec uniquement la portée `create:todos`) : + + - Vous pouvez créer de nouvelles tâches avec l’outil `create-todo` + - Vous ne pouvez voir et supprimer que vos propres tâches + - Vous ne pourrez pas voir ou supprimer les tâches des autres utilisateurs + +- Si vous êtes connecté en tant qu’**Admin** (avec toutes les portées : `create:todos`, `read:todos`, `delete:todos`) : + - Vous pouvez créer de nouvelles tâches + - Vous pouvez voir toutes les tâches du système avec l’outil `get-todos` + - Vous pouvez supprimer n’importe quelle tâche avec l’outil `delete-todo`, quel que soit le créateur + +Vous pouvez tester ces différents niveaux de permission en : + +1. Vous déconnectant de la session en cours (cliquez sur le bouton "Disconnect" dans MCP inspector) +2. Vous connectant avec un autre compte utilisateur ayant des rôles/permissions différents +3. Essayant à nouveau les mêmes outils pour observer comment le comportement change selon les permissions de l’utilisateur + +Cela démontre comment le contrôle d’accès basé sur les rôles (RBAC) fonctionne en pratique, où différents utilisateurs ont différents niveaux d’accès aux fonctionnalités du système. + +![Résultat de l’outil gestionnaire de tâches dans MCP inspector](/docs-assets/images/tutorials/todo-manager/result.png) + + + + +:::info +Consultez le [dépôt du SDK MCP Auth Python](https://github.com/mcp-auth/python) pour le code complet du serveur MCP (version OIDC). +::: + + + + +:::info +Consultez le [dépôt du SDK MCP Auth Node.js](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) pour le code complet du serveur MCP (version OIDC). +::: + + + + +## Notes de clôture \{#closing-notes} + +🎊 Félicitations ! Vous avez terminé avec succès le tutoriel. Récapitulons ce que nous avons fait : + +- Mise en place d’un serveur MCP de base avec des outils de gestion de tâches (`create-todo`, `get-todos`, `delete-todo`) +- Implémentation du contrôle d’accès basé sur les rôles (RBAC) avec différents niveaux de permissions pour les utilisateurs et les admins +- Intégration du serveur MCP avec un serveur d’autorisation à l’aide de MCP Auth +- Configuration du MCP Inspector pour authentifier les utilisateurs et utiliser des jetons d’accès avec des portées pour appeler les outils + +N’hésitez pas à consulter d’autres tutoriels et la documentation pour tirer le meilleur parti de MCP Auth. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/README.mdx b/i18n/ja/docusaurus-plugin-content-docs/current/README.mdx new file mode 100644 index 0000000..74438af --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/README.mdx @@ -0,0 +1,297 @@ +--- +sidebar_position: 1 +sidebar_label: はじめに +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# はじめに + +:::info MCP 認可 (Authorization) 仕様サポート +このバージョンは [MCP 認可 (Authorization) 仕様 (バージョン 2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) をサポートしています。 +::: + + +## 互換性のある OAuth 2.1 または OpenID Connect プロバイダーを選択する \{#choose-a-compatible-oauth-2-1-or-openid-connect-provider} + +MCP 仕様は、認可 (Authorization) に関して [特定の要件](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#standards-compliance) があります。認可 (Authorization) メカニズムは確立された仕様に基づいており、セキュリティと相互運用性を確保しつつシンプルさを維持するために、機能の一部のみを実装しています: + +- OAuth 2.1 IETF DRAFT ([draft-ietf-oauth-v2-1-13](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13)) +- OAuth 2.0 Authorization Server Metadata ([RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)) +- OAuth 2.0 Dynamic Client Registration Protocol ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) +- OAuth 2.0 Protected Resource Metadata ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)) + +これらの仕様は連携して、MCP 実装のための安全で標準化された認可 (Authorization) フレームワークを提供します。 + +[互換性のある MCP プロバイダー一覧](/provider-list) で、プロバイダーがサポートされているか確認できます。 + +## MCP Auth SDK をインストールする \{#install-mcp-auth-sdk} + +MCP Auth は Python と TypeScript の両方で利用できます。他の言語やフレームワークのサポートが必要な場合はお知らせください! + + + + +```bash +pip install mcpauth +``` + +または、pipenv や poetry などお好みのパッケージマネージャーを利用できます。 + + + + +```bash +npm install mcp-auth +``` + +または、pnpm や yarn などお好みのパッケージマネージャーを利用できます。 + + + + +## MCP Auth を初期化する \{#init-mcp-auth} + +最初のステップは、リソース識別子を定義し、認証 (Authentication) 用に信頼する認可 (Authorization) サーバーを設定することです。MCP Auth は現在リソースサーバーモードで動作し、OAuth 2.0 Protected Resource Metadata (RFC 9728) を要求する最新の MCP 仕様に準拠しています。 + +プロバイダーが以下に準拠している場合: + +- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +組み込み関数を使ってメタデータを取得し、MCP Auth インスタンスを初期化できます: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType, ResourceServerConfig, ResourceServerMetadata +from mcpauth.utils import fetch_server_config + +# 1. リソース識別子を定義し、信頼する認可 (Authorization) サーバーの設定を取得します。 +resource_id = "https://api.example.com/notes" +auth_server_config = fetch_server_config("https://auth.logto.io/oidc", AuthServerType.OIDC) + +# 2. リソースサーバーモードで MCPAuth を初期化します。 +# `protected_resources` は単一オブジェクトまたは複数リソース用のリストにできます。 +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +// 1. リソース識別子を定義し、信頼する認可 (Authorization) サーバーの設定を取得します。 +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +// 2. リソースサーバーモードで MCPAuth を初期化します。 +// `protectedResources` は単一オブジェクトまたは複数リソース用の配列にできます。 +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +カスタムメタデータ URL、データ変換、手動メタデータ指定など、他の認可 (Authorization) サーバーメタデータ設定方法については [MCP Auth の他の設定方法](./configure-server/mcp-auth.mdx#other-ways) をご覧ください。 + +## 保護されたリソースメタデータエンドポイントをマウントする \{#mount-the-protected-resource-metadata-endpoint} + +最新の MCP 仕様に準拠するため、MCP Auth は OAuth 2.0 Protected Resource Metadata エンドポイント (RFC 9728) を MCP サーバーにマウントします。このエンドポイントによりクライアントは以下を発見できます: + +- 保護されたリソースに対して有効なトークンを発行できる認可 (Authorization) サーバー +- 各リソースでサポートされるスコープ +- 適切なトークン検証に必要なその他のメタデータ + +エンドポイントのパスはリソース識別子のパスコンポーネントによって自動的に決まります: + +- **パスなし**: `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **パスあり**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + +MCP サーバーは **リソースサーバー** としてトークンを検証し、保護されたリソースのメタデータを提供します。認証 (Authentication) と認可 (Authorization) はすべて外部の認可 (Authorization) サーバーに依存します。 + +SDK の提供するメソッドでこのエンドポイントをマウントできます: + + + + +```python +from starlette.applications import Starlette + +# Protected Resource Metadata を提供するルーターをマウントします。 +# リソース "https://api.example.com" → エンドポイント: /.well-known/oauth-protected-resource +# リソース "https://api.example.com/notes" → エンドポイント: /.well-known/oauth-protected-resource/notes +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// Protected Resource Metadata を提供するルーターをマウントします。 +// リソース "https://api.example.com" → エンドポイント: /.well-known/oauth-protected-resource +// リソース "https://api.example.com/notes" → エンドポイント: /.well-known/oauth-protected-resource/notes +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + + +## Bearer 認証 (Authentication) ミドルウェアを利用する \{#use-the-bearer-auth-middleware} + +MCP Auth インスタンスを初期化したら、Bearer 認証 (Authentication) ミドルウェアを適用して MCP ルートを保護できます。ミドルウェアは、どのリソースに属するエンドポイントかを指定する必要があり、適切なトークン検証が可能になります: + +:::note オーディエンス (Audience) 検証 +`audience` パラメーターは安全なトークン検証のために OAuth 2.0 仕様で **必須** です。ただし、リソース識別子をまだサポートしていない認可 (Authorization) サーバーとの互換性維持のため、現在は **オプション** です。セキュリティのため、**可能な限り audience パラメーターを必ず含めてください**。将来のバージョンでは audience 検証が必須となり、仕様に完全準拠します。 +::: + + + + +```python +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount + +# リソース固有ポリシーで MCP サーバーを保護するミドルウェアを作成します。 +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', + resource=resource_id, + audience=resource_id, # セキュリティのため audience 検証を有効化 + required_scopes=['read:notes'] +)) + +# Protected Resource Metadata を提供し、MCP サーバーを保護するルーターをマウントします。 +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # Bearer 認証 (Authentication) ミドルウェアで MCP サーバーを保護 + Mount("/", app=mcp.sse_app(), middleware=[bearer_auth]), + ], +) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// Protected Resource Metadata を提供するルーターをマウント +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// リソース固有ポリシーで API エンドポイントを保護 +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, // セキュリティのため audience 検証を有効化 + requiredScopes: ['read:notes'], + }), + (req, res) => { + // トークンが有効な場合、`req.auth` にクレーム (Claims) 情報が格納されます。 + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); + +app.listen(3000); +``` + + + + +上記の例では、`jwt` トークンタイプとリソース識別子を指定しています。ミドルウェアは、そのリソース用に設定された信頼できる認可 (Authorization) サーバーに対して JWT トークンを自動的に検証し、認証 (Authentication) 済みユーザー情報を格納します。 + +:::info +JWT (JSON Web Token) について聞いたことがない場合もご安心ください。ドキュメントを読み進めていただければ、必要なタイミングで説明します。簡単な紹介は [Auth Wiki](https://auth.wiki/jwt) もご覧ください。 +::: + +Bearer 認証 (Authentication) 設定の詳細は [Bearer 認証 (Authentication) の設定](./configure-server/bearer-auth.mdx) をご覧ください。 + +## MCP 実装で認証 (Authentication) 情報を取得する \{#retrieve-the-auth-info-in-your-mcp-implementation} + +Bearer 認証 (Authentication) ミドルウェアを適用すると、MCP 実装内で認証 (Authentication) 済みユーザー(またはアイデンティティ)の情報にアクセスできます: + + + + +Bearer 認証 (Authentication) ミドルウェアが適用されると、MCP Auth は認証 (Authentication) 済みユーザー情報をコンテキスト変数に保存します。MCP ツールハンドラー内で次のようにアクセスできます: + +```python +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP() + +# これまでの例のように MCP Auth で初期化 +# ... + +@mcp.tool() +def add(a: int, b: int): + """ + 2 つの数値を加算するツールです。 + 認証 (Authentication) 済みユーザー情報はコンテキストで利用可能です。 + """ + auth_info = mcp_auth.auth_info # 現在のコンテキストで認証 (Authentication) 情報にアクセス + if auth_info: + print(f"Authenticated user: {auth_info.claims}") + return a + b +``` + + + + +ツールハンドラーの第 2 引数に `authInfo` オブジェクトが含まれ、認証 (Authentication) 済みユーザー情報が利用できます: + +```ts +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { z } from 'zod'; + +const server = new McpServer(/* ... */); + +// これまでの例のように MCP Auth で初期化 +// ... + +server.tool('add', { a: z.number(), b: z.number() }, async ({ a, b }, { authInfo }) => { + // `authInfo` オブジェクトで認証 (Authentication) 情報にアクセスできます +}); +``` + + + + +## 次のステップ \{#next-steps} + +この後は、MCP Auth を MCP サーバーに統合するエンドツーエンドの例や、MCP クライアントでの認証 (Authentication) フローの扱い方について学んでいきましょう。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx b/i18n/ja/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx new file mode 100644 index 0000000..2efef3a --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx @@ -0,0 +1,280 @@ +--- +sidebar_position: 2 +sidebar_label: Bearer 認証 +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# MCP サーバーでの Bearer 認証の設定 + +最新の MCP 仕様では、MCP サーバーは保護されたリソースのための **リソースサーバー (Resource Server)** として動作し、アクセス トークンの検証を行います。MCP Auth では、Bearer 認可 (Authorization) を設定するためのさまざまな方法が提供されています: + +- [JWT (JSON Web Token)](https://auth.wiki/jwt) モード:クレーム (Claim) アサーションによって JWT を検証する組み込みの認可 (Authorization) 方法。 +- カスタムモード:独自の認可 (Authorization) ロジックを実装できます。 + +Bearer 認証 (Authentication) ミドルウェアでは、エンドポイントがどのリソースに属するかを指定する必要があり、設定された認可 (Authorization) サーバーに対して適切なトークン検証が可能になります。 + +## JWT モードでの Bearer 認証 (Authentication) 設定 \{#configure-bearer-auth-with-jwt-mode} + +OAuth / OIDC プロバイダーが認可 (Authorization) のために JWT を発行する場合、MCP Auth の組み込み JWT モードを利用できます。JWT の署名、有効期限、指定したその他のクレーム (Claim) を検証し、認証 (Authentication) 情報をリクエストコンテキストに格納して MCP 実装で利用できるようにします。 + +### スコープ (Scope) 検証 \{#scope-validation} + +基本的なスコープ (Scope) 検証の例です: + + + + +```python +from mcpauth import MCPAuth +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP("MyMCPServer") +mcp_auth = MCPAuth( + # Initialize with your auth server config +) +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", # このエンドポイントが属するリソースを指定 + audience="https://api.example.com", # セキュリティのためオーディエンス (Audience) 検証を有効化 + required_scopes=["read", "write"] # [!code highlight] +) + +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + /* ... */ +}); +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // このエンドポイントが属するリソースを指定 + audience: 'https://api.example.com', // セキュリティのためオーディエンス (Audience) 検証を有効化 + requiredScopes: ['read', 'write'] // [!code highlight] +}); + +app.use('/mcp', bearerAuth, (req, res) => { + // `req.auth` に認証 (Authentication) 情報が格納されます + console.log(req.auth); +}); +``` + + + + +上記の例では、JWT に `read` および `write` スコープ (Scope) が必要であることを指定しています。JWT にこれらのスコープ (Scope) の **いずれか** が含まれていない場合、リクエストは 403 Forbidden エラーで拒否されます。 + +### オーディエンス (Audience) 検証(RFC 8707) \{#audience-validation-rfc-8707} + +セキュアなトークン検証のため、`audience` パラメーターを指定して常にオーディエンス (Audience) 検証を有効にしてください。これは JWT の `aud`(オーディエンス (Audience))クレーム (Claim) を検証し、そのトークンが MCP サーバーリソース用に発行されたことを確認します。 + +:::note Audience Validation +`audience` パラメーターは、セキュアなトークン検証のため OAuth 2.0 仕様で **必須** です。ただし、リソースインジケーター (Resource indicator) をまだサポートしていない認可 (Authorization) サーバーとの互換性維持のため、現時点では **オプション** となっています。セキュリティ上の理由から、**可能な限り audience パラメーターを必ず指定してください**。今後のバージョンでは、仕様に完全準拠するため audience 検証が必須となります。 +::: + +audience の値は通常、リソース識別子と一致させます: + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", # このエンドポイントが属するリソースを指定 + audience="https://api.example.com", # セキュリティのためオーディエンス (Audience) 検証を有効化 [!code highlight] + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // このエンドポイントが属するリソースを指定 + audience: 'https://api.example.com', // セキュリティのためオーディエンス (Audience) 検証を有効化 [!code highlight] + requiredScopes: ['read', 'write'], +}); +``` + + + + +上記の例では、MCP Auth は JWT の `aud` クレーム (Claim) と必要なスコープ (Scope) の **両方** を検証します。 + +### JWT 検証へのカスタムオプションの指定 \{#provide-custom-options-to-the-jwt-verification} + +JWT 検証ライブラリにカスタムオプションを指定することもできます: + + + + +Python SDK では、JWT 検証に [PyJWT](https://pyjwt.readthedocs.io/en/stable/) を使用しています。次のオプションが利用可能です: + +- `leeway`: JWT の有効期限検証時に許容する猶予時間(秒単位)。デフォルトは 60 秒です。 + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", + audience="https://api.example.com", + required_scopes=["read", "write"], + leeway=10, # 10 秒の猶予でクロックスキューを緩和 [!code highlight] +) +``` + + + + +Node.js SDK では、JWT 検証に [jose](https://github.com/panva/jose) ライブラリを使用しています。次のオプションが利用可能です: + +- `jwtVerify`: JWT 検証プロセス用のオプション(`jose` の `jwtVerify` 関数)。 +- `remoteJwtSet`: リモート JWT セット取得用のオプション(`jose` の `createRemoteJWKSet` 関数)。 + +```ts {5-10} +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', + requiredScopes: ['read', 'write'], + jwtVerify: { + clockTolerance: 60, // 60 秒のクロックスキューを許容 + }, + remoteJwtSet: { + timeoutDuration: 10 * 1000, // リモート JWT セット取得のタイムアウト 10 秒 + }, +}); +``` + + + + +## カスタム検証による Bearer 認証 (Authentication) の設定 \{#configure-bearer-auth-with-custom-verification} + +OAuth / OIDC プロバイダーが JWT を発行しない場合や、独自の認可 (Authorization) ロジックを実装したい場合、MCP Auth ではカスタム検証関数を作成できます: + +:::info +Bearer 認証 (Authentication) ミドルウェアは、発行者(`iss`)、オーディエンス(`aud`)、必要なスコープ(`scope`)を検証結果と照合します。そのため、これらのチェックをカスタム検証関数で実装する必要はありません。トークンの有効性(署名、有効期限など)の検証と認証 (Authentication) 情報オブジェクトの返却に集中できます。 +::: + + + + +```python +from mcpauth.exceptions import MCPAuthJwtVerificationException, MCPAuthJwtVerificationExceptionCode +from mcpauth.types import AuthInfo + +async def custom_verification(token: str) -> AuthInfo: + # ここにカスタム検証ロジックを実装 + info = await verify_token(token) + if not info: + raise MCPAuthJwtVerificationException( + MCPAuthJwtVerificationExceptionCode.JWT_VERIFICATION_FAILED + ) + return info # 認証 (Authentication) 情報オブジェクトを返却 + +bearer_auth = mcp_auth.bearer_auth_middleware( + custom_verification, + resource="https://api.example.com", + audience="https://api.example.com", # セキュリティのためオーディエンス (Audience) 検証を有効化 + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth( + async (token) => { + // ここにカスタム検証ロジックを実装 + const info = await verifyToken(token); + if (!info) { + throw new MCPAuthJwtVerificationError('jwt_verification_failed'); + } + return info; // 認証 (Authentication) 情報オブジェクトを返却 + }, + { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // セキュリティのためオーディエンス (Audience) 検証を有効化 + requiredScopes: ['read', 'write'] + } +); +``` + + + + +## MCP サーバーでの Bearer 認証 (Authentication) の適用 \{#apply-bearer-auth-in-your-mcp-server} + +MCP サーバーを Bearer 認証 (Authentication) で保護するには、MCP サーバーインスタンスに Bearer 認証 (Authentication) ミドルウェアを適用します。 + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", + audience="https://api.example.com", # セキュリティのためオーディエンス (Audience) 検証を有効化 + required_scopes=["read", "write"] +) +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```js +const app = express(); +app.use(mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // セキュリティのためオーディエンス (Audience) 検証を有効化 + requiredScopes: ['read', 'write'] +})); +``` + + + + +これにより、すべての受信リクエストが設定された Bearer 認証 (Authentication) 設定に従って認証 (Authentication) および認可 (Authorization) され、認証 (Authentication) 情報がリクエストコンテキストで利用可能になります。 + +MCP サーバー実装内で情報を参照できます: + + + + +```python +@mcp.tool() +async def whoami() -> dict: + # `mcp_auth.auth_info` は現在のリクエストのコンテキストオブジェクト + auth_info = mcp_auth.auth_info + print(f"Authenticated user: {auth_info.subject}") + return {"subject": auth_info.subject} +``` + + + + +```js +// `authInfo` は `req.auth` オブジェクトから渡されます +server.tool('whoami', ({ authInfo }) => { + console.log(`Authenticated user: ${authInfo.subject}`); + return { subject: authInfo.subject }; +}); +``` + + + diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx b/i18n/ja/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx new file mode 100644 index 0000000..57a51a7 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx @@ -0,0 +1,290 @@ +--- +sidebar_position: 1 +sidebar_label: MCP Auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# MCP サーバーでの MCP Auth 設定 + +最新の [MCP 仕様 (2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18) では、MCP サーバーは外部認可サーバーによって発行されたアクセス トークン (Access token) を検証する **リソースサーバー (Resource Server)** として動作します。 + +MCP Auth を設定するには、主に 2 つのステップが必要です: +1. **認可サーバーメタデータの設定** - どの認可サーバーが MCP サーバー用の有効なトークンを発行できるかを定義し、MCP クライアントにアクセス トークン (Access token) の取得先を案内します +2. **保護リソースメタデータの設定** - MCP サーバーをサポートするスコープ付きの保護リソースとして定義します + +## ステップ 1: 認可サーバーメタデータの設定 \{#configure-authorization-server-metadata} + +### メタデータの自動取得 \{#automatic-metadata-fetching} + +認可サーバーメタデータを設定する最も簡単な方法は、well-known URL からメタデータを取得する組み込み関数を利用することです。プロバイダーが次のいずれかの標準に準拠している場合: + +- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +`fetchServerConfig` を使い、`issuer` URL を指定することで自動的にメタデータを取得できます: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +# 認可サーバーメタデータの取得 +auth_server_config = fetch_server_config( + "https://auth.logto.io/oidc", + AuthServerType.OIDC # または AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +// 認可サーバーメタデータの取得 +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); // または 'oauth' +``` + + + + +issuer にパスが含まれている場合、OAuth 2.0 と OpenID Connect で挙動が少し異なります: + +- **OAuth 2.0**:well-known URL は issuer の **ドメイン** に追加されます。例:issuer が `https://my-project.logto.app/oauth` の場合、well-known URL は `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` となります。 +- **OpenID Connect**:well-known URL は **issuer** に直接追加されます。例:issuer が `https://my-project.logto.app/oidc` の場合、well-known URL は `https://auth.logto.io/oidc/.well-known/openid-configuration` となります。 + +### その他の認可サーバーメタデータ設定方法 \{#other-ways} + +#### カスタムデータ変換 \{#custom-data-transpilation} + +場合によっては、プロバイダーから返されるメタデータが期待される形式に準拠していないことがあります。プロバイダーが準拠していると確信できる場合は、`transpile_data` オプションを使ってメタデータを使用前に変更できます: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +auth_server_config = fetch_server_config( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfig('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +これにより、MCP Auth で使用する前にメタデータオブジェクトを変更できます。たとえば、フィールドの追加や削除、値の変更、別の形式への変換などが可能です。 + +#### 特定の URL からメタデータを取得 \{#fetch-metadata-from-a-specific-url} + +プロバイダーが標準以外の特定のメタデータ URL を持つ場合も、同様に利用できます: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC # または AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfigByWellKnownUrl } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { type: 'oidc' }); // または 'oauth' +``` + + + + +#### 特定の URL からカスタムデータ変換付きでメタデータを取得 \{#fetch-metadata-from-a-specific-url-with-custom-data-transpilation} + +場合によっては、プロバイダーのレスポンスが不正または期待されるメタデータ形式に準拠していないことがあります。プロバイダーが準拠していると確信できる場合は、設定オプションでメタデータを変換できます: + + + + +```python +from mcpauth.config import AuthServerType, fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +#### メタデータを手動で指定 \{#manually-provide-metadata} + +プロバイダーがメタデータの取得をサポートしていない場合は、メタデータオブジェクトを手動で指定できます: + + + + +```python +from mcpauth.config import AuthServerConfig, AuthServerType, AuthorizationServerMetadata + +auth_server_config = AuthServerConfig( + type=AuthServerType.OIDC, # または AuthServerType.OAUTH + metadata=AuthorizationServerMetadata( + issuer='', + authorization_endpoint='', + # ... 他のメタデータフィールド + ), +) +``` + + + + +```ts +const authServerConfig = { + metadata: { + issuer: '', + // メタデータフィールドは camelCase で記述 + authorizationEndpoint: '', + // ... 他のメタデータフィールド + }, + type: 'oidc', // または 'oauth' +}; +``` + + + + +## ステップ 2: 保護リソースメタデータの設定 \{#configure-protected-resource-metadata} + +認可サーバーメタデータの設定後、保護リソースメタデータを定義して MCPAuth をリソースサーバーとして初期化します。 + +このステップでは、[RFC 9728 (OAuth 2.0 Protected Resource Metadata)](https://datatracker.ietf.org/doc/html/rfc9728) 仕様に従い、MCP サーバーを保護リソースとして記述します: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import ResourceServerConfig, ResourceServerMetadata + +# リソース識別子の定義 +resource_id = "https://api.example.com/notes" + +# リソースサーバーモードで MCPAuth を初期化 +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], # ステップ 1 で取得した config を利用 + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth } from 'mcp-auth'; + +// リソース識別子の定義 +const resourceIdentifier = 'https://api.example.com/notes'; + +// リソースサーバーモードで MCPAuth を初期化 +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], // ステップ 1 で取得した config を利用 + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +複数のリソースがある場合は、それぞれのメタデータ設定を持つ保護リソースの配列を指定できます。 + +上記の設定は基本的なセットアップをカバーしています。より高度なメタデータパラメーターについては [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata) を参照してください。 + +## ステップ 3: 保護リソースメタデータエンドポイントのマウント \{#mount-the-protected-resource-metadata-endpoint} + +ルーターをマウントして保護リソースメタデータエンドポイントを提供します。エンドポイントパスはリソース識別子のパスコンポーネントによって自動的に決定されます: + +- **パスなし**:`https://api.example.com` → `/.well-known/oauth-protected-resource` +- **パスあり**:`https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + + + + +```python +from starlette.applications import Starlette +from mcpauth import MCPAuth + +mcp_auth = MCPAuth({/* ... */}) + +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +const mcpAuth = new MCPAuth({/* ... */}); + +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/README.md new file mode 100644 index 0000000..2051515 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/README.md @@ -0,0 +1,59 @@ +--- +sidebar_label: Node.js SDK +--- + +# MCP Auth Node.js SDK リファレンス + +## クラス {#classes} + +- [MCPAuth](/references/js/classes/MCPAuth.md) +- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) +- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) +- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) +- [MCPAuthError](/references/js/classes/MCPAuthError.md) +- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) + +## 型エイリアス {#type-aliases} + +- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) +- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) +- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) +- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) +- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) +- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) +- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) +- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) +- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) +- [AuthServerType](/references/js/type-aliases/AuthServerType.md) +- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) +- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) +- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) +- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) +- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) +- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) +- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) +- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) +- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) +- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) +- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) +- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) + +## 変数 {#variables} + +- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) +- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) +- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) +- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) +- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) +- [defaultValues](/references/js/variables/defaultValues.md) +- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) +- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) +- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) +- [validateServerConfig](/references/js/variables/validateServerConfig.md) + +## 関数 {#functions} + +- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) +- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) +- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) +- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md new file mode 100644 index 0000000..91b2eb4 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md @@ -0,0 +1,281 @@ +--- +sidebar_label: MCPAuth +--- + +# クラス: MCPAuth + +mcp-auth ライブラリのメインクラスです。保護されたリソースのための認証 (Authentication) ポリシーを作成するためのファクトリーおよびレジストリとして機能します。 + +サーバー構成で初期化され、トークンベースの認証 (Authentication) 用の Express ミドルウェアを生成する `bearerAuth` メソッドを提供します。 + +## 例 {#example} + +### `resource server` モードでの利用例 {#usage-in-resource-server-mode} + +新しいアプリケーションにはこの方法が推奨されます。 + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); + +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +const mcpAuth = new MCPAuth({ + // `protectedResources` は単一の構成オブジェクトまたはその配列を指定できます。 + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); + +// 保護されたリソースメタデータを処理するルーターをマウント +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// 設定したリソース用の API エンドポイントを保護 +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, // このエンドポイントが属するリソースを指定 + audience: resourceIdentifier, // 任意で 'aud' クレームを検証 + requiredScopes: ['read:notes'], + }), + (req, res) => { + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); +``` + +### `authorization server` モードでのレガシー利用例(非推奨) {#legacy-usage-in-authorization-server-mode-deprecated} + +後方互換性のためにサポートされています。 + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + server: await fetchServerConfig( + 'https://auth.logto.io/oidc', + { type: 'oidc' } + ), +}); + +// レガシー認可サーバーメタデータを処理するルーターをマウント +app.use(mcpAuth.delegatedRouter()); + +// デフォルトポリシーでエンドポイントを保護 +app.get( + '/mcp', + mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), + (req, res) => { + console.log('Auth info:', req.auth); + // ここで MCP リクエストを処理 + }, +); +``` + +## コンストラクター {#constructors} + +### コンストラクター {#constructor} + +```ts +new MCPAuth(config: MCPAuthConfig): MCPAuth; +``` + +MCPAuth のインスタンスを作成します。 +エラー時にすぐ失敗するよう、全体の構成を事前に検証します。 + +#### パラメーター {#parameters} + +##### config {#config} + +[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) + +認証 (Authentication) 構成。 + +#### 戻り値 {#returns} + +`MCPAuth` + +## プロパティ {#properties} + +### config {#config} + +```ts +readonly config: MCPAuthConfig; +``` + +認証 (Authentication) 構成。 + +## メソッド {#methods} + +### bearerAuth() {#bearerauth} + +#### 呼び出しシグネチャ {#call-signature} + +```ts +bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; +``` + +リクエストの `Authorization` ヘッダー内の アクセス トークン (Access token) を検証する Bearer 認証 (Authentication) ハンドラー(Express ミドルウェア)を作成します。 + +##### パラメーター {#parameters} + +###### verifyAccessToken {#verifyaccesstoken} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +アクセス トークン (Access token) を検証する関数です。文字列として アクセス トークン (Access token) を受け取り、検証結果に解決される promise(または値)を返す必要があります。 + +**参照** + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) で `verifyAccessToken` 関数の型定義を確認できます。 + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> + +Bearer 認証 (Authentication) ハンドラーのためのオプション構成。 + +**参照** + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) で利用可能な構成オプション(`verifyAccessToken` と `issuer` を除く)を確認できます。 + +##### 戻り値 {#returns} + +`RequestHandler` + +アクセス トークン (Access token) を検証し、検証結果をリクエストオブジェクト(`req.auth`)に追加する Express ミドルウェア関数。 + +##### 参照 {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) で実装詳細および `req.auth`(`AuthInfo`)オブジェクトの拡張型を確認できます。 + +#### 呼び出しシグネチャ {#call-signature} + +```ts +bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; +``` + +事前定義された検証モードを使用して、リクエストの `Authorization` ヘッダー内の アクセス トークン (Access token) を検証する Bearer 認証 (Authentication) ハンドラー(Express ミドルウェア)を作成します。 + +`'jwt'` モードでは、認可サーバーの JWKS URI から JWK Set を使って JWT 検証関数を作成します。 + +##### パラメーター {#parameters} + +###### mode {#mode} + +`"jwt"` + +アクセス トークン (Access token) の検証モード。現在は 'jwt' のみサポートされています。 + +**参照** + +[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) で利用可能なモードを確認できます。 + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` + +JWT 検証オプションやリモート JWK Set オプションを含む、Bearer 認証 (Authentication) ハンドラーのためのオプション構成。 + +**参照** + + - VerifyJwtConfig で JWT 検証のための構成オプションを確認できます。 + - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) で利用可能な構成オプション(`verifyAccessToken` と `issuer` を除く)を確認できます。 + +##### 戻り値 {#returns} + +`RequestHandler` + +アクセス トークン (Access token) を検証し、検証結果をリクエストオブジェクト(`req.auth`)に追加する Express ミドルウェア関数。 + +##### 参照 {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) で実装詳細および `req.auth`(`AuthInfo`)オブジェクトの拡張型を確認できます。 + +##### 例外 {#throws} + +`'jwt'` モード使用時にサーバーメタデータに JWKS URI が指定されていない場合にスローされます。 + +*** + +### ~~delegatedRouter()~~ {#delegatedrouter} + +```ts +delegatedRouter(): Router; +``` + +インスタンスに提供されたメタデータで、レガシー OAuth 2.0 認可サーバーメタデータエンドポイント +(`/.well-known/oauth-authorization-server`)を提供するための委譲ルーターを作成します。 + +#### 戻り値 {#returns} + +`Router` + +インスタンスに提供されたメタデータで OAuth 2.0 認可サーバーメタデータエンドポイントを提供するルーター。 + +#### 非推奨 {#deprecated} + +代わりに [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) を使用してください。 + +#### 例 {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth: MCPAuth; // 初期化済みと仮定 +app.use(mcpAuth.delegatedRouter()); +``` + +#### 例外 {#throws} + +`resource server` モードで呼び出された場合にスローされます。 + +*** + +### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} + +```ts +protectedResourceMetadataRouter(): Router; +``` + +設定されたすべてのリソースに対して OAuth 2.0 保護リソースメタデータエンドポイントを提供するルーターを作成します。 + +このルーターは、構成で指定された各リソース識別子に対して正しい `.well-known` エンドポイントを自動的に作成します。 + +#### 戻り値 {#returns} + +`Router` + +OAuth 2.0 保護リソースメタデータエンドポイントを提供するルーター。 + +#### 例外 {#throws} + +`authorization server` モードで呼び出された場合にスローされます。 + +#### 例 {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +// mcpAuth が 1 つ以上の `protectedResources` 構成で初期化されていると仮定 +const mcpAuth: MCPAuth; +const app = express(); + +// 構成したリソース識別子に基づき、`/.well-known/oauth-protected-resource/...` でメタデータを提供 +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md new file mode 100644 index 0000000..bef1792 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md @@ -0,0 +1,238 @@ +--- +sidebar_label: MCPAuthAuthServerError +--- + +# クラス: MCPAuthAuthServerError + +リモート認可 (Authorization) サーバーに問題が発生した場合にスローされるエラーです。 + +## 継承 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## コンストラクター {#constructors} + +### コンストラクター {#constructor} + +```ts +new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; +``` + +#### パラメーター {#parameters} + +##### code {#code} + +[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### 戻り値 {#returns} + +`MCPAuthAuthServerError` + +#### オーバーライド {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## プロパティ {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: AuthServerErrorCode; +``` + +スネークケース形式のエラーコードです。 + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthAuthServerError'; +``` + +#### オーバーライド {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` プロパティは、スタックトレース(`new Error().stack` または `Error.captureStackTrace(obj)` で生成される)によって収集されるスタックフレームの数を指定します。 + +デフォルト値は `10` ですが、有効な JavaScript の数値であれば任意に設定できます。値を変更した後にキャプチャされたすべてのスタックトレースに影響します。 + +数値以外、または負の数値を設定した場合、スタックトレースはフレームをキャプチャしません。 + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## メソッド {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +エラーを HTTP レスポンスに適した JSON 形式に変換します。 + +#### パラメーター {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +エラーの原因を JSON レスポンスに含めるかどうか。デフォルトは `false` です。 + +#### 戻り値 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +`targetObject` に `.stack` プロパティを作成し、アクセス時に +`Error.captureStackTrace()` が呼び出されたコード位置を表す文字列を返します。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // `new Error().stack` と同様 +``` + +トレースの最初の行は `${myObject.name}: ${myObject.message}` で始まります。 + +オプションの `constructorOpt` 引数には関数を指定できます。指定した場合、`constructorOpt` より上のすべてのフレーム(`constructorOpt` を含む)は生成されたスタックトレースから省略されます。 + +`constructorOpt` 引数は、エラー生成の実装詳細をユーザーから隠すのに便利です。例: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // スタックトレースを二重に計算しないよう、スタックトレースなしでエラーを作成 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 関数 b より上のスタックトレースをキャプチャ + Error.captureStackTrace(error, b); // 関数 c と b はスタックトレースに含まれません + throw error; +} + +a(); +``` + +#### パラメーター {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 戻り値 {#returns} + +`void` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### パラメーター {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 戻り値 {#returns} + +`any` + +#### 参照 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md new file mode 100644 index 0000000..10ac7f6 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md @@ -0,0 +1,239 @@ +--- +sidebar_label: MCPAuthBearerAuthError +--- + +# クラス: MCPAuthBearerAuthError + +Bearer トークンによる認証 (Authentication) 時に問題が発生した場合にスローされるエラーです。 + +## 継承 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## コンストラクター {#constructors} + +### コンストラクター {#constructor} + +```ts +new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; +``` + +#### パラメーター {#parameters} + +##### code {#code} + +[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) + +##### cause? {#cause} + +[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) + +#### 戻り値 {#returns} + +`MCPAuthBearerAuthError` + +#### オーバーライド {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## プロパティ {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: MCPAuthBearerAuthErrorDetails; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: BearerAuthErrorCode; +``` + +エラーコードは snake_case 形式です。 + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthBearerAuthError'; +``` + +#### オーバーライド {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` プロパティは、スタックトレース(`new Error().stack` または `Error.captureStackTrace(obj)` で生成される)の際に収集されるスタックフレーム数を指定します。 + +デフォルト値は `10` ですが、有効な JavaScript の数値であれば任意に設定できます。値を変更した後にキャプチャされたスタックトレースに影響します。 + +数値以外や負の数値を設定した場合、スタックトレースはフレームをキャプチャしません。 + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## メソッド {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +エラーを HTTP レスポンスに適した JSON 形式に変換します。 + +#### パラメーター {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +エラーの原因を JSON レスポンスに含めるかどうか。デフォルトは `false` です。 + +#### 戻り値 {#returns} + +`Record`\<`string`, `unknown`\> + +#### オーバーライド {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +`targetObject` に `.stack` プロパティを作成し、アクセス時に +`Error.captureStackTrace()` が呼び出されたコード位置を表す文字列を返します。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // `new Error().stack` と同様 +``` + +トレースの最初の行は +`${myObject.name}: ${myObject.message}` で始まります。 + +オプションの `constructorOpt` 引数には関数を指定できます。指定した場合、`constructorOpt` より上のすべてのフレーム(`constructorOpt` を含む)は生成されたスタックトレースから省略されます。 + +`constructorOpt` 引数は、エラー生成の実装詳細をユーザーから隠すのに便利です。例: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // スタックトレースを二重に計算しないよう、スタックトレースなしでエラーを作成 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 関数 b より上のスタックトレースをキャプチャ + Error.captureStackTrace(error, b); // 関数 c と b はスタックトレースに含まれません + throw error; +} + +a(); +``` + +#### パラメーター {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 戻り値 {#returns} + +`void` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### パラメーター {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 戻り値 {#returns} + +`any` + +#### 参考 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md new file mode 100644 index 0000000..34e9be3 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md @@ -0,0 +1,241 @@ +--- +sidebar_label: MCPAuthConfigError +--- + +# クラス: MCPAuthConfigError + +mcp-auth の設定に問題がある場合にスローされるエラーです。 + +## 継承 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## コンストラクター {#constructors} + +### コンストラクター {#constructor} + +```ts +new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; +``` + +#### パラメーター {#parameters} + +##### code {#code} + +`string` + +スネークケース形式のエラーコード。 + +##### message {#message} + +`string` + +エラーの人間が読める説明。 + +#### 戻り値 {#returns} + +`MCPAuthConfigError` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## プロパティ {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +スネークケース形式のエラーコード。 + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthConfigError'; +``` + +#### オーバーライド {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` プロパティは、スタックトレース(`new Error().stack` または `Error.captureStackTrace(obj)` で生成される)によって収集されるスタックフレームの数を指定します。 + +デフォルト値は `10` ですが、有効な JavaScript の数値であれば任意に設定できます。値を変更した後にキャプチャされたすべてのスタックトレースに影響します。 + +数値以外や負の値を設定した場合、スタックトレースはフレームをキャプチャしません。 + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## メソッド {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +エラーを HTTP レスポンスに適した JSON 形式に変換します。 + +#### パラメーター {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +JSON レスポンスにエラーの原因を含めるかどうか。デフォルトは `false` です。 + +#### 戻り値 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +`targetObject` に `.stack` プロパティを作成します。このプロパティにアクセスすると、`Error.captureStackTrace()` が呼び出されたコード位置を表す文字列が返されます。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // `new Error().stack` と同様 +``` + +トレースの最初の行は `${myObject.name}: ${myObject.message}` で始まります。 + +オプションの `constructorOpt` 引数には関数を指定できます。指定した場合、`constructorOpt` より上のすべてのフレーム(`constructorOpt` を含む)は生成されたスタックトレースから省略されます。 + +`constructorOpt` 引数は、エラー生成の実装詳細をユーザーから隠すのに便利です。例えば: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // スタックトレースを二重に計算しないよう、スタックトレースなしでエラーを作成 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 関数 b より上のスタックトレースをキャプチャ + Error.captureStackTrace(error, b); // 関数 c と b はスタックトレースに含まれません + throw error; +} + +a(); +``` + +#### パラメーター {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 戻り値 {#returns} + +`void` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### パラメーター {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 戻り値 {#returns} + +`any` + +#### 参考 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md new file mode 100644 index 0000000..4d098d7 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md @@ -0,0 +1,261 @@ +--- +sidebar_label: MCPAuthError +--- + +# クラス: MCPAuthError + +すべての mcp-auth エラーの基底クラスです。 + +MCP の認証 (Authentication) および認可 (Authorization) に関連するエラーを標準化された方法で処理する手段を提供します。 + +## 継承元 {#extends} + +- `Error` + +## このクラスを継承するクラス {#extended-by} + +- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) +- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) +- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) +- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) + +## コンストラクター {#constructors} + +### コンストラクター {#constructor} + +```ts +new MCPAuthError(code: string, message: string): MCPAuthError; +``` + +#### パラメーター {#parameters} + +##### code {#code} + +`string` + +スネークケース形式のエラーコード。 + +##### message {#message} + +`string` + +エラーの人間が読める説明。 + +#### 戻り値 {#returns} + +`MCPAuthError` + +#### オーバーライド元 {#overrides} + +```ts +Error.constructor +``` + +## プロパティ {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### 継承元 {#inherited-from} + +```ts +Error.cause +``` + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +スネークケース形式のエラーコード。 + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 継承元 {#inherited-from} + +```ts +Error.message +``` + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthError'; +``` + +#### オーバーライド元 {#overrides} + +```ts +Error.name +``` + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 継承元 {#inherited-from} + +```ts +Error.stack +``` + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` プロパティは、スタックトレース(`new Error().stack` または `Error.captureStackTrace(obj)` で生成される)によって収集されるスタックフレームの数を指定します。 + +デフォルト値は `10` ですが、有効な JavaScript の数値であれば任意に設定できます。値を変更した後にキャプチャされるすべてのスタックトレースに影響します。 + +数値以外や負の数値を設定した場合、スタックトレースはフレームをキャプチャしません。 + +#### 継承元 {#inherited-from} + +```ts +Error.stackTraceLimit +``` + +## メソッド {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +エラーを HTTP レスポンスに適した JSON 形式に変換します。 + +#### パラメーター {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +JSON レスポンスにエラーの原因を含めるかどうか。 +デフォルトは `false` です。 + +#### 戻り値 {#returns} + +`Record`\<`string`, `unknown`\> + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +`targetObject` に `.stack` プロパティを作成し、アクセス時に +`Error.captureStackTrace()` が呼び出されたコード位置を表す文字列を返します。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // `new Error().stack` と同様 +``` + +トレースの最初の行は +`${myObject.name}: ${myObject.message}` で始まります。 + +オプションの `constructorOpt` 引数には関数を指定できます。指定した場合、`constructorOpt` より上のすべてのフレーム(`constructorOpt` を含む)は生成されたスタックトレースから省略されます。 + +`constructorOpt` 引数は、エラー生成の実装詳細をユーザーから隠すのに便利です。例: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // スタックトレースを二重に計算しないように、スタックトレースなしでエラーを作成 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 関数 b より上のスタックトレースをキャプチャ + Error.captureStackTrace(error, b); // c と b はスタックトレースに含まれません + throw error; +} + +a(); +``` + +#### パラメーター {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 戻り値 {#returns} + +`void` + +#### 継承元 {#inherited-from} + +```ts +Error.captureStackTrace +``` + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### パラメーター {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 戻り値 {#returns} + +`any` + +#### 参考 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 継承元 {#inherited-from} + +```ts +Error.prepareStackTrace +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md new file mode 100644 index 0000000..3a2cce8 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md @@ -0,0 +1,240 @@ +--- +sidebar_label: MCPAuthTokenVerificationError +--- + +# クラス: MCPAuthTokenVerificationError + +トークンの検証時に問題が発生した場合にスローされるエラーです。 + +## 継承 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## コンストラクター {#constructors} + +### コンストラクター {#constructor} + +```ts +new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; +``` + +#### パラメーター {#parameters} + +##### code {#code} + +[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### 戻り値 {#returns} + +`MCPAuthTokenVerificationError` + +#### オーバーライド {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## プロパティ {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: MCPAuthTokenVerificationErrorCode; +``` + +スネークケース形式のエラーコードです。 + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthTokenVerificationError'; +``` + +#### オーバーライド {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` プロパティは、スタックトレース(`new Error().stack` または `Error.captureStackTrace(obj)` で生成される)によって収集されるスタックフレームの数を指定します。 + +デフォルト値は `10` ですが、有効な JavaScript の数値であれば任意に設定できます。値を変更した後にキャプチャされたスタックトレースに影響します。 + +数値以外や負の数を設定した場合、スタックトレースはフレームをキャプチャしません。 + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## メソッド {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +エラーを HTTP レスポンスに適した JSON 形式に変換します。 + +#### パラメーター {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +エラーの原因を JSON レスポンスに含めるかどうか。デフォルトは `false` です。 + +#### 戻り値 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +`targetObject` に `.stack` プロパティを作成し、アクセス時に +`Error.captureStackTrace()` が呼び出されたコード位置を表す文字列を返します。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // `new Error().stack` と同様 +``` + +トレースの最初の行は +`${myObject.name}: ${myObject.message}` で始まります。 + +オプションの `constructorOpt` 引数には関数を指定できます。指定した場合、`constructorOpt` を含むそれより上のすべてのフレームが +生成されたスタックトレースから省略されます。 + +`constructorOpt` 引数は、エラー生成の実装詳細をユーザーから隠すのに便利です。例: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // スタックトレースを二重に計算しないよう、スタックトレースなしでエラーを作成 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 関数 b より上のスタックトレースをキャプチャ + Error.captureStackTrace(error, b); // 関数 c と b はスタックトレースに含まれません + throw error; +} + +a(); +``` + +#### パラメーター {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 戻り値 {#returns} + +`void` + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### パラメーター {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 戻り値 {#returns} + +`any` + +#### 参考 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 継承元 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md new file mode 100644 index 0000000..3e03ad3 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md @@ -0,0 +1,43 @@ +--- +sidebar_label: createVerifyJwt +--- + +# 関数: createVerifyJwt() + +```ts +function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; +``` + +指定されたキー取得関数とオプションを使用して、JWT アクセス トークン (Access token) を検証する関数を作成します。 + +## パラメーター {#parameters} + +### getKey {#getkey} + +`JWTVerifyGetKey` + +JWT を検証するために使用するキーを取得する関数です。 + +**参照** + +キー取得関数の型定義については JWTVerifyGetKey を参照してください。 + +### options? {#options} + +`JWTVerifyOptions` + +オプションの JWT 検証オプションです。 + +**参照** + +オプションの型定義については JWTVerifyOptions を参照してください。 + +## 戻り値 {#returns} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +JWT アクセス トークン (Access token) を検証し、トークンが有効な場合は AuthInfo オブジェクトを返す関数です。この関数は、JWT のペイロードに `iss`、`client_id`、`sub` フィールドが含まれている必要があり、オプションで `scope` または `scopes` フィールドを含めることができます。内部的には `jose` ライブラリを使用して JWT の検証を行います。 + +## 参照 {#see} + +返される関数の型定義については [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) を参照してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md new file mode 100644 index 0000000..8b7d4e4 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md @@ -0,0 +1,60 @@ +--- +sidebar_label: fetchServerConfig +--- + +# 関数: fetchServerConfig() + +```ts +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +``` + +発行者 (Issuer) と認可サーバーの種類に基づいてサーバー設定を取得します。 + +この関数は、サーバーの種類に応じて自動的に well-known URL を判別します。OAuth および OpenID Connect サーバーは、メタデータエンドポイントの規約が異なります。 + +## パラメーター {#parameters} + +### issuer {#issuer} + +`string` + +認可サーバーの発行者 (Issuer) URL。 + +### config {#config} + +`ServerMetadataConfig` + +サーバーの種類およびオプションのトランスパイル関数を含む設定オブジェクト。 + +## 戻り値 {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +サーバー設定を解決する Promise。 + +## 参照 {#see} + + - 基本実装については [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) を参照してください。 + - OAuth 2.0 認可サーバーメタデータ仕様については [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) を参照してください。 + - OpenID Connect Discovery 仕様については [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) を参照してください。 + +## 例 {#example} + +```ts +import { fetchServerConfig } from 'mcp-auth'; +// OAuth サーバー設定の取得 +// これは `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` からメタデータを取得します +const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); + +// OpenID Connect サーバー設定の取得 +// これは `https://auth.logto.io/oidc/.well-known/openid-configuration` からメタデータを取得します +const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); +``` + +## 例外 {#throws} + +フェッチ操作が失敗した場合にスローされます。 + +## 例外 {#throws} + +サーバーメタデータが無効、または MCP 仕様と一致しない場合にスローされます。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md new file mode 100644 index 0000000..4f66b26 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md @@ -0,0 +1,41 @@ +--- +sidebar_label: fetchServerConfigByWellKnownUrl +--- + +# 関数: fetchServerConfigByWellKnownUrl() + +```ts +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +``` + +指定された well-known URL からサーバー構成を取得し、それを MCP 仕様に照らして検証します。 + +サーバーメタデータが期待されるスキーマに準拠していない場合でも、互換性があると確信している場合は、`transpileData` 関数を定義してメタデータを期待される形式に変換できます。 + +## パラメーター {#parameters} + +### wellKnownUrl {#wellknownurl} + +サーバー構成を取得するための well-known URL。これは文字列または URL オブジェクトで指定できます。 + +`string` | `URL` + +### config {#config} + +`ServerMetadataConfig` + +サーバータイプおよびオプションのトランスパイル関数を含む構成オブジェクト。 + +## 戻り値 {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +サーバー構成を解決する Promise。 + +## 例外 {#throws} + +フェッチ操作が失敗した場合にスローされます。 + +## 例外 {#throws} + +サーバーメタデータが無効、または MCP 仕様に一致しない場合にスローされます。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md new file mode 100644 index 0000000..6f2fae3 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md @@ -0,0 +1,38 @@ +--- +sidebar_label: handleBearerAuth +--- + +# 関数: handleBearerAuth() + +```ts +function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; +``` + +Express アプリケーションで Bearer 認証 (Bearer auth) を処理するためのミドルウェア関数を作成します。 + +このミドルウェアは、`Authorization` ヘッダーから Bearer トークンを抽出し、指定された `verifyAccessToken` 関数を使用して検証し、発行者、オーディエンス、必要なスコープをチェックします。 + +- トークンが有効な場合、認証情報を `request.auth` プロパティに追加します。有効でない場合は、適切なエラーメッセージで応答します。 +- アクセス トークン (Access token) の検証に失敗した場合、401 Unauthorized エラーで応答します。 +- トークンに必要なスコープ (Scope) が含まれていない場合、403 Forbidden エラーで応答します。 +- 認証 (Authentication) プロセス中に予期しないエラーが発生した場合、ミドルウェアはそれらを再スローします。 + +**注意:** `request.auth` オブジェクトには、`@modelcontextprotocol/sdk` モジュールで定義されている標準の AuthInfo インターフェースと比較して拡張されたフィールドが含まれます。詳細はこのファイル内の拡張インターフェースを参照してください。 + +## パラメーター {#parameters} + +### param0 {#param0} + +[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) + +Bearer 認証 (Bearer auth) ハンドラーの設定。 + +## 戻り値 {#returns} + +`RequestHandler` + +Bearer 認証 (Bearer auth) を処理する Express 用ミドルウェア関数。 + +## 参照 {#see} + +設定オプションについては [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) を参照してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md new file mode 100644 index 0000000..b69e6c7 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md @@ -0,0 +1,47 @@ +--- +sidebar_label: AuthServerConfig +--- + +# 型エイリアス: AuthServerConfig + +```ts +type AuthServerConfig = { + metadata: CamelCaseAuthorizationServerMetadata; + type: AuthServerType; +}; +``` + +MCP サーバーと統合されたリモート認可サーバー (Authorization server) の設定です。 + +## プロパティ {#properties} + +### metadata {#metadata} + +```ts +metadata: CamelCaseAuthorizationServerMetadata; +``` + +認可サーバー (Authorization server) のメタデータで、MCP 仕様(OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) に基づく)に準拠している必要があります。 + +このメタデータは通常、サーバーの well-known エンドポイント(OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) または OpenID Connect Discovery)から取得されます。サーバーがそのようなエンドポイントをサポートしていない場合は、設定内で直接指定することもできます。 + +**注意:** メタデータは mcp-auth ライブラリの推奨に従い、camelCase 形式である必要があります。 + +#### 参照 {#see} + + - [OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata)](https://datatracker.ietf.org/doc/html/rfc8414) + - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +*** + +### type {#type} + +```ts +type: AuthServerType; +``` + +認可サーバー (Authorization server) のタイプです。 + +#### 参照 {#see} + +[AuthServerType](/references/js/type-aliases/AuthServerType.md) で利用可能な値を確認できます。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md new file mode 100644 index 0000000..2e8e8e5 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md @@ -0,0 +1,45 @@ +--- +sidebar_label: AuthServerConfigError +--- + +# 型エイリアス: AuthServerConfigError + +```ts +type AuthServerConfigError = { + cause?: Error; + code: AuthServerConfigErrorCode; + description: string; +}; +``` + +認可サーバーメタデータの検証中に発生するエラーを表します。 + +## プロパティ {#properties} + +### cause? {#cause} + +```ts +optional cause: Error; +``` + +エラーの任意の原因。通常は、より詳細なコンテキストを提供する `Error` のインスタンスです。 + +*** + +### code {#code} + +```ts +code: AuthServerConfigErrorCode; +``` + +特定の検証エラーを表すコードです。 + +*** + +### description {#description} + +```ts +description: string; +``` + +エラーの人間が読める説明です。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md new file mode 100644 index 0000000..81df4a9 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: AuthServerConfigErrorCode +--- + +# 型エイリアス: AuthServerConfigErrorCode + +```ts +type AuthServerConfigErrorCode = + | "invalid_server_metadata" + | "code_response_type_not_supported" + | "authorization_code_grant_not_supported" + | "pkce_not_supported" + | "s256_code_challenge_method_not_supported"; +``` + +認可サーバーメタデータの検証時に発生する可能性があるエラーのコードです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md new file mode 100644 index 0000000..5a3c435 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md @@ -0,0 +1,34 @@ +--- +sidebar_label: AuthServerConfigWarning +--- + +# 型エイリアス: AuthServerConfigWarning + +```ts +type AuthServerConfigWarning = { + code: AuthServerConfigWarningCode; + description: string; +}; +``` + +認可サーバーメタデータの検証中に発生する警告を表します。 + +## プロパティ {#properties} + +### code {#code} + +```ts +code: AuthServerConfigWarningCode; +``` + +特定の検証警告を表すコードです。 + +*** + +### description {#description} + +```ts +description: string; +``` + +警告の人間が読める説明です。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md new file mode 100644 index 0000000..a11e5a4 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerConfigWarningCode +--- + +# 型エイリアス: AuthServerConfigWarningCode + +```ts +type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; +``` + +認可サーバーメタデータの検証時に発生する可能性がある警告のコードです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md new file mode 100644 index 0000000..bfa1379 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md @@ -0,0 +1,12 @@ +--- +sidebar_label: AuthServerErrorCode +--- + +# 型エイリアス: AuthServerErrorCode + +```ts +type AuthServerErrorCode = + | "invalid_server_metadata" + | "invalid_server_config" + | "missing_jwks_uri"; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md new file mode 100644 index 0000000..bc69700 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md @@ -0,0 +1,31 @@ +--- +sidebar_label: AuthServerModeConfig +--- + +# 型エイリアス: ~~AuthServerModeConfig~~ + +```ts +type AuthServerModeConfig = { + server: AuthServerConfig; +}; +``` + +レガシーの MCP サーバーを認可サーバーモードとして使用するための設定。 + +## 非推奨 {#deprecated} + +代わりに `ResourceServerModeConfig` 設定を使用してください。 + +## プロパティ {#properties} + +### ~~server~~ {#server} + +```ts +server: AuthServerConfig; +``` + +単一の認可サーバー設定。 + +#### 非推奨 {#deprecated} + +代わりに `protectedResources` 設定を使用してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md new file mode 100644 index 0000000..e9db26d --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md @@ -0,0 +1,17 @@ +--- +sidebar_label: AuthServerSuccessCode +--- + +# 型エイリアス: AuthServerSuccessCode + +```ts +type AuthServerSuccessCode = + | "server_metadata_valid" + | "dynamic_registration_supported" + | "pkce_supported" + | "s256_code_challenge_method_supported" + | "authorization_code_grant_supported" + | "code_response_type_supported"; +``` + +認可サーバーメタデータの検証が成功した場合のコードです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md new file mode 100644 index 0000000..9777ddd --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerType +--- + +# 型エイリアス: AuthServerType + +```ts +type AuthServerType = "oauth" | "oidc"; +``` + +認可サーバー (Authorization server) の種類です。この情報はサーバーの設定によって提供され、サーバーが OAuth 2.0 か OpenID Connect (OIDC) の認可サーバー (Authorization server) であるかを示します。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md new file mode 100644 index 0000000..3848338 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md @@ -0,0 +1,228 @@ +--- +sidebar_label: AuthorizationServerMetadata +--- + +# 型エイリアス: AuthorizationServerMetadata + +```ts +type AuthorizationServerMetadata = { + authorization_endpoint: string; + code_challenge_methods_supported?: string[]; + grant_types_supported?: string[]; + introspection_endpoint?: string; + introspection_endpoint_auth_methods_supported?: string[]; + introspection_endpoint_auth_signing_alg_values_supported?: string[]; + issuer: string; + jwks_uri?: string; + op_policy_uri?: string; + op_tos_uri?: string; + registration_endpoint?: string; + response_modes_supported?: string[]; + response_types_supported: string[]; + revocation_endpoint?: string; + revocation_endpoint_auth_methods_supported?: string[]; + revocation_endpoint_auth_signing_alg_values_supported?: string[]; + scopes_supported?: string[]; + service_documentation?: string; + token_endpoint: string; + token_endpoint_auth_methods_supported?: string[]; + token_endpoint_auth_signing_alg_values_supported?: string[]; + ui_locales_supported?: string[]; + userinfo_endpoint?: string; +}; +``` + +RFC 8414 で定義されている OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) のスキーマです。 + +## 型定義 {#type-declaration} + +### authorization\_endpoint {#authorization-endpoint} + +```ts +authorization_endpoint: string; +``` + +認可サーバーの認可エンドポイントの URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 +認可エンドポイントを使用するグラントタイプがサポートされていない場合を除き、これは必須です。 + +#### 参照 {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.1 + +### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} + +```ts +optional code_challenge_methods_supported: string[]; +``` + +この認可サーバーがサポートする Proof Key for Code Exchange (PKCE) +[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] のコードチャレンジ方式のリストを含む JSON 配列です。 + +### grant\_types\_supported? {#grant-types-supported} + +```ts +optional grant_types_supported: string[]; +``` + +この認可サーバーがサポートする OAuth 2.0 グラントタイプ値のリストを含む JSON 配列です。配列の値は、「OAuth 2.0 Dynamic Client Registration Protocol」[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] で定義されている `grant_types` パラメーターで使用されるものと同じです。 +省略された場合、デフォルト値は `["authorization_code", "implicit"]` です。 + +### introspection\_endpoint? {#introspection-endpoint} + +```ts +optional introspection_endpoint: string; +``` + +認可サーバーの OAuth 2.0 インスペクションエンドポイントの URL +[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]。 + +### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} + +```ts +optional introspection_endpoint_auth_methods_supported: string[]; +``` + +### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} + +```ts +optional introspection_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +認可サーバーの発行者 (Issuer) 識別子であり、`https` スキームを使用し、クエリやフラグメントコンポーネントを持たない URL です。 + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +認可サーバーの JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] +ドキュメントの URL。参照されるドキュメントには、クライアントが認可サーバーからの署名を検証するために使用する署名鍵が含まれています。この URL は `https` スキームを使用しなければなりません。 + +### op\_policy\_uri? {#op-policy-uri} + +```ts +optional op_policy_uri: string; +``` + +### op\_tos\_uri? {#op-tos-uri} + +```ts +optional op_tos_uri: string; +``` + +### registration\_endpoint? {#registration-endpoint} + +```ts +optional registration_endpoint: string; +``` + +認可サーバーの OAuth 2.0 ダイナミッククライアント登録エンドポイントの URL +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]。 + +### response\_modes\_supported? {#response-modes-supported} + +```ts +optional response_modes_supported: string[]; +``` + +この認可サーバーがサポートする OAuth 2.0 の `response_mode` 値のリストを含む JSON 配列です。「OAuth 2.0 Multiple Response Type Encoding Practices」 +[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)] で規定されています。 + +省略された場合、デフォルトは `["query", "fragment"]` です。レスポンスモード値 `"form_post"` も「OAuth 2.0 Form Post Response Mode」 +[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)] で定義されています。 + +### response\_types\_supported {#response-types-supported} + +```ts +response_types_supported: string[]; +``` + +この認可サーバーがサポートする OAuth 2.0 の `response_type` 値のリストを含む JSON 配列です。配列の値は、「OAuth 2.0 Dynamic Client Registration Protocol」 +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] で定義されている `response_types` パラメーターで使用されるものと同じです。 + +### revocation\_endpoint? {#revocation-endpoint} + +```ts +optional revocation_endpoint: string; +``` + +認可サーバーの OAuth 2.0 取り消しエンドポイントの URL +[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]。 + +### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} + +```ts +optional revocation_endpoint_auth_methods_supported: string[]; +``` + +### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} + +```ts +optional revocation_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +この認可サーバーがサポートする OAuth 2.0 の `scope` 値のリストを含む JSON 配列です。 +[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] + +### service\_documentation? {#service-documentation} + +```ts +optional service_documentation: string; +``` + +### token\_endpoint {#token-endpoint} + +```ts +token_endpoint: string; +``` + +認可サーバーのトークンエンドポイントの URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 +暗黙的グラントタイプのみがサポートされている場合を除き、これは必須です。 + +#### 参照 {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.2 + +### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} + +```ts +optional token_endpoint_auth_methods_supported: string[]; +``` + +### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} + +```ts +optional token_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### ui\_locales\_supported? {#ui-locales-supported} + +```ts +optional ui_locales_supported: string[]; +``` + +### userinfo\_endpoint? {#userinfo-endpoint} + +```ts +optional userinfo_endpoint: string; +``` + +OpenID Connect の [userinfo エンドポイント](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) の URL。 +このエンドポイントは、認証済みユーザーに関する情報を取得するために使用されます。 + +## 参照 {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md new file mode 100644 index 0000000..119de07 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md @@ -0,0 +1,107 @@ +--- +sidebar_label: BearerAuthConfig +--- + +# 型エイリアス: BearerAuthConfig + +```ts +type BearerAuthConfig = { + audience?: string; + issuer: | string + | ValidateIssuerFunction; + requiredScopes?: string[]; + resource?: string; + showErrorDetails?: boolean; + verifyAccessToken: VerifyAccessTokenFunction; +}; +``` + +## プロパティ {#properties} + +### audience? {#audience} + +```ts +optional audience: string; +``` + +アクセス トークン (アクセス トークン) の想定されるオーディエンス (`aud` クレーム)。これは通常、トークンが意図されているリソースサーバー (API) です。指定しない場合、オーディエンスのチェックはスキップされます。 + +**注:** 認可サーバーがリソースインジケーター (RFC 8707) をサポートしていない場合、このフィールドは省略できます。なぜなら、オーディエンスが関連しない場合があるためです。 + +#### 参照 {#see} + +https://datatracker.ietf.org/doc/html/rfc8707 + +*** + +### issuer {#issuer} + +```ts +issuer: + | string + | ValidateIssuerFunction; +``` + +有効な発行者 (Issuer) を表す文字列、またはアクセス トークンの発行者を検証するための関数。 + +文字列が指定された場合は、直接比較のための想定される発行者値として使用されます。 + +関数が指定された場合は、[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) のルールに従って発行者を検証する必要があります。 + +#### 参照 {#see} + +検証関数の詳細については [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) を参照してください。 + +*** + +### requiredScopes? {#requiredscopes} + +```ts +optional requiredScopes: string[]; +``` + +アクセス トークンが持つべき必須スコープ (スコープ) の配列。トークンにこれらすべてのスコープが含まれていない場合、エラーがスローされます。 + +**注:** ハンドラーはトークン内の `scope` クレームをチェックします。これは認可サーバーの実装によって、スペース区切りの文字列または文字列の配列である場合があります。`scope` クレームが存在しない場合、利用可能であれば `scopes` クレームをチェックします。 + +*** + +### resource? {#resource} + +```ts +optional resource: string; +``` + +保護されたリソースの識別子。指定された場合、ハンドラーはこのリソース用に設定された認可サーバーを使用して受信したトークンを検証します。`protectedResources` 設定とともにハンドラーを使用する場合は必須です。 + +*** + +### showErrorDetails? {#showerrordetails} + +```ts +optional showErrorDetails: boolean; +``` + +レスポンスに詳細なエラー情報を表示するかどうか。これは開発中のデバッグに役立ちますが、本番環境では機密情報漏洩を防ぐために無効にする必要があります。 + +#### デフォルト {#default} + +```ts +false +``` + +*** + +### verifyAccessToken {#verifyaccesstoken} + +```ts +verifyAccessToken: VerifyAccessTokenFunction; +``` + +アクセス トークンを検証するための関数型。 + +この関数は、トークンが無効な場合は [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) をスローし、有効な場合は AuthInfo オブジェクトを返す必要があります。 + +#### 参照 {#see} + +詳細については [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) を参照してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md new file mode 100644 index 0000000..908bb65 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: BearerAuthErrorCode +--- + +# 型エイリアス: BearerAuthErrorCode + +```ts +type BearerAuthErrorCode = + | "missing_auth_header" + | "invalid_auth_header_format" + | "missing_bearer_token" + | "invalid_issuer" + | "invalid_audience" + | "missing_required_scopes" + | "invalid_token"; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md new file mode 100644 index 0000000..22a0143 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md @@ -0,0 +1,179 @@ +--- +sidebar_label: CamelCaseAuthorizationServerMetadata +--- + +# 型エイリアス: CamelCaseAuthorizationServerMetadata + +```ts +type CamelCaseAuthorizationServerMetadata = { + authorizationEndpoint: string; + codeChallengeMethodsSupported?: string[]; + grantTypesSupported?: string[]; + introspectionEndpoint?: string; + introspectionEndpointAuthMethodsSupported?: string[]; + introspectionEndpointAuthSigningAlgValuesSupported?: string[]; + issuer: string; + jwksUri?: string; + opPolicyUri?: string; + opTosUri?: string; + registrationEndpoint?: string; + responseModesSupported?: string[]; + responseTypesSupported: string[]; + revocationEndpoint?: string; + revocationEndpointAuthMethodsSupported?: string[]; + revocationEndpointAuthSigningAlgValuesSupported?: string[]; + scopesSupported?: string[]; + serviceDocumentation?: string; + tokenEndpoint: string; + tokenEndpointAuthMethodsSupported?: string[]; + tokenEndpointAuthSigningAlgValuesSupported?: string[]; + uiLocalesSupported?: string[]; + userinfoEndpoint?: string; +}; +``` + +OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) 型の camelCase バージョンです。 + +## 型定義 {#type-declaration} + +### authorizationEndpoint {#authorizationendpoint} + +```ts +authorizationEndpoint: string; +``` + +### codeChallengeMethodsSupported? {#codechallengemethodssupported} + +```ts +optional codeChallengeMethodsSupported: string[]; +``` + +### grantTypesSupported? {#granttypessupported} + +```ts +optional grantTypesSupported: string[]; +``` + +### introspectionEndpoint? {#introspectionendpoint} + +```ts +optional introspectionEndpoint: string; +``` + +### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} + +```ts +optional introspectionEndpointAuthMethodsSupported: string[]; +``` + +### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} + +```ts +optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### opPolicyUri? {#oppolicyuri} + +```ts +optional opPolicyUri: string; +``` + +### opTosUri? {#optosuri} + +```ts +optional opTosUri: string; +``` + +### registrationEndpoint? {#registrationendpoint} + +```ts +optional registrationEndpoint: string; +``` + +### responseModesSupported? {#responsemodessupported} + +```ts +optional responseModesSupported: string[]; +``` + +### responseTypesSupported {#responsetypessupported} + +```ts +responseTypesSupported: string[]; +``` + +### revocationEndpoint? {#revocationendpoint} + +```ts +optional revocationEndpoint: string; +``` + +### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} + +```ts +optional revocationEndpointAuthMethodsSupported: string[]; +``` + +### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} + +```ts +optional revocationEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### serviceDocumentation? {#servicedocumentation} + +```ts +optional serviceDocumentation: string; +``` + +### tokenEndpoint {#tokenendpoint} + +```ts +tokenEndpoint: string; +``` + +### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} + +```ts +optional tokenEndpointAuthMethodsSupported: string[]; +``` + +### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} + +```ts +optional tokenEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### uiLocalesSupported? {#uilocalessupported} + +```ts +optional uiLocalesSupported: string[]; +``` + +### userinfoEndpoint? {#userinfoendpoint} + +```ts +optional userinfoEndpoint: string; +``` + +## 参照 {#see} + +元の型およびフィールド情報については [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) を参照してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md new file mode 100644 index 0000000..c4a449e --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md @@ -0,0 +1,123 @@ +--- +sidebar_label: CamelCaseProtectedResourceMetadata +--- + +# 型エイリアス: CamelCaseProtectedResourceMetadata + +```ts +type CamelCaseProtectedResourceMetadata = { + authorizationDetailsTypesSupported?: string[]; + authorizationServers?: string[]; + bearerMethodsSupported?: string[]; + dpopBoundAccessTokensRequired?: boolean; + dpopSigningAlgValuesSupported?: string[]; + jwksUri?: string; + resource: string; + resourceDocumentation?: string; + resourceName?: string; + resourcePolicyUri?: string; + resourceSigningAlgValuesSupported?: string[]; + resourceTosUri?: string; + scopesSupported?: string[]; + signedMetadata?: string; + tlsClientCertificateBoundAccessTokens?: boolean; +}; +``` + +OAuth 2.0 Protected Resource Metadata 型の camelCase バージョンです。 + +## 型定義 {#type-declaration} + +### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} + +```ts +optional authorizationDetailsTypesSupported: string[]; +``` + +### authorizationServers? {#authorizationservers} + +```ts +optional authorizationServers: string[]; +``` + +### bearerMethodsSupported? {#bearermethodssupported} + +```ts +optional bearerMethodsSupported: string[]; +``` + +### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} + +```ts +optional dpopBoundAccessTokensRequired: boolean; +``` + +### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} + +```ts +optional dpopSigningAlgValuesSupported: string[]; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### resource {#resource} + +```ts +resource: string; +``` + +### resourceDocumentation? {#resourcedocumentation} + +```ts +optional resourceDocumentation: string; +``` + +### resourceName? {#resourcename} + +```ts +optional resourceName: string; +``` + +### resourcePolicyUri? {#resourcepolicyuri} + +```ts +optional resourcePolicyUri: string; +``` + +### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} + +```ts +optional resourceSigningAlgValuesSupported: string[]; +``` + +### resourceTosUri? {#resourcetosuri} + +```ts +optional resourceTosUri: string; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### signedMetadata? {#signedmetadata} + +```ts +optional signedMetadata: string; +``` + +### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} + +```ts +optional tlsClientCertificateBoundAccessTokens: boolean; +``` + +## 参照 {#see} + +元の型およびフィールド情報については、 [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) を参照してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md new file mode 100644 index 0000000..4012d4c --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md @@ -0,0 +1,55 @@ +--- +sidebar_label: MCPAuthBearerAuthErrorDetails +--- + +# 型エイリアス: MCPAuthBearerAuthErrorDetails + +```ts +type MCPAuthBearerAuthErrorDetails = { + actual?: unknown; + cause?: unknown; + expected?: unknown; + missingScopes?: string[]; + uri?: URL; +}; +``` + +## プロパティ {#properties} + +### actual? {#actual} + +```ts +optional actual: unknown; +``` + +*** + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +*** + +### expected? {#expected} + +```ts +optional expected: unknown; +``` + +*** + +### missingScopes? {#missingscopes} + +```ts +optional missingScopes: string[]; +``` + +*** + +### uri? {#uri} + +```ts +optional uri: URL; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md new file mode 100644 index 0000000..774d77d --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md @@ -0,0 +1,13 @@ +--- +sidebar_label: MCPAuthConfig +--- + +# 型エイリアス: MCPAuthConfig + +```ts +type MCPAuthConfig = + | AuthServerModeConfig + | ResourceServerModeConfig; +``` + +[MCPAuth](/references/js/classes/MCPAuth.md) クラスの設定であり、単一のレガシー `authorization server` または `resource server` 設定のいずれかをサポートします。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md new file mode 100644 index 0000000..36e1f1a --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md @@ -0,0 +1,9 @@ +--- +sidebar_label: MCPAuthTokenVerificationErrorCode +--- + +# 型エイリアス: MCPAuthTokenVerificationErrorCode + +```ts +type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md new file mode 100644 index 0000000..459d38d --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md @@ -0,0 +1,151 @@ +--- +sidebar_label: ProtectedResourceMetadata +--- + +# 型エイリアス: ProtectedResourceMetadata + +```ts +type ProtectedResourceMetadata = { + authorization_details_types_supported?: string[]; + authorization_servers?: string[]; + bearer_methods_supported?: string[]; + dpop_bound_access_tokens_required?: boolean; + dpop_signing_alg_values_supported?: string[]; + jwks_uri?: string; + resource: string; + resource_documentation?: string; + resource_name?: string; + resource_policy_uri?: string; + resource_signing_alg_values_supported?: string[]; + resource_tos_uri?: string; + scopes_supported?: string[]; + signed_metadata?: string; + tls_client_certificate_bound_access_tokens?: boolean; +}; +``` + +OAuth 2.0 保護されたリソースメタデータのスキーマです。 + +## 型宣言 {#type-declaration} + +### authorization\_details\_types\_supported? {#authorization-details-types-supported} + +```ts +optional authorization_details_types_supported: string[]; +``` + +authorization_details リクエストパラメーターを使用する際にサポートされる認可詳細タイプの値。 + +### authorization\_servers? {#authorization-servers} + +```ts +optional authorization_servers: string[]; +``` + +この保護されたリソースで使用できる OAuth 認可サーバーの発行者識別子のリスト。 + +### bearer\_methods\_supported? {#bearer-methods-supported} + +```ts +optional bearer_methods_supported: string[]; +``` + +OAuth 2.0 ベアラートークンの送信にサポートされる方法。値: ["header", "body", "query"]。 + +### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} + +```ts +optional dpop_bound_access_tokens_required: boolean; +``` + +この保護されたリソースが常に DPoP バインド付きアクセス トークン (アクセス トークン) を必要とするかどうか。 + +### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} + +```ts +optional dpop_signing_alg_values_supported: string[]; +``` + +DPoP 証明 JWT の検証にサポートされる JWS アルゴリズム。 + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +保護されたリソースの JSON Web Key (JWK) セットドキュメントの URL。このドキュメントには、この保護されたリソースから返されるレスポンスやデータのデジタル署名を検証するために使用できる公開鍵が含まれています。 +これはトークン検証に使用される認可サーバーの jwks_uri とは異なります。保護されたリソースがレスポンスに署名する場合、クライアントはこれらの公開鍵を取得して受信データの真正性と完全性を検証できます。 + +### resource {#resource} + +```ts +resource: string; +``` + +保護されたリソースのリソース識別子。 + +### resource\_documentation? {#resource-documentation} + +```ts +optional resource_documentation: string; +``` + +保護されたリソースの利用方法に関する開発者向けドキュメントの URL。 + +### resource\_name? {#resource-name} + +```ts +optional resource_name: string; +``` + +エンドユーザー向けに表示するための保護されたリソースの人間が読める名前。 + +### resource\_policy\_uri? {#resource-policy-uri} + +```ts +optional resource_policy_uri: string; +``` + +保護されたリソースのデータ利用要件に関する情報を含む URL。 + +### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} + +```ts +optional resource_signing_alg_values_supported: string[]; +``` + +リソースレスポンスの署名に保護されたリソースがサポートする JWS 署名アルゴリズム。 + +### resource\_tos\_uri? {#resource-tos-uri} + +```ts +optional resource_tos_uri: string; +``` + +保護されたリソースの利用規約を含む URL。 + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +この保護されたリソースへアクセスするための認可リクエストで使用されるスコープ (スコープ) のリスト。 + +### signed\_metadata? {#signed-metadata} + +```ts +optional signed_metadata: string; +``` + +クレームとしてメタデータパラメーターを含む署名付き JWT。この JWT は JWS を使用して署名され、'iss' クレームを含める必要があります。このフィールドは、メタデータ自体の真正性を暗号学的に検証する方法を提供します。署名は `jwks_uri` エンドポイントで利用可能な公開鍵を使用して検証できます。 +存在する場合、この署名付きメタデータ内の値は、このメタデータドキュメント内の対応するプレーン JSON 値よりも優先されます。これにより、リソースメタデータの改ざんを防ぐことができます。 + +### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} + +```ts +optional tls_client_certificate_bound_access_tokens: boolean; +``` + +保護されたリソースが相互 TLS クライアント証明書バインド付きアクセス トークン (アクセス トークン) をサポートするかどうか。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md new file mode 100644 index 0000000..ad853f7 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md @@ -0,0 +1,23 @@ +--- +sidebar_label: ResourceServerModeConfig +--- + +# 型エイリアス: ResourceServerModeConfig + +```ts +type ResourceServerModeConfig = { + protectedResources: ResourceServerConfig | ResourceServerConfig[]; +}; +``` + +MCP サーバーをリソースサーバーモードとして構成するための設定です。 + +## プロパティ {#properties} + +### protectedResources {#protectedresources} + +```ts +protectedResources: ResourceServerConfig | ResourceServerConfig[]; +``` + +単一のリソースサーバー設定、またはその配列です。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md new file mode 100644 index 0000000..12b1a93 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md @@ -0,0 +1,30 @@ +--- +sidebar_label: ValidateIssuerFunction +--- + +# 型エイリアス: ValidateIssuerFunction() + +```ts +type ValidateIssuerFunction = (tokenIssuer: string) => void; +``` + +アクセス トークン (Access token) の発行者 (Issuer) を検証するための関数型です。 + +この関数は、発行者 (Issuer) が有効でない場合、コード 'invalid_issuer' の [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) をスローする必要があります。発行者 (Issuer) は以下に対して検証されるべきです: + +1. MCP-Auth の認可サーバーメタデータで設定された認可サーバー (Authorization servers) +2. 保護されたリソースのメタデータに記載された認可サーバー (Authorization servers) + +## パラメーター {#parameters} + +### tokenIssuer {#tokenissuer} + +`string` + +## 戻り値 {#returns} + +`void` + +## 例外 {#throws} + +発行者 (Issuer) が認識されない、または無効な場合にスローされます。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md new file mode 100644 index 0000000..9f3a787 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md @@ -0,0 +1,35 @@ +--- +sidebar_label: VerifyAccessTokenFunction +--- + +# 型エイリアス: VerifyAccessTokenFunction() + +```ts +type VerifyAccessTokenFunction = (token: string) => MaybePromise; +``` + +アクセス トークン (Access token) を検証するための関数型です。 + +この関数は、トークンが無効な場合は [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) をスローし、有効な場合は AuthInfo オブジェクトを返す必要があります。 + +例えば、JWT 検証関数がある場合、少なくともトークンの署名を確認し、有効期限を検証し、必要なクレーム (Claims) を抽出して `AuthInfo` オブジェクトを返す必要があります。 + +**注意:** 次のフィールドについては、ハンドラー側で確認されるため、トークン内で検証する必要はありません: + +- `iss`(発行者 (Issuer)) +- `aud`(オーディエンス (Audience)) +- `scope`(スコープ (Scopes)) + +## パラメーター {#parameters} + +### token {#token} + +`string` + +検証対象のアクセス トークン (Access token) 文字列。 + +## 戻り値 {#returns} + +`MaybePromise`\<`AuthInfo`\> + +トークンが有効な場合、AuthInfo オブジェクトを解決する Promise または同期値。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md new file mode 100644 index 0000000..28efbbb --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: VerifyAccessTokenMode +--- + +# 型エイリアス: VerifyAccessTokenMode + +```ts +type VerifyAccessTokenMode = "jwt"; +``` + +`bearerAuth` でサポートされている組み込みの検証モードです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md new file mode 100644 index 0000000..fec4bec --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: authServerErrorDescription +--- + +# 変数: authServerErrorDescription + +```ts +const authServerErrorDescription: Readonly>; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md new file mode 100644 index 0000000..dfbc6ee --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: authorizationServerMetadataSchema +--- + +# 変数: authorizationServerMetadataSchema + +```ts +const authorizationServerMetadataSchema: ZodObject; +``` + +RFC 8414 で定義されている OAuth 2.0 認可サーバーメタデータのための Zod スキーマです。 + +## 参考 {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md new file mode 100644 index 0000000..445c574 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: bearerAuthErrorDescription +--- + +# 変数: bearerAuthErrorDescription + +```ts +const bearerAuthErrorDescription: Readonly>; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md new file mode 100644 index 0000000..d1d5ad5 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseAuthorizationServerMetadataSchema +--- + +# 変数: camelCaseAuthorizationServerMetadataSchema + +```ts +const camelCaseAuthorizationServerMetadataSchema: ZodObject; +``` + +OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) の Zod スキーマの camelCase バージョンです。 + +## 参照 {#see} + +元のスキーマおよびフィールド情報については、 [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) を参照してください。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md new file mode 100644 index 0000000..d5dfe27 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseProtectedResourceMetadataSchema +--- + +# 変数: camelCaseProtectedResourceMetadataSchema + +```ts +const camelCaseProtectedResourceMetadataSchema: ZodObject; +``` + +OAuth 2.0 Protected Resource Metadata Zod スキーマの camelCase バージョンです。 + +## 参照 {#see} + +元のスキーマおよびフィールド情報については、 [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) を参照してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md new file mode 100644 index 0000000..99aeb6b --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md @@ -0,0 +1,9 @@ +--- +sidebar_label: defaultValues +--- + +# 変数: defaultValues + +```ts +const defaultValues: Readonly>; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md new file mode 100644 index 0000000..e871e73 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md @@ -0,0 +1,11 @@ +--- +sidebar_label: protectedResourceMetadataSchema +--- + +# 変数: protectedResourceMetadataSchema + +```ts +const protectedResourceMetadataSchema: ZodObject; +``` + +OAuth 2.0 保護されたリソースメタデータのための Zod スキーマです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md new file mode 100644 index 0000000..698258c --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md @@ -0,0 +1,12 @@ +--- +sidebar_label: serverMetadataPaths +--- + +# 変数: serverMetadataPaths + +```ts +const serverMetadataPaths: Readonly<{ + oauth: "/.well-known/oauth-authorization-server"; + oidc: "/.well-known/openid-configuration"; +}>; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md new file mode 100644 index 0000000..f5bf4c8 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: tokenVerificationErrorDescription +--- + +# 変数: tokenVerificationErrorDescription + +```ts +const tokenVerificationErrorDescription: Readonly>; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md new file mode 100644 index 0000000..3725276 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md @@ -0,0 +1,9 @@ +--- +sidebar_label: validateServerConfig +--- + +# 変数: validateServerConfig + +```ts +const validateServerConfig: ValidateServerConfig; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx b/i18n/ja/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx new file mode 100644 index 0000000..00f677a --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx @@ -0,0 +1,73 @@ +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + + + + +```python +mcp = FastMCP("MyMCPServer") +resource_identifier = "https://api.example.com" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_identifier, + authorization_servers=[fetch_server_config('', AuthServerType.OIDC)], + scopes_supported=["read", "write"], + ) + ) +) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + Mount('/', app=mcp.sse_app(), middleware=[Middleware( + mcp_auth.bearer_auth_middleware("jwt", + resource=resource_identifier, + audience=resource_identifier, + required_scopes=["read", "write"] + ) + )]) + ] +) + +@mcp.tool() +def whoami(): + return mcp_auth.auth_info.claims +``` + + + + +```ts +const server = new McpServer(/* ... */); +const resourceIdentifier = 'https://api.example.com'; + +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceIdentifier, + authorizationServers: [await fetchServerConfig('', { type: 'oidc' })], + scopesSupported: ['read', 'write'], + } + } +}); + +const app = express(); + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +app.use(mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, + requiredScopes: ['read', 'write'] +})); + +server.tool('whoami', ({ authInfo }) => { + return authInfo.claims; +}); +``` + + + diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx b/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx new file mode 100644 index 0000000..e1b64f3 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx @@ -0,0 +1,862 @@ +--- +sidebar_position: 2 +sidebar_label: 'チュートリアル: Todo マネージャーを構築する' +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + +# チュートリアル: Todo マネージャーを構築する + +このチュートリアルでは、ユーザー認証 (Authentication) と認可 (Authorization) を備えた todo マネージャー MCP サーバーを構築します。最新の MCP 仕様に従い、MCP サーバーは OAuth 2.0 **リソースサーバー (Resource Server)** として動作し、アクセス トークンを検証し、スコープベースの権限を強制します。 + +このチュートリアルを完了すると、次のことができるようになります: + +- ✅ MCP サーバーでロールベースのアクセス制御 (RBAC) を設定する方法の基本的な理解 +- ✅ リソースサーバー (Resource Server) として動作し、認可サーバー (Authorization Server) から発行されたアクセス トークンを利用する MCP サーバー +- ✅ Todo 操作に対するスコープベースの権限強制の実装 + +## 概要 \{#overview} + +このチュートリアルでは、以下のコンポーネントを扱います: + +- **MCP クライアント (MCP Inspector)**:OAuth 2.0 / OIDC クライアントとして動作する MCP サーバーのビジュアルテストツール。認可サーバーと認可フローを開始し、MCP サーバーへのリクエスト認証のためにアクセス トークンを取得します。 +- **認可サーバー (Authorization Server)**:OAuth 2.1 または OpenID Connect プロバイダーで、ユーザーのアイデンティティを管理し、ユーザーを認証 (Authentication) し、認可されたクライアントに適切なスコープを持つアクセス トークンを発行します。 +- **MCP サーバー (リソースサーバー)**:最新の MCP 仕様に従い、OAuth 2.0 フレームワークにおけるリソースサーバー (Resource Server) として動作します。認可サーバーから発行されたアクセス トークンを検証し、todo 操作に対してスコープベースの権限を強制します。 + +このアーキテクチャは標準的な OAuth 2.0 フローに従います: + +- **MCP Inspector** がユーザーの代理で保護されたリソースをリクエスト +- **認可サーバー (Authorization Server)** がユーザーを認証 (Authentication) し、アクセス トークンを発行 +- **MCP サーバー** がトークンを検証し、付与された権限に基づいて保護されたリソースを提供 + +これらのコンポーネント間のやり取りを高レベルで示した図です: + +```mermaid +sequenceDiagram + autonumber + participant Client as MCP Inspector
(OAuth クライアント) + participant RS as MCP サーバー
(リソースサーバー) + participant AS as 認可サーバー + + Client->>RS: MCP リクエスト (トークンなし) + RS-->>Client: 401 Unauthorized (WWW-Authenticate) + Note over Client: WWW-Authenticate ヘッダーから
resource_metadata URL を抽出 + + Client->>RS: GET /.well-known/oauth-protected-resource (resource_metadata) + RS-->>Client: 保護リソースのメタデータ
(認可サーバー URL を含む) + + Client->>AS: GET /.well-known/oauth-authorization-server + AS-->>Client: 認可サーバーのメタデータ + Client->>AS: OAuth 認可 (ログイン & 同意) + AS-->>Client: アクセス トークン + + Client->>RS: MCP リクエスト (Authorization: Bearer ) + RS->>RS: アクセス トークンが有効かつ認可済みか検証 + RS-->>Client: MCP レスポンス +``` + +## 認可サーバーを理解する \{#understand-your-authorization-server} + +### スコープ付きアクセス トークン \{#access-tokens-with-scopes} + +MCP サーバーで [ロールベースのアクセス制御 (RBAC)](https://auth.wiki/rbac) を実装するには、認可サーバーがスコープ付きのアクセス トークンを発行できる必要があります。スコープはユーザーに付与された権限を表します。 + + + + +[Logto](https://logto.io) は、API リソース([RFC 8707: OAuth 2.0 のリソースインジケーター](https://datatracker.ietf.org/doc/html/rfc8707) に準拠)とロール機能を通じて RBAC をサポートしています。設定方法は以下の通りです: + +1. [Logto Console](https://cloud.logto.io)(またはセルフホスト版 Logto Console)にサインイン + +2. API リソースとスコープを作成: + + - 「API リソース」に移動 + - 「Todo Manager」という新しい API リソースを作成 + - 以下のスコープを追加: + - `create:todos`: "新しい todo アイテムの作成" + - `read:todos`: "すべての todo アイテムの閲覧" + - `delete:todos`: "任意の todo アイテムの削除" + +3. ロールを作成(管理を簡単にするため推奨): + + - 「ロール」に移動 + - 「Admin」ロールを作成し、すべてのスコープ(`create:todos`, `read:todos`, `delete:todos`)を割り当て + - 「User」ロールを作成し、`create:todos` スコープのみを割り当て + +4. 権限を割り当て: + - 「ユーザー」に移動 + - ユーザーを選択 + - 「ロール」タブでロールを割り当て(推奨) + - または「権限」タブでスコープを直接割り当て + +スコープは JWT アクセス トークンの `scope` クレームにスペース区切りの文字列として含まれます。 + + + + +OAuth 2.0 / OIDC プロバイダーは通常、スコープベースのアクセス制御をサポートしています。RBAC を実装する際は: + +1. 認可サーバーで必要なスコープを定義 +2. クライアントが認可フロー中にこれらのスコープをリクエストするよう設定 +3. 認可サーバーが付与されたスコープをアクセス トークンに含めることを確認 +4. スコープは通常、JWT アクセス トークンの `scope` クレームに含まれます + +詳細はプロバイダーのドキュメントを参照してください: + +- スコープの定義と管理方法 +- スコープがアクセス トークンにどのように含まれるか +- ロール管理など追加の RBAC 機能 + + + + +### トークンの検証と権限チェック \{#validating-tokens-and-checking-permissions} + +最新の MCP 仕様によると、MCP サーバーは OAuth 2.0 フレームワークにおける **リソースサーバー (Resource Server)** として動作します。リソースサーバーとして、MCP サーバーは以下の責任を持ちます: + +1. **トークン検証**:MCP クライアントから受け取ったアクセス トークンの真正性と完全性を検証 +2. **スコープ強制**:アクセス トークンからスコープを抽出し、クライアントが実行できる操作を判定 +3. **リソース保護**:クライアントが十分な権限を持つ有効なトークンを提示した場合のみ保護リソース(ツールの実行)を提供 + +MCP サーバーがリクエストを受け取ると、次の検証プロセスを実行します: + +1. `Authorization` ヘッダーからアクセス トークンを抽出(Bearer トークン形式) +2. アクセス トークンの署名と有効期限を検証 +3. 検証済みトークンからスコープとユーザー情報を抽出 +4. リクエストされた操作に必要なスコープをトークンが持っているか確認 + +例えば、ユーザーが新しい todo アイテムを作成したい場合、そのアクセス トークンには `create:todos` スコープが含まれている必要があります。リソースサーバーの検証フローは次の通りです: + +```mermaid +sequenceDiagram + participant Client as MCP クライアント + participant Server as MCP サーバー
(リソースサーバー) + participant Auth as 認可サーバー + + Client->>Server: アクセス トークン付きリクエスト
(Authorization: Bearer ) + + alt JWT 検証(推奨) + Server->>Auth: JWKS を取得(キャッシュされていない場合) + Auth-->>Server: JWKS を返す + Server->>Server: JWT 署名とクレームをローカルで検証 + else トークンインスペクション(フォールバック) + Server->>Auth: POST /introspect
(token=access_token) + Auth-->>Server: トークン情報を返す
(active, scope, user_id など) + end + + Server->>Server: 検証済みトークンからスコープとユーザーコンテキストを抽出 + + alt 必要なスコープあり + Server->>Server: リクエストされた操作を実行 + Server->>Client: 操作結果を返す + else 必要なスコープなし + Server->>Client: 403 Forbidden
(insufficient_scope エラー) + end +``` + +### Dynamic Client Registration \{#dynamic-client-registration} + +このチュートリアルでは Dynamic Client Registration は必須ではありませんが、認可サーバーで MCP クライアント登録を自動化したい場合に便利です。詳細は [Dynamic Client Registration は必要ですか?](/provider-list#is-dcr-required) を参照してください。 + +## Todo マネージャーにおける RBAC を理解する \{#understand-rbac-in-todo-manager} + +デモ目的で、todo マネージャー MCP サーバーにシンプルなロールベースのアクセス制御 (RBAC) システムを実装します。これにより、RBAC の基本原則をシンプルな実装で体験できます。 + +:::note +このチュートリアルは RBAC ベースのスコープ管理を例示していますが、すべての認証 (Authentication) プロバイダーがロールによるスコープ管理を実装しているわけではありません。プロバイダーによっては独自のアクセス制御や権限管理の仕組みを持つ場合があります。 +::: + +### ツールとスコープ \{#tools-and-scopes} + +todo マネージャー MCP サーバーは主に 3 つのツールを提供します: + +- `create-todo`: 新しい todo アイテムの作成 +- `get-todos`: すべての todo の一覧取得 +- `delete-todo`: ID で todo を削除 + +これらのツールへのアクセスを制御するため、次のスコープを定義します: + +- `create:todos`: 新しい todo アイテムの作成を許可 +- `delete:todos`: 既存の todo アイテムの削除を許可 +- `read:todos`: すべての todo アイテムの取得を許可 + +### ロールと権限 \{#roles-and-permissions} + +異なるアクセスレベルを持つ 2 つのロールを定義します: + +| ロール | create:todos | read:todos | delete:todos | +| ------- | ------------ | ---------- | ------------ | +| Admin | ✅ | ✅ | ✅ | +| User | ✅ | | | + +- **User**:自分の todo アイテムの作成・閲覧・削除のみ可能な一般ユーザー +- **Admin**:すべての todo アイテムを作成・閲覧・削除できる管理者(所有者に関係なく) + +### リソース所有権 \{#resource-ownership} + +上記の権限テーブルは各ロールに明示的に割り当てられたスコープを示していますが、リソース所有権の重要な原則も考慮する必要があります: + +- **User** は `read:todos` や `delete:todos` スコープを持っていませんが、以下は可能です: + - 自分の todo アイテムの閲覧 + - 自分の todo アイテムの削除 +- **Admin** はすべての権限(`read:todos` および `delete:todos`)を持ち、以下が可能です: + - システム内のすべての todo アイテムの閲覧 + - 所有者に関係なく任意の todo アイテムの削除 + +これは、リソース所有権がユーザー自身のリソースに対する暗黙的な権限を与え、管理者ロールにはすべてのリソースに対する明示的な権限が付与されるという、RBAC システムでよく見られるパターンです。 + +:::tip 詳しく学ぶ +RBAC の概念やベストプラクティスについてさらに深く知りたい場合は、[Mastering RBAC: A Comprehensive Real-World Example](https://blog.logto.io/mastering-rbac) をご覧ください。 +::: + +## プロバイダーで認可を設定する \{#configure-authorization-in-your-provider} + +前述のアクセス制御システムを実装するには、認可サーバーで必要なスコープをサポートするよう設定する必要があります。プロバイダーごとの設定方法は以下の通りです: + + + + +[Logto](https://logto.io) は、API リソースとロール機能を通じて RBAC をサポートしています。設定方法は以下の通りです: + +1. [Logto Console](https://cloud.logto.io)(またはセルフホスト版 Logto Console)にサインイン + +2. API リソースとスコープを作成: + + - 「API リソース」に移動 + - 「Todo Manager」という新しい API リソースを作成し、リソースインジケーターに `http://localhost:3001` を使用 + - **重要**:リソースインジケーターは MCP サーバーの URL と一致する必要があります。このチュートリアルでは MCP サーバーがポート 3001 で動作するため `http://localhost:3001` を使用します。本番環境では実際の MCP サーバー URL(例:`https://your-mcp-server.example.com`)を使用してください。 + - 以下のスコープを作成: + - `create:todos`: "新しい todo アイテムの作成" + - `read:todos`: "すべての todo アイテムの閲覧" + - `delete:todos`: "任意の todo アイテムの削除" + +3. ロールを作成(管理を簡単にするため推奨): + + - 「ロール」に移動 + - 「Admin」ロールを作成し、すべてのスコープ(`create:todos`, `read:todos`, `delete:todos`)を割り当て + - 「User」ロールを作成し、`create:todos` スコープのみを割り当て + - 「User」ロールの詳細ページで「一般」タブに切り替え、「User」ロールを「デフォルトロール」に設定 + +4. ユーザーのロールと権限を管理: + - 新規ユーザーの場合: + - デフォルトロールを設定したため自動的に「User」ロールが付与されます + - 既存ユーザーの場合: + - 「ユーザー管理」に移動 + - ユーザーを選択 + - 「ロール」タブでロールを割り当て + +:::tip プログラムによるロール管理 +Logto の [Management API](https://docs.logto.io/integrate-logto/interact-with-management-api) を利用してユーザーロールをプログラムで管理することも可能です。自動化や管理画面構築時に便利です。 +::: + +アクセストークンをリクエストする際、Logto はユーザーのロール権限に基づきスコープをトークンの `scope` クレームに含めます。 + + + + +OAuth 2.0 または OpenID Connect プロバイダーの場合、異なる権限を表すスコープを設定する必要があります。具体的な手順はプロバイダーによって異なりますが、一般的には: + +1. スコープの定義: + + - 認可サーバーで以下をサポートするよう設定: + - `create:todos` + - `read:todos` + - `delete:todos` + +2. クライアントの設定: + + - クライアントを登録または更新し、これらのスコープをリクエストするように設定 + - スコープがアクセス トークンに含まれることを確認 + +3. 権限の割り当て: + - プロバイダーの管理画面でユーザーに適切なスコープを付与 + - 一部のプロバイダーはロールベース管理をサポートし、他は直接スコープ割り当てを使用 + - 推奨方法はプロバイダーのドキュメントを参照 + +:::tip +ほとんどのプロバイダーは付与されたスコープをアクセス トークンの `scope` クレームに含めます。形式は通常スペース区切りのスコープ値です。 +::: + + + + +認可サーバーの設定後、ユーザーは付与されたスコープを含むアクセス トークンを受け取ります。MCP サーバーはこれらのスコープを使用して次を判定します: + +- 新しい todo を作成できるか(`create:todos`) +- すべての todo を閲覧できるか(`read:todos`)または自分のものだけか +- 任意の todo を削除できるか(`delete:todos`)または自分のものだけか + +## MCP サーバーのセットアップ \{#set-up-the-mcp-server} + +[MCP 公式 SDK](https://github.com/modelcontextprotocol) を使って todo マネージャー MCP サーバーを作成します。 + +### 新しいプロジェクトを作成 \{#create-a-new-project} + + + + +新しい Python プロジェクトをセットアップ: + +```bash +mkdir mcp-todo-server +cd mcp-todo-server + +# 新しい Python プロジェクトを初期化 +uv init + +# uv で仮想環境を作成 +uv venv + +# 仮想環境を有効化('uv run' 使用時は省略可) +source .venv/bin/activate +``` + +:::note +このプロジェクトはパッケージ管理に `uv` を使用していますが、`pip`、`poetry`、`conda` など他のパッケージマネージャーも利用できます。 +::: + + + + +新しい Node.js プロジェクトをセットアップ: + +```bash +mkdir mcp-server +cd mcp-server +npm init -y # または `pnpm init` を使用 +npm pkg set type="module" +npm pkg set main="todo-manager.ts" +npm pkg set scripts.start="node --experimental-strip-types todo-manager.ts" +``` + +:::note +例では TypeScript を使用しています。Node.js v22.6.0 以降は `--experimental-strip-types` フラグで TypeScript をネイティブ実行できます。JavaScript を使う場合もほぼ同様ですが、Node.js v22.6.0 以降を使用してください。詳細は Node.js ドキュメントを参照。 +::: + + + + +### MCP SDK と依存パッケージのインストール \{#install-the-mcp-sdk-and-dependencies} + + + + +必要な依存パッケージをインストール: + +```bash +uv add "mcp[cli]" uvicorn starlette +``` + + + + +```bash +npm install @modelcontextprotocol/sdk express zod +``` + +または `pnpm` や `yarn` などお好みのパッケージマネージャーを使用してください。 + + + + +### MCP サーバーを作成 \{#create-the-mcp-server} + +まず、ツール定義を含む基本的な MCP サーバーを作成します: + + + + +`server.py` というファイルを作成し、以下のコードを追加: + +(※以降のコード・手順・説明は原文通り。省略) + + + + +`todo-manager.ts` というファイルを作成し、以下のコードを追加: + +(※以降のコード・手順・説明は原文通り。省略) + + + + +### MCP サーバーの検証 \{#inspect-the-mcp-server} + +#### MCP inspector のクローンと実行 \{#clone-and-run-mcp-inspector} + +MCP サーバーが起動したら、MCP inspector を使ってツールが利用可能か確認できます。 + +公式 MCP inspector v0.16.2 には認証 (Authentication) 機能に影響するバグがあります。これを解決するため、OAuth / OIDC 認証フローの修正を含む [パッチ版 MCP inspector](https://github.com/mcp-auth/inspector/tree/patch/0.16.2-fixes) を用意しました。修正内容は公式リポジトリにもプルリクエスト済みです。 + +MCP inspector を実行するには、以下のコマンドを使用してください(Node.js 必須): + +```bash +git clone https://github.com/mcp-auth/inspector.git -b patch/0.16.2-fixes +cd inspector +npm install +npm run dev +``` + +MCP inspector は自動的にデフォルトブラウザで開きます。もしくはターミナル出力のリンク(`MCP_PROXY_AUTH_TOKEN` パラメータ付き、例:`http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=458ae4a4...acab1907`)を手動で開いてください。 + +#### MCP inspector を MCP サーバーに接続 \{#connect-mcp-inspector-to-the-mcp-server} + +進む前に、MCP inspector の設定を確認してください: + +- **Transport Type**:`Streamable HTTP` に設定 +- **URL**:MCP サーバーの URL(この例では `http://localhost:3001`) + +「Connect」ボタンをクリックし、MCP inspector が MCP サーバーに接続できるか確認します。正常なら MCP inspector に「Connected」ステータスが表示されます。 + +#### チェックポイント: Todo マネージャーツールの実行 \{#checkpoint-run-todo-manager-tools} + +1. MCP inspector の上部メニューで「Tools」タブをクリック +2. 「List Tools」ボタンをクリック +3. `create-todo`, `get-todos`, `delete-todo` ツールが一覧表示されるはずです。クリックして詳細を開きます +4. 右側に「Run Tool」ボタンが表示されます。必要なパラメータを入力してツールを実行 +5. ツール結果として `{"error": "Not implemented"}` の JSON レスポンスが表示されます + +![MCP inspector first run](/docs-assets/images/tutorials/todo-manager/inspector-first-run.png) + +## 認可サーバーとの連携 \{#integrate-with-your-authorization-server} + +このセクションを完了するには、いくつかの考慮事項があります: + +
+**認可サーバーの発行者 (Issuer) URL** + +通常は認可サーバーのベース URL です(例:`https://auth.example.com`)。プロバイダーによっては `https://example.logto.app/oidc` のようなパスが付く場合もあるので、ドキュメントを確認してください。 + +
+ +
+**認可サーバーのメタデータ取得方法** + +- 認可サーバーが [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) または [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) に準拠していれば、MCP Auth の組み込みユーティリティで自動取得できます +- 準拠していない場合は、MCP サーバー設定でメタデータ URL やエンドポイントを手動指定してください。詳細はプロバイダーのドキュメント参照 + +
+ +
+**MCP inspector を認可サーバーのクライアントとして登録する方法** + +- 認可サーバーが [Dynamic Client Registration](https://datatracker.ietf.org/doc/html/rfc7591) をサポートしていれば、このステップは不要で MCP inspector が自動登録されます +- サポートしていない場合は MCP inspector を手動でクライアント登録してください + +
+ +
+**トークンリクエストパラメータの理解** + +認可サーバーごとにターゲットリソースや権限指定の方法が異なります。主なパターンは以下の通りです: + +- **リソースインジケーター方式**: + + - `resource` パラメータでターゲット API を指定([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707) 参照) + - モダンな OAuth 2.0 実装で一般的 + - 例: + ```json + { + "resource": "http://localhost:3001", + "scope": "create:todos read:todos" + } + ``` + - サーバーはリソースにバインドされたトークンを発行 + +- **オーディエンス方式**: + + - `audience` パラメータでトークンの宛先を指定 + - リソースインジケーターと似ているが意味が異なる + - 例: + ```json + { + "audience": "todo-api", + "scope": "create:todos read:todos" + } + ``` + +- **純粋なスコープ方式**: + - resource/audience パラメータなしでスコープのみ指定 + - 従来の OAuth 2.0 アプローチ + - 例: + ```json + { + "scope": "todo-api:create todo-api:read openid profile" + } + ``` + - スコープにプレフィックスを付けて権限をネームスペース化することが多い + - シンプルな OAuth 2.0 実装で一般的 + +:::tip ベストプラクティス + +- プロバイダーのドキュメントでサポートされているパラメータを確認 +- 複数の方式を同時にサポートするプロバイダーもある +- リソースインジケーターはオーディエンス制限によるセキュリティ向上に有効 +- 可能ならリソースインジケーター方式を利用するとより良いアクセス制御が可能 + ::: + +
+ +プロバイダーごとに要件は異なりますが、以下の手順で MCP inspector および MCP サーバーをプロバイダー固有の設定で統合できます。 + +### MCP inspector をクライアントとして登録 \{#register-mcp-inspector-as-a-client} + + + + +[Logto](https://logto.io) との連携はシンプルです。OpenID Connect プロバイダーであり、リソースインジケーターとスコープをサポートしているため、`http://localhost:3001` をリソースインジケーターとして todo API を安全に保護できます。 + +Logto は Dynamic Client Registration をまだサポートしていないため、MCP inspector を Logto テナントのクライアントとして手動登録する必要があります: + +1. MCP inspector を開き、Authentication 設定で「OAuth2.0 Flow」設定をクリック。**Redirect URI** の値(例:`http://localhost:6274/oauth/callback`)をコピー +2. [Logto Console](https://cloud.logto.io)(またはセルフホスト版 Logto Console)にサインイン +3. 「アプリケーション」タブで「アプリケーションを作成」をクリック。ページ下部で「フレームワークなしでアプリを作成」をクリック +4. アプリケーション詳細を入力し、「アプリケーションを作成」をクリック: + - **アプリケーションタイプ**:「シングルページアプリケーション」を選択 + - **アプリケーション名**:例「MCP Inspector」 +5. 「設定 / リダイレクト URI」セクションで、MCP inspector からコピーした **Redirect URI** を貼り付け。「変更を保存」をクリック +6. 上部カードに「App ID」が表示されるのでコピー +7. MCP inspector に戻り、「OAuth2.0 Flow」の「Client ID」欄に「App ID」を貼り付け +8. 「Scope」欄に `create:todos read:todos delete:todos` を入力。これで Logto から返されるアクセストークンに必要なスコープが含まれます + + + + +:::note +これは一般的な OAuth 2.0 / OpenID Connect プロバイダー統合ガイドです。OIDC は OAuth 2.0 上に構築されているため手順はほぼ同じです。詳細はプロバイダーのドキュメントを参照してください。 +::: + +Dynamic Client Registration をサポートしている場合は下記 8 の MCP inspector 設定に直接進めます。そうでない場合は MCP inspector を手動でクライアント登録してください: + +1. MCP inspector を開き、Authentication 設定で「OAuth2.0 Flow」設定をクリック。**Redirect URI** の値(例:`http://localhost:6274/oauth/callback`)をコピー + +2. プロバイダーのコンソールにサインイン + +3. 「アプリケーション」または「クライアント」セクションで新規アプリケーションまたはクライアントを作成 + +4. クライアントタイプが必要な場合は「シングルページアプリケーション」または「パブリッククライアント」を選択 + +5. アプリケーション作成後、リダイレクト URI を設定。MCP inspector からコピーした **Redirect URI** を貼り付け + +6. 新規アプリケーションの「Client ID」または「Application ID」をコピー + +7. MCP inspector に戻り、「OAuth2.0 Flow」の「Client ID」欄に「Client ID」を貼り付け + +8. 「Scope」欄に todo 操作用の必要なスコープを入力: + +```text +create:todos read:todos delete:todos +``` + + + + +### MCP Auth のセットアップ \{#set-up-mcp-auth} + +まず、MCP サーバープロジェクトに MCP Auth SDK をインストールします。 + + + + +```bash +uv add mcpauth==0.2.0b1 +``` + + + + +```bash +npm install mcp-auth@0.2.0-beta.1 +``` + + + + +次に、MCP サーバーで MCP Auth を初期化します。主な手順は 2 つです: + +1. **認可サーバーメタデータの取得**:MCP Auth で認可サーバー発行のアクセス トークン検証やリソースメタデータへの発行者識別子追加に利用 +2. **保護リソースメタデータの設定**:MCP サーバーのリソース識別子とサポートするスコープを定義 + +#### ステップ 1: 認可サーバーメタデータの取得 \{#step-1-fetch-authorization-server-metadata\} + +OAuth / OIDC 仕様に従い、認可サーバーの発行者 (issuer) URL からメタデータを取得できます。 + + + + + +Logto では、Logto Console のアプリケーション詳細ページ「Endpoints & Credentials / Issuer endpoint」セクションで issuer URL を確認できます(例:`https://my-project.logto.app/oidc`)。 + + + + + +OAuth 2.0 プロバイダーの場合: + +1. プロバイダーのドキュメントで認可サーバー URL(issuer URL または base URL)を確認 +2. 多くの場合 `https://{your-domain}/.well-known/oauth-authorization-server` で公開 +3. 管理コンソールの OAuth / API 設定を確認 + + + + + +次に、MCP Auth のユーティリティ関数で認可サーバーのメタデータを取得します: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +issuer_url = "" # 認可サーバーの issuer URL に置き換え + +# 認可サーバー設定を取得 +auth_server_config = fetch_server_config(issuer_url, AuthServerType.OIDC) # または AuthServerType.OAUTH +``` + + + +```js +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const issuerUrl = ''; // 認可サーバーの issuer URL に置き換え + +// 認可サーバー設定を取得(OIDC Discovery) +const authServerConfig = await fetchServerConfig(issuerUrl, { type: 'oidc' }); // または { type: 'oauth' } +``` + + + + +認可サーバーメタデータの他の取得方法やカスタマイズについては [認可サーバーメタデータの他の設定方法](/docs/configure-server/mcp-auth#other-ways) を参照してください。 + +#### ステップ 2: 保護リソースメタデータの設定 \{#step-2-configure-protected-resource-metadata} + +次に、MCP Auth インスタンス構築時に保護リソースメタデータを設定します。以降、MCP サーバーは MCP Auth で設定したリソースメタデータを公開します。 + + + + +```python +# server.py + +# 他の import... +from mcpauth.types import ResourceServerConfig, ResourceServerMetadata + +# この MCP サーバーのリソース識別子を定義 +resource_id = "http://localhost:3001" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + # 前ステップで取得した認可サーバーメタデータ + authorization_servers=[auth_server_config], + # この MCP サーバーが理解するスコープ + scopes_supported=[ + "create:todos", + "read:todos", + "delete:todos" + ] + ) + ) +) +``` + + + +```js +// todo-manager.ts + +// この MCP サーバーのリソース識別子を定義 +const resourceId = 'http://localhost:3001'; + +// MCP Auth に保護リソースメタデータを設定 +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceId, + // 前ステップで取得した認可サーバーメタデータ + authorizationServers: [authServerConfig], + // この MCP サーバーが理解するスコープ + scopesSupported: [ + "create:todos", + "read:todos", + "delete:todos" + ] + } + } +}); +``` + + + + +### MCP サーバーの更新 \{#update-mcp-server} + +あと少しです!MCP Auth のルートとミドルウェア関数を適用し、ユーザーのスコープに基づく権限制御を実装しましょう。 + +まず、MCP クライアントが MCP サーバーからリソースメタデータを取得できるよう、保護リソースメタデタルートを適用します。 + + + +```python +# server.py + +# ..他のコード + +app = Starlette( + routes=[ + # 保護リソースメタデータルートを設定 + # OAuth クライアント向けにこのリソースサーバーのメタデータを公開 + *mcp_auth.resource_metadata_router().routes, + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +// 保護リソースメタデータルートを設定 +// OAuth クライアント向けにこのリソースサーバーのメタデータを公開 +app.use(mcpAuth.protectedResourceMetadataRouter()); + +``` + + + +次に、MCP サーバーに MCP Auth ミドルウェアを適用します。このミドルウェアはリクエストの認証 (Authentication) と認可 (Authorization) を処理し、認可されたユーザーのみが todo マネージャーツールにアクセスできるようにします。 + + + +```python +# server.py + +# 他の import... +from starlette.middleware import Middleware + +# 他のコード... + +# ミドルウェアを作成 +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', resource=resource_id, audience=resource_id)) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # MCP Auth ミドルウェアを適用 + Mount("/", app=mcp.streamable_http_app(), middleware=[bearer_auth]), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// MCP Auth ミドルウェアを適用 +app.use( + mcpAuth.bearerAuth('jwt', { + resource: resourceId, + audience: resourceId, + }) +); +``` + + + +ここまで来たら、todo マネージャーツールの実装を MCP Auth ミドルウェアによる認証 (Authentication)・認可 (Authorization) に対応させましょう。 + +ツールの実装を更新します。 + +(※以降のコード・手順・説明は原文通り。省略) + +--- + +🎉 おめでとうございます!認証 (Authentication) と認可 (Authorization) を備えた完全な MCP サーバーの実装が完了しました! + +サンプルコードも参考にしてください: + + + + +:::info +[MCP Auth Python SDK リポジトリ](https://github.com/mcp-auth/python/tree/master/samples/current/todo-manager) で MCP サーバー(OIDC 版)の完全なコードを確認できます。 +::: + + + + +:::info +[MCP Auth Node.js SDK リポジトリ](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) で MCP サーバー(OIDC 版)の完全なコードを確認できます。 +::: + + + + +## チェックポイント: `todo-manager` ツールの実行 \{#checkpoint-run-the-todo-manager-tools} + +MCP サーバーを再起動し、ブラウザで MCP inspector を開きます。「Connect」ボタンをクリックすると、認可サーバーのサインインページにリダイレクトされます。 + +サインイン後 MCP inspector に戻り、前回のチェックポイントと同じ操作で todo マネージャーツールを実行してください。今回は認証 (Authentication) 済みユーザーのアイデンティティでツールを利用できます。ツールの挙動はユーザーに割り当てられたロールと権限によって異なります: + +- **User**(`create:todos` スコープのみ)の場合: + + - `create-todo` ツールで新しい todo を作成可能 + - 自分の todo のみ閲覧・削除可能 + - 他ユーザーの todo は閲覧・削除不可 + +- **Admin**(すべてのスコープ:`create:todos`, `read:todos`, `delete:todos`)の場合: + - 新しい todo の作成が可能 + - `get-todos` ツールですべての todo を閲覧可能 + - `delete-todo` ツールで誰の todo でも削除可能 + +異なる権限レベルをテストするには: + +1. MCP inspector で「Disconnect」ボタンをクリックして現在のセッションからサインアウト +2. 別のロール/権限を持つユーザーアカウントでサインイン +3. 同じツールを再度試し、ユーザーの権限による挙動の違いを確認 + +これにより、ロールベースのアクセス制御 (RBAC) が実際にどのように機能するかを体験できます。 + +![MCP inspector todo manager tool result](/docs-assets/images/tutorials/todo-manager/result.png) + + + + +:::info +[MCP Auth Python SDK リポジトリ](https://github.com/mcp-auth/python) で MCP サーバー(OIDC 版)の完全なコードを確認できます。 +::: + + + + +:::info +[MCP Auth Node.js SDK リポジトリ](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) で MCP サーバー(OIDC 版)の完全なコードを確認できます。 +::: + + + + +## 締めくくり \{#closing-notes} + +🎊 おめでとうございます!チュートリアルを無事完了しました。ここまでの内容を振り返りましょう: + +- Todo 管理ツール(`create-todo`, `get-todos`, `delete-todo`)を備えた基本的な MCP サーバーのセットアップ +- ユーザーと管理者で異なる権限レベルを持つロールベースのアクセス制御 (RBAC) の実装 +- MCP サーバーを MCP Auth で認可サーバーと連携 +- MCP Inspector でユーザー認証 (Authentication)・スコープ付きアクセストークンによるツール呼び出し + +他のチュートリアルやドキュメントもぜひご覧いただき、MCP Auth を最大限に活用してください。 \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/README.mdx b/i18n/ko/docusaurus-plugin-content-docs/current/README.mdx new file mode 100644 index 0000000..eae1d76 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/README.mdx @@ -0,0 +1,297 @@ +--- +sidebar_position: 1 +sidebar_label: 시작하기 +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# 시작하기 + +:::info MCP 인가 (Authorization) 명세 지원 +이 버전은 [MCP 인가 (Authorization) 명세 (버전 2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization)을 지원합니다. +::: + + +## 호환되는 OAuth 2.1 또는 OpenID Connect 제공자 선택하기 \{#choose-a-compatible-oauth-2-1-or-openid-connect-provider} + +MCP 명세는 인가 (Authorization)에 대해 [특정 요구사항](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#standards-compliance)을 가지고 있습니다. 인가 (Authorization) 메커니즘은 기존 명세를 기반으로 하며, 보안성과 상호 운용성을 보장하면서도 단순함을 유지하기 위해 선택된 일부 기능만 구현합니다: + +- OAuth 2.1 IETF DRAFT ([draft-ietf-oauth-v2-1-13](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13)) +- OAuth 2.0 인가 서버 메타데이터 ([RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)) +- OAuth 2.0 동적 클라이언트 등록 프로토콜 ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) +- OAuth 2.0 보호된 리소스 메타데이터 ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)) + +이 명세들은 함께 작동하여 MCP 구현을 위한 안전하고 표준화된 인가 (Authorization) 프레임워크를 제공합니다. + +[호환 MCP 제공자 목록](/provider-list)에서 사용 중인 제공자가 지원되는지 확인할 수 있습니다. + +## MCP Auth SDK 설치하기 \{#install-mcp-auth-sdk} + +MCP Auth는 Python과 TypeScript 모두에서 사용할 수 있습니다. 다른 언어나 프레임워크 지원이 필요하다면 알려주세요! + + + + +```bash +pip install mcpauth +``` + +또는 pipenv, poetry 등 선호하는 패키지 매니저를 사용할 수 있습니다. + + + + +```bash +npm install mcp-auth +``` + +또는 pnpm, yarn 등 선호하는 패키지 매니저를 사용할 수 있습니다. + + + + +## MCP Auth 초기화하기 \{#init-mcp-auth} + +첫 번째 단계는 리소스 식별자를 정의하고, 인증 (Authentication)에 신뢰할 수 있는 인가 (Authorization) 서버를 구성하는 것입니다. MCP Auth는 이제 리소스 서버 모드로 동작하며, OAuth 2.0 보호된 리소스 메타데이터 (RFC 9728)를 요구하는 최신 MCP 명세를 준수합니다. + +사용 중인 제공자가 다음을 준수한다면: + +- [OAuth 2.0 인가 서버 메타데이터](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +내장 함수를 사용해 메타데이터를 가져오고 MCP Auth 인스턴스를 초기화할 수 있습니다: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType, ResourceServerConfig, ResourceServerMetadata +from mcpauth.utils import fetch_server_config + +# 1. 리소스 식별자를 정의하고, 신뢰할 수 있는 인가 (Authorization) 서버의 설정을 가져옵니다. +resource_id = "https://api.example.com/notes" +auth_server_config = fetch_server_config("https://auth.logto.io/oidc", AuthServerType.OIDC) + +# 2. 리소스 서버 모드로 MCPAuth를 초기화합니다. +# `protected_resources`는 단일 객체 또는 여러 리소스의 리스트가 될 수 있습니다. +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +// 1. 리소스 식별자를 정의하고, 신뢰할 수 있는 인가 (Authorization) 서버의 설정을 가져옵니다. +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +// 2. 리소스 서버 모드로 MCPAuth를 초기화합니다. +// `protectedResources`는 단일 객체 또는 여러 리소스의 배열이 될 수 있습니다. +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +커스텀 메타데이터 URL, 데이터 변환, 수동 메타데이터 지정 등 인가 (Authorization) 서버 메타데이터를 구성하는 다른 방법은 [MCP Auth 구성의 다른 방법](./configure-server/mcp-auth.mdx#other-ways)을 참고하세요. + +## 보호된 리소스 메타데이터 엔드포인트 마운트하기 \{#mount-the-protected-resource-metadata-endpoint} + +최신 MCP 명세를 준수하기 위해, MCP Auth는 OAuth 2.0 보호된 리소스 메타데이터 엔드포인트 (RFC 9728)를 MCP 서버에 마운트합니다. 이 엔드포인트를 통해 클라이언트는 다음을 확인할 수 있습니다: + +- 어떤 인가 (Authorization) 서버가 보호된 리소스에 대해 유효한 토큰을 발급할 수 있는지 +- 각 리소스에 대해 지원되는 스코프 (Scope)는 무엇인지 +- 올바른 토큰 검증에 필요한 기타 메타데이터 + +엔드포인트 경로는 리소스 식별자의 경로 컴포넌트에 따라 자동으로 결정됩니다: + +- **경로 없음**: `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **경로 있음**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + +MCP 서버는 이제 **리소스 서버**로 동작하며, 토큰을 검증하고 보호된 리소스의 메타데이터를 제공하지만, 인증 (Authentication) 및 인가 (Authorization)는 전적으로 외부 인가 (Authorization) 서버에 의존합니다. + +SDK에서 제공하는 메서드를 사용해 이 엔드포인트를 마운트할 수 있습니다: + + + + +```python +from starlette.applications import Starlette + +# 보호된 리소스 메타데이터를 제공하는 라우터를 마운트합니다. +# 리소스 "https://api.example.com" → 엔드포인트: /.well-known/oauth-protected-resource +# 리소스 "https://api.example.com/notes" → 엔드포인트: /.well-known/oauth-protected-resource/notes +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// 보호된 리소스 메타데이터를 제공하는 라우터를 마운트합니다. +// 리소스 "https://api.example.com" → 엔드포인트: /.well-known/oauth-protected-resource +// 리소스 "https://api.example.com/notes" → 엔드포인트: /.well-known/oauth-protected-resource/notes +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + + +## Bearer 인증 (Authentication) 미들웨어 사용하기 \{#use-the-bearer-auth-middleware} + +MCP Auth 인스턴스를 초기화한 후, Bearer 인증 (Authentication) 미들웨어를 적용하여 MCP 라우트를 보호할 수 있습니다. 이제 미들웨어는 엔드포인트가 속한 리소스를 지정해야 하며, 이를 통해 올바른 토큰 검증이 가능합니다: + +:::note 대상 (Audience) 검증 +`audience` 파라미터는 안전한 토큰 검증을 위해 OAuth 2.0 명세에서 **필수**입니다. 그러나 아직 리소스 식별자를 지원하지 않는 인가 (Authorization) 서버와의 호환성을 위해 현재는 **선택 사항**입니다. 보안을 위해 **가능한 경우 항상 audience 파라미터를 포함**하세요. 향후 버전에서는 명세 준수를 위해 audience 검증이 필수로 적용될 예정입니다. +::: + + + + +```python +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount + +# 리소스별 정책으로 MCP 서버를 보호하는 미들웨어를 생성합니다. +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', + resource=resource_id, + audience=resource_id, # 보안을 위해 대상 (Audience) 검증 활성화 + required_scopes=['read:notes'] +)) + +# 보호된 리소스 메타데이터 라우터를 마운트하고 MCP 서버를 보호합니다. +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # Bearer 인증 (Authentication) 미들웨어로 MCP 서버 보호 + Mount("/", app=mcp.sse_app(), middleware=[bearer_auth]), + ], +) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// 보호된 리소스 메타데이터 라우터를 마운트합니다. +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// 리소스별 정책으로 API 엔드포인트를 보호합니다. +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, // 보안을 위해 대상 (Audience) 검증 활성화 + requiredScopes: ['read:notes'], + }), + (req, res) => { + // 토큰이 유효하면 `req.auth`에 클레임 (Claim) 정보가 채워집니다. + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); + +app.listen(3000); +``` + + + + +위 예시에서는 `jwt` 토큰 타입과 리소스 식별자를 지정합니다. 미들웨어는 해당 리소스에 대해 구성된 신뢰할 수 있는 인가 (Authorization) 서버를 기준으로 JWT 토큰을 자동으로 검증하고, 인증된 사용자의 정보를 채워줍니다. + +:::info +JWT (JSON Web Token)에 대해 들어본 적이 없으신가요? 걱정하지 마세요. 문서를 계속 읽으시면 필요할 때 설명해 드립니다. 빠른 소개가 필요하다면 [Auth Wiki](https://auth.wiki/jwt)를 참고하세요. +::: + +Bearer 인증 (Authentication) 구성에 대한 자세한 내용은 [Bearer 인증 (Authentication) 구성하기](./configure-server/bearer-auth.mdx)를 참고하세요. + +## MCP 구현에서 인증 (Authentication) 정보 가져오기 \{#retrieve-the-auth-info-in-your-mcp-implementation} + +Bearer 인증 (Authentication) 미들웨어가 적용되면, MCP 구현 내에서 인증된 사용자(또는 아이덴티티)의 정보를 접근할 수 있습니다: + + + + +Bearer 인증 (Authentication) 미들웨어가 적용된 후, MCP Auth는 인증된 사용자의 정보를 컨텍스트 변수에 저장합니다. MCP 도구 핸들러에서 다음과 같이 접근할 수 있습니다: + +```python +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP() + +# 앞선 예시와 같이 MCP Auth로 초기화 +# ... + +@mcp.tool() +def add(a: int, b: int): + """ + 두 숫자를 더하는 도구입니다. + 인증된 사용자의 정보는 컨텍스트에서 사용할 수 있습니다. + """ + auth_info = mcp_auth.auth_info # 현재 컨텍스트에서 인증 (Authentication) 정보 접근 + if auth_info: + print(f"Authenticated user: {auth_info.claims}") + return a + b +``` + + + + +도구 핸들러의 두 번째 인자는 인증된 사용자 정보를 포함하는 `authInfo` 객체를 제공합니다: + +```ts +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { z } from 'zod'; + +const server = new McpServer(/* ... */); + +// 앞선 예시와 같이 MCP Auth로 초기화 +// ... + +server.tool('add', { a: z.number(), b: z.number() }, async ({ a, b }, { authInfo }) => { + // 이제 `authInfo` 객체를 사용해 인증 (Authentication) 정보를 접근할 수 있습니다 +}); +``` + + + + +## 다음 단계 \{#next-steps} + +MCP Auth를 MCP 서버와 통합하는 방법과 MCP 클라이언트에서 인증 (Authentication) 플로우를 처리하는 방법에 대한 엔드 투 엔드 예제를 계속해서 읽어보세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx b/i18n/ko/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx new file mode 100644 index 0000000..da756f6 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx @@ -0,0 +1,280 @@ +--- +sidebar_position: 2 +sidebar_label: Bearer auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# MCP 서버에서 Bearer 인증 (Authentication) 구성하기 + +최신 MCP 명세에 따르면, MCP 서버는 보호된 리소스에 대한 액세스 토큰 (Access token) 을 검증하는 **리소스 서버 (Resource Server)** 역할을 합니다. MCP Auth는 Bearer 인가 (Authorization) 를 구성하는 다양한 방법을 제공합니다: + +- [JWT (JSON Web Token)](https://auth.wiki/jwt) 모드: 클레임 (Claim) 검증을 통해 JWT를 검증하는 내장 인가 방식입니다. +- 커스텀 모드: 직접 인가 로직을 구현할 수 있습니다. + +Bearer 인증 (Authentication) 미들웨어는 이제 엔드포인트가 속한 리소스를 지정해야 하며, 이를 통해 구성된 인가 서버에 대해 적절한 토큰 검증이 가능합니다. + +## JWT 모드로 Bearer 인증 (Authentication) 구성하기 \{#configure-bearer-auth-with-jwt-mode} + +OAuth / OIDC 제공자가 인가를 위해 JWT를 발급하는 경우, MCP Auth의 내장 JWT 모드를 사용할 수 있습니다. 이 모드는 JWT의 서명, 만료, 그리고 지정한 기타 클레임 (Claim) 을 검증한 후, 인증 (Authentication) 정보를 요청 컨텍스트에 채워 MCP 구현에서 추가 처리를 할 수 있도록 합니다. + +### 스코프 (Scope) 검증 \{#scope-validation} + +다음은 기본적인 스코프 (Scope) 검증 예시입니다: + + + + +```python +from mcpauth import MCPAuth +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP("MyMCPServer") +mcp_auth = MCPAuth( + # Initialize with your auth server config +) +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", # 이 엔드포인트가 속한 리소스를 지정하세요 + audience="https://api.example.com", # 보안을 위해 대상 (Audience) 검증 활성화 + required_scopes=["read", "write"] # [!code highlight] +) + +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + /* ... */ +}); +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // 이 엔드포인트가 속한 리소스를 지정하세요 + audience: 'https://api.example.com', // 보안을 위해 대상 (Audience) 검증 활성화 + requiredScopes: ['read', 'write'] // [!code highlight] +}); + +app.use('/mcp', bearerAuth, (req, res) => { + // 이제 `req.auth`에 인증 (Authentication) 정보가 포함됩니다 + console.log(req.auth); +}); +``` + + + + +위 예시에서 JWT에 `read` 및 `write` 스코프 (Scope) 가 필요함을 지정했습니다. JWT에 이 중 **하나라도** 포함되어 있지 않으면, 요청은 403 Forbidden 오류로 거부됩니다. + +### 대상 (Audience) 검증 (RFC 8707) \{#audience-validation-rfc-8707} + +보안 토큰 검증을 위해서는 항상 `audience` 파라미터를 지정하여 대상 (Audience) 검증을 포함해야 합니다. 이는 JWT의 `aud` (대상) 클레임 (Claim) 을 검증하여 토큰이 해당 MCP 서버 리소스에 대해 발급되었는지 확인합니다. + +:::note Audience Validation +`audience` 파라미터는 보안 토큰 검증을 위해 OAuth 2.0 명세에서 **필수**입니다. 그러나, 아직 리소스 식별자를 지원하지 않는 인가 서버와의 호환성을 위해 현재는 **선택 사항**입니다. 보안을 위해 **가능한 경우 항상 audience 파라미터를 포함하세요**. 향후 버전에서는 명세 준수를 위해 audience 검증이 필수로 적용될 예정입니다. +::: + +대상 (Audience) 값은 일반적으로 리소스 식별자와 일치해야 합니다: + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", # 이 엔드포인트가 속한 리소스를 지정하세요 + audience="https://api.example.com", # 보안을 위해 대상 (Audience) 검증 활성화 [!code highlight] + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // 이 엔드포인트가 속한 리소스를 지정하세요 + audience: 'https://api.example.com', // 보안을 위해 대상 (Audience) 검증 활성화 [!code highlight] + requiredScopes: ['read', 'write'], +}); +``` + + + + +위 예시에서 MCP Auth는 JWT의 `aud` 클레임 (Claim) 과 필요한 스코프 (Scope) 를 **모두** 검증합니다. + +### JWT 검증에 커스텀 옵션 제공하기 \{#provide-custom-options-to-the-jwt-verification} + +기본 JWT 검증 라이브러리에 커스텀 옵션을 제공할 수도 있습니다: + + + + +Python SDK에서는 JWT 검증을 위해 [PyJWT](https://pyjwt.readthedocs.io/en/stable/)를 사용합니다. 다음 옵션을 사용할 수 있습니다: + +- `leeway`: JWT 만료 시간 검증 시 허용할 여유 시간 (초 단위). 기본값은 60초입니다. + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", + audience="https://api.example.com", + required_scopes=["read", "write"], + leeway=10, # 10초의 여유 시간을 허용하여 시계 오차를 줄임 [!code highlight] +) +``` + + + + +Node.js SDK에서는 JWT 검증을 위해 [jose](https://github.com/panva/jose) 라이브러리를 사용합니다. 다음 옵션을 제공할 수 있습니다: + +- `jwtVerify`: JWT 검증 과정의 옵션 (`jose`의 `jwtVerify` 함수). +- `remoteJwtSet`: 원격 JWT 세트 가져오기 옵션 (`jose`의 `createRemoteJWKSet` 함수). + +```ts {5-10} +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', + requiredScopes: ['read', 'write'], + jwtVerify: { + clockTolerance: 60, // 60초의 시계 오차 허용 + }, + remoteJwtSet: { + timeoutDuration: 10 * 1000, // 원격 JWT 세트 가져오기 10초 타임아웃 + }, +}); +``` + + + + +## 커스텀 검증으로 Bearer 인증 (Authentication) 구성하기 \{#configure-bearer-auth-with-custom-verification} + +OAuth / OIDC 제공자가 JWT를 발급하지 않거나, 직접 인가 로직을 구현하고 싶은 경우, MCP Auth는 커스텀 검증 함수를 만들 수 있도록 지원합니다: + +:::info +Bearer 인증 (Authentication) 미들웨어는 발급자 (`iss`), 대상 (`aud`), 그리고 필요한 스코프 (`scope`) 를 검증 결과와 비교합니다. 따라서 커스텀 검증 함수에서 이 검증을 직접 구현할 필요가 없습니다. 토큰의 유효성 (예: 서명, 만료 등) 검증과 인증 (Authentication) 정보 객체 반환에 집중하면 됩니다. +::: + + + + +```python +from mcpauth.exceptions import MCPAuthJwtVerificationException, MCPAuthJwtVerificationExceptionCode +from mcpauth.types import AuthInfo + +async def custom_verification(token: str) -> AuthInfo: + # 여기서 커스텀 검증 로직을 구현하세요 + info = await verify_token(token) + if not info: + raise MCPAuthJwtVerificationException( + MCPAuthJwtVerificationExceptionCode.JWT_VERIFICATION_FAILED + ) + return info # 인증 (Authentication) 정보 객체 반환 + +bearer_auth = mcp_auth.bearer_auth_middleware( + custom_verification, + resource="https://api.example.com", + audience="https://api.example.com", # 보안을 위해 대상 (Audience) 검증 활성화 + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth( + async (token) => { + // 여기서 커스텀 검증 로직을 구현하세요 + const info = await verifyToken(token); + if (!info) { + throw new MCPAuthJwtVerificationError('jwt_verification_failed'); + } + return info; // 인증 (Authentication) 정보 객체 반환 + }, + { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // 보안을 위해 대상 (Audience) 검증 활성화 + requiredScopes: ['read', 'write'] + } +); +``` + + + + +## MCP 서버에 Bearer 인증 (Authentication) 적용하기 \{#apply-bearer-auth-in-your-mcp-server} + +MCP 서버를 Bearer 인증 (Authentication) 으로 보호하려면, MCP 서버 인스턴스에 Bearer 인증 (Authentication) 미들웨어를 적용해야 합니다. + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", + audience="https://api.example.com", # 보안을 위해 대상 (Audience) 검증 활성화 + required_scopes=["read", "write"] +) +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```js +const app = express(); +app.use(mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // 보안을 위해 대상 (Audience) 검증 활성화 + requiredScopes: ['read', 'write'] +})); +``` + + + + +이렇게 하면 모든 들어오는 요청이 구성된 Bearer 인증 (Authentication) 설정에 따라 인증 (Authentication) 및 인가 (Authorization) 되며, 인증 (Authentication) 정보가 요청 컨텍스트에서 사용할 수 있게 됩니다. + +이후 MCP 서버 구현에서 해당 정보를 사용할 수 있습니다: + + + + +```python +@mcp.tool() +async def whoami() -> dict: + # `mcp_auth.auth_info`는 현재 요청의 컨텍스트 객체입니다 + auth_info = mcp_auth.auth_info + print(f"Authenticated user: {auth_info.subject}") + return {"subject": auth_info.subject} +``` + + + + +```js +// `authInfo`는 `req.auth` 객체에서 전달됩니다 +server.tool('whoami', ({ authInfo }) => { + console.log(`Authenticated user: ${authInfo.subject}`); + return { subject: authInfo.subject }; +}); +``` + + + diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx b/i18n/ko/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx new file mode 100644 index 0000000..8e87262 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx @@ -0,0 +1,290 @@ +--- +sidebar_position: 1 +sidebar_label: MCP Auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# MCP 서버에서 MCP Auth 구성하기 + +최신 [MCP 명세 (2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18)에 따르면, MCP 서버는 외부 인가 (Authorization) 서버에서 발급된 액세스 토큰 (Access token)을 검증하는 **리소스 서버 (Resource Server)** 역할을 합니다. + +MCP Auth를 구성하려면 두 가지 주요 단계를 거쳐야 합니다: +1. **인가 (Authorization) 서버 메타데이터 구성** - 어떤 인가 (Authorization) 서버가 MCP 서버에 대해 유효한 토큰을 발급할 수 있는지 정의하고, MCP 클라이언트가 액세스 토큰 (Access token)을 어디서 받아야 하는지 안내합니다. +2. **보호된 리소스 메타데이터 구성** - MCP 서버를 지원하는 스코프 (Scope)와 함께 보호된 리소스로 정의합니다. + +## 1단계: 인가 (Authorization) 서버 메타데이터 구성하기 \{#configure-authorization-server-metadata} + +### 메타데이터 자동 가져오기 \{#automatic-metadata-fetching} + +인가 (Authorization) 서버 메타데이터를 구성하는 가장 쉬운 방법은 well-known URL에서 메타데이터를 가져오는 내장 함수를 사용하는 것입니다. 만약 제공자가 다음 표준 중 하나를 준수한다면: + +- [OAuth 2.0 인가 (Authorization) 서버 메타데이터](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +`fetchServerConfig`를 사용하여 `issuer` URL을 제공하면 메타데이터를 자동으로 가져올 수 있습니다: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +# 인가 (Authorization) 서버 메타데이터 가져오기 +auth_server_config = fetch_server_config( + "https://auth.logto.io/oidc", + AuthServerType.OIDC # 또는 AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +// 인가 (Authorization) 서버 메타데이터 가져오기 +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); // 또는 'oauth' +``` + + + + +issuer에 경로가 포함된 경우, OAuth 2.0과 OpenID Connect에서 동작이 약간 다릅니다: + +- **OAuth 2.0**: well-known URL이 issuer의 **도메인**에 추가됩니다. 예를 들어, issuer가 `https://my-project.logto.app/oauth`라면, well-known URL은 `https://auth.logto.io/.well-known/oauth-authorization-server/oauth`가 됩니다. +- **OpenID Connect**: well-known URL이 **issuer**에 직접 추가됩니다. 예를 들어, issuer가 `https://my-project.logto.app/oidc`라면, well-known URL은 `https://auth.logto.io/oidc/.well-known/openid-configuration`이 됩니다. + +### 인가 (Authorization) 서버 메타데이터를 구성하는 다른 방법 \{#other-ways} + +#### 사용자 지정 데이터 변환 \{#custom-data-transpilation} + +경우에 따라 제공자가 반환하는 메타데이터가 예상 형식과 다를 수 있습니다. 제공자가 표준을 준수한다고 확신한다면, `transpile_data` 옵션을 사용하여 메타데이터를 사용하기 전에 수정할 수 있습니다: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +auth_server_config = fetch_server_config( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfig('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +이렇게 하면 MCP Auth에서 사용하기 전에 메타데이터 객체를 수정할 수 있습니다. 예를 들어, 필드를 추가하거나 제거하고, 값을 변경하거나, 다른 형식으로 변환할 수 있습니다. + +#### 특정 URL에서 메타데이터 가져오기 \{#fetch-metadata-from-a-specific-url} + +제공자가 표준이 아닌 특정 메타데이터 URL을 제공하는 경우에도 비슷하게 사용할 수 있습니다: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC # 또는 AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfigByWellKnownUrl } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { type: 'oidc' }); // 또는 'oauth' +``` + + + + +#### 특정 URL에서 사용자 지정 데이터 변환과 함께 메타데이터 가져오기 \{#fetch-metadata-from-a-specific-url-with-custom-data-transpilation} + +경우에 따라 제공자의 응답이 잘못되었거나 예상 메타데이터 형식과 다를 수 있습니다. 제공자가 표준을 준수한다고 확신한다면, config 옵션을 통해 메타데이터를 변환할 수 있습니다: + + + + +```python +from mcpauth.config import AuthServerType, fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +#### 메타데이터를 수동으로 제공하기 \{#manually-provide-metadata} + +제공자가 메타데이터 가져오기를 지원하지 않는 경우, 메타데이터 객체를 수동으로 제공할 수 있습니다: + + + + +```python +from mcpauth.config import AuthServerConfig, AuthServerType, AuthorizationServerMetadata + +auth_server_config = AuthServerConfig( + type=AuthServerType.OIDC, # 또는 AuthServerType.OAUTH + metadata=AuthorizationServerMetadata( + issuer='', + authorization_endpoint='', + # ... 기타 메타데이터 필드 + ), +) +``` + + + + +```ts +const authServerConfig = { + metadata: { + issuer: '', + // 메타데이터 필드는 camelCase여야 합니다 + authorizationEndpoint: '', + // ... 기타 메타데이터 필드 + }, + type: 'oidc', // 또는 'oauth' +}; +``` + + + + +## 2단계: 보호된 리소스 메타데이터 구성하기 \{#configure-protected-resource-metadata} + +인가 (Authorization) 서버 메타데이터를 구성한 후, 보호된 리소스 메타데이터를 정의하여 MCPAuth를 리소스 서버 모드로 초기화해야 합니다. + +이 단계는 [RFC 9728 (OAuth 2.0 보호된 리소스 메타데이터)](https://datatracker.ietf.org/doc/html/rfc9728) 명세를 따라 MCP 서버를 보호된 리소스로 설명합니다: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import ResourceServerConfig, ResourceServerMetadata + +# 리소스 식별자 정의 +resource_id = "https://api.example.com/notes" + +# 리소스 서버 모드로 MCPAuth 초기화 +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], # 1단계에서 구성한 config 사용 + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth } from 'mcp-auth'; + +// 리소스 식별자 정의 +const resourceIdentifier = 'https://api.example.com/notes'; + +// 리소스 서버 모드로 MCPAuth 초기화 +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], // 1단계에서 구성한 config 사용 + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +여러 리소스가 있는 경우, 각각의 메타데이터 구성을 가진 보호된 리소스 배열을 제공할 수 있습니다. + +위의 구성은 기본 설정을 다룹니다. 더 고급 메타데이터 파라미터는 [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata)을 참고하세요. + +## 3단계: 보호된 리소스 메타데이터 엔드포인트 마운트하기 \{#mount-the-protected-resource-metadata-endpoint} + +라우터를 마운트하여 보호된 리소스 메타데이터 엔드포인트를 제공합니다. 엔드포인트 경로는 리소스 식별자의 path 컴포넌트에 따라 자동으로 결정됩니다: + +- **경로 없음**: `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **경로 있음**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + + + + +```python +from starlette.applications import Starlette +from mcpauth import MCPAuth + +mcp_auth = MCPAuth({/* ... */}) + +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +const mcpAuth = new MCPAuth({/* ... */}); + +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/README.md new file mode 100644 index 0000000..f7e3467 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/README.md @@ -0,0 +1,59 @@ +--- +sidebar_label: Node.js SDK +--- + +# MCP Auth Node.js SDK 참고 + +## 클래스 {#classes} + +- [MCPAuth](/references/js/classes/MCPAuth.md) +- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) +- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) +- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) +- [MCPAuthError](/references/js/classes/MCPAuthError.md) +- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) + +## 타입 별칭 {#type-aliases} + +- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) +- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) +- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) +- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) +- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) +- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) +- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) +- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) +- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) +- [AuthServerType](/references/js/type-aliases/AuthServerType.md) +- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) +- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) +- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) +- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) +- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) +- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) +- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) +- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) +- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) +- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) +- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) +- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) + +## 변수 {#variables} + +- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) +- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) +- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) +- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) +- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) +- [defaultValues](/references/js/variables/defaultValues.md) +- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) +- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) +- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) +- [validateServerConfig](/references/js/variables/validateServerConfig.md) + +## 함수 {#functions} + +- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) +- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) +- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) +- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md new file mode 100644 index 0000000..233b0d2 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md @@ -0,0 +1,281 @@ +--- +sidebar_label: MCPAuth +--- + +# 클래스: MCPAuth + +mcp-auth 라이브러리의 주요 클래스입니다. 보호된 리소스에 대한 인증 (Authentication) 정책을 생성하기 위한 팩토리이자 레지스트리 역할을 합니다. + +서버 구성으로 초기화되며, 토큰 기반 인증 (Authentication)을 위한 Express 미들웨어를 생성하는 `bearerAuth` 메서드를 제공합니다. + +## 예시 {#example} + +### `리소스 서버` 모드에서의 사용 {#usage-in-resource-server-mode} + +신규 애플리케이션에 권장되는 접근 방식입니다. + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); + +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +const mcpAuth = new MCPAuth({ + // `protectedResources`는 단일 구성 객체 또는 객체 배열이 될 수 있습니다. + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); + +// 보호된 리소스 메타데이터를 처리하는 라우터를 마운트합니다. +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// 구성된 리소스에 대한 API 엔드포인트를 보호합니다. +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, // 이 엔드포인트가 속한 리소스를 지정합니다. + audience: resourceIdentifier, // 선택적으로 'aud' 클레임을 검증합니다. + requiredScopes: ['read:notes'], + }), + (req, res) => { + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); +``` + +### `인가 (Authorization) 서버` 모드의 레거시 사용법 (더 이상 권장되지 않음) {#legacy-usage-in-authorization-server-mode-deprecated} + +이 방식은 하위 호환성을 위해 지원됩니다. + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + server: await fetchServerConfig( + 'https://auth.logto.io/oidc', + { type: 'oidc' } + ), +}); + +// 레거시 인가 (Authorization) 서버 메타데이터를 처리하는 라우터를 마운트합니다. +app.use(mcpAuth.delegatedRouter()); + +// 기본 정책을 사용하여 엔드포인트를 보호합니다. +app.get( + '/mcp', + mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), + (req, res) => { + console.log('Auth info:', req.auth); + // 여기서 MCP 요청을 처리합니다. + }, +); +``` + +## 생성자 {#constructors} + +### 생성자 {#constructor} + +```ts +new MCPAuth(config: MCPAuthConfig): MCPAuth; +``` + +MCPAuth 인스턴스를 생성합니다. +전체 구성을 사전에 검증하여 오류 발생 시 빠르게 실패하도록 합니다. + +#### 매개변수 {#parameters} + +##### config {#config} + +[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) + +인증 (Authentication) 구성입니다. + +#### 반환값 {#returns} + +`MCPAuth` + +## 속성 {#properties} + +### config {#config} + +```ts +readonly config: MCPAuthConfig; +``` + +인증 (Authentication) 구성입니다. + +## 메서드 {#methods} + +### bearerAuth() {#bearerauth} + +#### 호출 시그니처 {#call-signature} + +```ts +bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; +``` + +요청의 `Authorization` 헤더에 있는 액세스 토큰 (Access token)을 검증하는 Bearer 인증 (Authentication) 핸들러 (Express 미들웨어)를 생성합니다. + +##### 매개변수 {#parameters} + +###### verifyAccessToken {#verifyaccesstoken} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +액세스 토큰 (Access token)을 검증하는 함수입니다. 문자열로 액세스 토큰을 받아 검증 결과로 해결되는 프로미스(또는 값)를 반환해야 합니다. + +**참고** + +`verifyAccessToken` 함수의 타입 정의는 [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md)에서 확인하세요. + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> + +Bearer 인증 (Authentication) 핸들러의 선택적 구성입니다. + +**참고** + +사용 가능한 구성 옵션(단, `verifyAccessToken` 및 `issuer` 제외)은 [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md)에서 확인하세요. + +##### 반환값 {#returns} + +`RequestHandler` + +액세스 토큰 (Access token)을 검증하고 검증 결과를 요청 객체 (`req.auth`)에 추가하는 Express 미들웨어 함수입니다. + +##### 참고 {#see} + +구현 세부사항 및 확장된 `req.auth` (`AuthInfo`) 객체 타입은 [handleBearerAuth](/references/js/functions/handleBearerAuth.md)에서 확인하세요. + +#### 호출 시그니처 {#call-signature} + +```ts +bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; +``` + +사전 정의된 검증 모드를 사용하여 요청의 `Authorization` 헤더에 있는 액세스 토큰 (Access token)을 검증하는 Bearer 인증 (Authentication) 핸들러 (Express 미들웨어)를 생성합니다. + +`'jwt'` 모드에서는 인가 (Authorization) 서버의 JWKS URI에서 JWK Set을 사용하여 JWT 검증 함수를 생성합니다. + +##### 매개변수 {#parameters} + +###### mode {#mode} + +`"jwt"` + +액세스 토큰 (Access token) 검증 모드입니다. 현재는 'jwt'만 지원됩니다. + +**참고** + +사용 가능한 모드는 [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md)에서 확인하세요. + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` + +JWT 검증 옵션 및 원격 JWK set 옵션을 포함한 Bearer 인증 (Authentication) 핸들러의 선택적 구성입니다. + +**참고** + + - JWT 검증을 위한 사용 가능한 구성 옵션은 VerifyJwtConfig에서 확인하세요. + - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md)에서 사용 가능한 구성 옵션(단, `verifyAccessToken` 및 `issuer` 제외)을 확인하세요. + +##### 반환값 {#returns} + +`RequestHandler` + +액세스 토큰 (Access token)을 검증하고 검증 결과를 요청 객체 (`req.auth`)에 추가하는 Express 미들웨어 함수입니다. + +##### 참고 {#see} + +구현 세부사항 및 확장된 `req.auth` (`AuthInfo`) 객체 타입은 [handleBearerAuth](/references/js/functions/handleBearerAuth.md)에서 확인하세요. + +##### 예외 {#throws} + +'jwt' 모드 사용 시 서버 메타데이터에 JWKS URI가 제공되지 않은 경우 예외가 발생합니다. + +*** + +### ~~delegatedRouter()~~ {#delegatedrouter} + +```ts +delegatedRouter(): Router; +``` + +인스턴스에 제공된 메타데이터로 레거시 OAuth 2.0 인가 (Authorization) 서버 메타데이터 엔드포인트 +(`/.well-known/oauth-authorization-server`)를 제공하는 위임 라우터를 생성합니다. + +#### 반환값 {#returns} + +`Router` + +인스턴스에 제공된 메타데이터로 OAuth 2.0 인가 (Authorization) 서버 메타데이터 엔드포인트를 제공하는 라우터입니다. + +#### 더 이상 사용되지 않음 {#deprecated} + +대신 [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter)를 사용하세요. + +#### 예시 {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth: MCPAuth; // 초기화되어 있다고 가정 +app.use(mcpAuth.delegatedRouter()); +``` + +#### 예외 {#throws} + +`리소스 서버` 모드에서 호출 시 예외가 발생합니다. + +*** + +### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} + +```ts +protectedResourceMetadataRouter(): Router; +``` + +구성된 모든 리소스에 대해 OAuth 2.0 보호된 리소스 메타데이터 엔드포인트를 제공하는 라우터를 생성합니다. + +이 라우터는 구성에 제공된 각 리소스 식별자에 대해 올바른 `.well-known` 엔드포인트를 자동으로 생성합니다. + +#### 반환값 {#returns} + +`Router` + +OAuth 2.0 보호된 리소스 메타데이터 엔드포인트를 제공하는 라우터입니다. + +#### 예외 {#throws} + +`인가 (Authorization) 서버` 모드에서 호출 시 예외가 발생합니다. + +#### 예시 {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +// mcpAuth가 하나 이상의 `protectedResources` 구성으로 초기화되어 있다고 가정 +const mcpAuth: MCPAuth; +const app = express(); + +// 리소스 식별자에 따라 `/.well-known/oauth-protected-resource/...`에서 메타데이터를 제공합니다. +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md new file mode 100644 index 0000000..cc9b2bf --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md @@ -0,0 +1,242 @@ +--- +sidebar_label: MCPAuthAuthServerError +--- + +# 클래스: MCPAuthAuthServerError + +원격 인가 (Authorization) 서버에 문제가 있을 때 발생하는 오류입니다. + +## 상속 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 생성자 {#constructors} + +### 생성자 {#constructor} + +```ts +new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; +``` + +#### 매개변수 {#parameters} + +##### code {#code} + +[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### 반환값 {#returns} + +`MCPAuthAuthServerError` + +#### 오버라이드 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 프로퍼티 {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: AuthServerErrorCode; +``` + +스네이크 케이스 형식의 오류 코드입니다. + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthAuthServerError'; +``` + +#### 오버라이드 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 프로퍼티는 스택 트레이스가 수집하는 스택 프레임의 개수를 지정합니다 +(`new Error().stack` 또는 `Error.captureStackTrace(obj)`로 생성된 경우). + +기본값은 `10`이지만, 유효한 JavaScript 숫자로 설정할 수 있습니다. 값이 변경된 _이후_에 캡처된 모든 스택 트레이스에 영향을 미칩니다. + +숫자가 아닌 값이나 음수로 설정하면, 스택 트레이스는 프레임을 캡처하지 않습니다. + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 메서드 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +오류를 HTTP 응답에 적합한 JSON 형식으로 변환합니다. + +#### 매개변수 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +오류의 원인(cause)을 JSON 응답에 포함할지 여부입니다. +기본값은 `false`입니다. + +#### 반환값 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +`targetObject`에 `.stack` 프로퍼티를 생성하며, 접근 시 +`Error.captureStackTrace()`가 호출된 코드 위치를 나타내는 문자열을 반환합니다. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // `new Error().stack`과 유사 +``` + +트레이스의 첫 번째 줄은 +`${myObject.name}: ${myObject.message}`로 시작합니다. + +선택적 `constructorOpt` 인자는 함수입니다. 제공되면, `constructorOpt`를 포함하여 그 위의 모든 프레임이 +생성된 스택 트레이스에서 생략됩니다. + +`constructorOpt` 인자는 오류 생성의 구현 세부 정보를 사용자로부터 숨기고자 할 때 유용합니다. 예시: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 스택 트레이스를 두 번 계산하지 않도록 스택 트레이스 없이 오류 생성 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 함수 b 위에서 스택 트레이스 캡처 + Error.captureStackTrace(error, b); // 함수 c와 b는 스택 트레이스에 포함되지 않음 + throw error; +} + +a(); +``` + +#### 매개변수 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 반환값 {#returns} + +`void` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 매개변수 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 반환값 {#returns} + +`any` + +#### 참고 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md new file mode 100644 index 0000000..7a8c5ae --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md @@ -0,0 +1,237 @@ +--- +sidebar_label: MCPAuthBearerAuthError +--- + +# 클래스: MCPAuthBearerAuthError + +Bearer 토큰으로 인증 (Authentication)할 때 문제가 발생하면 발생하는 오류입니다. + +## 상속 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 생성자 {#constructors} + +### 생성자 {#constructor} + +```ts +new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; +``` + +#### 매개변수 {#parameters} + +##### code {#code} + +[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) + +##### cause? {#cause} + +[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) + +#### 반환값 {#returns} + +`MCPAuthBearerAuthError` + +#### 오버라이드 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 프로퍼티 {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: MCPAuthBearerAuthErrorDetails; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: BearerAuthErrorCode; +``` + +스네이크 케이스 형식의 오류 코드입니다. + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthBearerAuthError'; +``` + +#### 오버라이드 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 프로퍼티는 스택 트레이스가 수집하는 스택 프레임의 개수를 지정합니다 (`new Error().stack` 또는 `Error.captureStackTrace(obj)`로 생성된 경우). + +기본값은 `10`이지만, 유효한 JavaScript 숫자로 설정할 수 있습니다. 값이 변경된 이후에 캡처된 모든 스택 트레이스에 영향을 미칩니다. + +숫자가 아닌 값이나 음수로 설정하면, 스택 트레이스는 프레임을 캡처하지 않습니다. + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 메서드 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +오류를 HTTP 응답에 적합한 JSON 형식으로 변환합니다. + +#### 매개변수 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +JSON 응답에 오류의 원인(cause)을 포함할지 여부입니다. 기본값은 `false`입니다. + +#### 반환값 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 오버라이드 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +`targetObject`에 `.stack` 프로퍼티를 생성하며, 접근 시 `Error.captureStackTrace()`가 호출된 코드 위치를 나타내는 문자열을 반환합니다. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // `new Error().stack`과 유사 +``` + +트레이스의 첫 번째 줄은 `${myObject.name}: ${myObject.message}`로 시작합니다. + +선택적 `constructorOpt` 인자는 함수입니다. 제공되면, `constructorOpt`를 포함하여 그 위의 모든 프레임이 생성된 스택 트레이스에서 생략됩니다. + +`constructorOpt` 인자는 오류 생성의 구현 세부 정보를 사용자로부터 숨기는 데 유용합니다. 예시: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 스택 트레이스를 두 번 계산하지 않도록 스택 트레이스 없는 오류 생성 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 함수 b 위에서 스택 트레이스 캡처 + Error.captureStackTrace(error, b); // 함수 c와 b는 스택 트레이스에 포함되지 않음 + throw error; +} + +a(); +``` + +#### 매개변수 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 반환값 {#returns} + +`void` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 매개변수 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 반환값 {#returns} + +`any` + +#### 참고 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md new file mode 100644 index 0000000..3748904 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthConfigError +--- + +# 클래스: MCPAuthConfigError + +mcp-auth의 구성 문제 발생 시 발생하는 오류입니다. + +## 상속 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 생성자 {#constructors} + +### 생성자 {#constructor} + +```ts +new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; +``` + +#### 매개변수 {#parameters} + +##### code {#code} + +`string` + +스네이크 케이스(snake_case) 형식의 오류 코드입니다. + +##### message {#message} + +`string` + +오류에 대한 사람이 읽을 수 있는 설명입니다. + +#### 반환값 {#returns} + +`MCPAuthConfigError` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 프로퍼티 {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +스네이크 케이스(snake_case) 형식의 오류 코드입니다. + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthConfigError'; +``` + +#### 오버라이드 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 프로퍼티는 스택 트레이스가 수집하는 스택 프레임의 개수를 지정합니다 +(`new Error().stack` 또는 `Error.captureStackTrace(obj)`로 생성된 경우). + +기본값은 `10`이지만, 유효한 JavaScript 숫자로 설정할 수 있습니다. +값이 변경된 이후에 캡처된 모든 스택 트레이스에 영향을 미칩니다. + +숫자가 아닌 값이나 음수로 설정하면, 스택 트레이스는 프레임을 캡처하지 않습니다. + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 메서드 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +오류를 HTTP 응답에 적합한 JSON 형식으로 변환합니다. + +#### 매개변수 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +JSON 응답에 오류의 원인(cause)을 포함할지 여부입니다. +기본값은 `false`입니다. + +#### 반환값 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +`targetObject`에 `.stack` 프로퍼티를 생성하며, +접근 시 `Error.captureStackTrace()`가 호출된 코드 위치를 나타내는 문자열을 반환합니다. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // `new Error().stack`과 유사 +``` + +트레이스의 첫 번째 줄은 +`${myObject.name}: ${myObject.message}`로 시작합니다. + +선택적 `constructorOpt` 인자는 함수입니다. +제공되면, `constructorOpt`를 포함하여 그 위의 모든 프레임이 +생성된 스택 트레이스에서 생략됩니다. + +`constructorOpt` 인자는 오류 생성의 구현 세부 정보를 사용자로부터 숨길 때 유용합니다. 예시: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 스택 트레이스를 두 번 계산하지 않도록 스택 트레이스 없이 오류 생성 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // b 함수 위에서 스택 트레이스 캡처 + Error.captureStackTrace(error, b); // c, b 함수 모두 스택 트레이스에 포함되지 않음 + throw error; +} + +a(); +``` + +#### 매개변수 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 반환값 {#returns} + +`void` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 매개변수 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 반환값 {#returns} + +`any` + +#### 참고 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md new file mode 100644 index 0000000..371b332 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md @@ -0,0 +1,261 @@ +--- +sidebar_label: MCPAuthError +--- + +# 클래스: MCPAuthError + +모든 mcp-auth 오류의 기본 클래스입니다. + +MCP 인증 (Authentication) 및 인가 (Authorization)와 관련된 오류를 표준화된 방식으로 처리할 수 있도록 합니다. + +## 상속 {#extends} + +- `Error` + +## 확장 클래스 {#extended-by} + +- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) +- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) +- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) +- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) + +## 생성자 {#constructors} + +### 생성자 {#constructor} + +```ts +new MCPAuthError(code: string, message: string): MCPAuthError; +``` + +#### 매개변수 {#parameters} + +##### code {#code} + +`string` + +스네이크 케이스(snake_case) 형식의 오류 코드입니다. + +##### message {#message} + +`string` + +오류에 대한 사람이 읽을 수 있는 설명입니다. + +#### 반환값 {#returns} + +`MCPAuthError` + +#### 오버라이드 {#overrides} + +```ts +Error.constructor +``` + +## 프로퍼티 {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### 상속됨 {#inherited-from} + +```ts +Error.cause +``` + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +스네이크 케이스(snake_case) 형식의 오류 코드입니다. + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 상속됨 {#inherited-from} + +```ts +Error.message +``` + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthError'; +``` + +#### 오버라이드 {#overrides} + +```ts +Error.name +``` + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 상속됨 {#inherited-from} + +```ts +Error.stack +``` + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 프로퍼티는 스택 트레이스( `new Error().stack` 또는 `Error.captureStackTrace(obj)`로 생성됨 )에서 수집되는 스택 프레임의 개수를 지정합니다. + +기본값은 `10`이지만, 유효한 JavaScript 숫자로 설정할 수 있습니다. 값이 변경된 이후에 캡처되는 모든 스택 트레이스에 영향을 미칩니다. + +숫자가 아닌 값이나 음수로 설정하면, 스택 트레이스는 프레임을 캡처하지 않습니다. + +#### 상속됨 {#inherited-from} + +```ts +Error.stackTraceLimit +``` + +## 메서드 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +오류를 HTTP 응답에 적합한 JSON 형식으로 변환합니다. + +#### 매개변수 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +JSON 응답에 오류의 원인(cause)을 포함할지 여부입니다. +기본값은 `false`입니다. + +#### 반환값 {#returns} + +`Record`\<`string`, `unknown`\> + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +`targetObject`에 `.stack` 프로퍼티를 생성하며, 접근 시 +`Error.captureStackTrace()`가 호출된 코드 위치를 나타내는 문자열을 반환합니다. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // `new Error().stack`과 유사 +``` + +트레이스의 첫 번째 줄은 +`${myObject.name}: ${myObject.message}`로 시작합니다. + +선택적 `constructorOpt` 인자는 함수입니다. 제공되면, `constructorOpt`를 포함하여 그 위의 모든 프레임이 생성된 스택 트레이스에서 생략됩니다. + +`constructorOpt` 인자는 오류 생성의 구현 세부 정보를 사용자에게 숨기고 싶을 때 유용합니다. 예시: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 스택 트레이스를 두 번 계산하지 않기 위해 스택 트레이스 없는 오류 생성 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 함수 b 위에서 스택 트레이스 캡처 + Error.captureStackTrace(error, b); // 함수 c와 b는 스택 트레이스에 포함되지 않음 + throw error; +} + +a(); +``` + +#### 매개변수 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 반환값 {#returns} + +`void` + +#### 상속됨 {#inherited-from} + +```ts +Error.captureStackTrace +``` + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 매개변수 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 반환값 {#returns} + +`any` + +#### 참고 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 상속됨 {#inherited-from} + +```ts +Error.prepareStackTrace +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md new file mode 100644 index 0000000..38e3730 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md @@ -0,0 +1,240 @@ +--- +sidebar_label: MCPAuthTokenVerificationError +--- + +# 클래스: MCPAuthTokenVerificationError + +토큰을 검증하는 과정에서 문제가 발생했을 때 발생하는 오류입니다. + +## 상속 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 생성자 {#constructors} + +### 생성자 {#constructor} + +```ts +new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; +``` + +#### 매개변수 {#parameters} + +##### code {#code} + +[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### 반환값 {#returns} + +`MCPAuthTokenVerificationError` + +#### 오버라이드 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 프로퍼티 {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: MCPAuthTokenVerificationErrorCode; +``` + +스네이크 케이스 형식의 오류 코드입니다. + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthTokenVerificationError'; +``` + +#### 오버라이드 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 프로퍼티는 스택 트레이스( `new Error().stack` 또는 `Error.captureStackTrace(obj)`로 생성됨 )에서 수집되는 스택 프레임의 개수를 지정합니다. + +기본값은 `10`이지만, 유효한 JavaScript 숫자로 설정할 수 있습니다. 값이 변경된 이후에 캡처된 모든 스택 트레이스에 영향을 미칩니다. + +숫자가 아닌 값이나 음수로 설정하면, 스택 트레이스는 프레임을 캡처하지 않습니다. + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 메서드 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +오류를 HTTP 응답에 적합한 JSON 형식으로 변환합니다. + +#### 매개변수 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +오류의 원인(cause)을 JSON 응답에 포함할지 여부입니다. +기본값은 `false`입니다. + +#### 반환값 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +`targetObject`에 `.stack` 프로퍼티를 생성하며, 접근 시 +`Error.captureStackTrace()`가 호출된 코드 위치를 나타내는 문자열을 반환합니다. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // `new Error().stack`과 유사 +``` + +트레이스의 첫 번째 줄은 +`${myObject.name}: ${myObject.message}`로 시작합니다. + +선택적인 `constructorOpt` 인자는 함수입니다. 제공되면, `constructorOpt`를 포함하여 그 위의 모든 프레임이 생성된 스택 트레이스에서 생략됩니다. + +`constructorOpt` 인자는 오류 생성의 구현 세부 정보를 사용자로부터 숨길 때 유용합니다. 예시: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 스택 트레이스를 두 번 계산하지 않기 위해 스택 트레이스 없는 오류 생성 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 함수 b 위에서 스택 트레이스 캡처 + Error.captureStackTrace(error, b); // 함수 c와 b는 스택 트레이스에 포함되지 않음 + throw error; +} + +a(); +``` + +#### 매개변수 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 반환값 {#returns} + +`void` + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 매개변수 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 반환값 {#returns} + +`any` + +#### 참고 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 상속됨 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md new file mode 100644 index 0000000..0587849 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md @@ -0,0 +1,43 @@ +--- +sidebar_label: createVerifyJwt +--- + +# 함수: createVerifyJwt() + +```ts +function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; +``` + +제공된 키 조회 함수와 옵션을 사용하여 JWT 액세스 토큰 (Access token)을 검증하는 함수를 생성합니다. + +## 매개변수 {#parameters} + +### getKey {#getkey} + +`JWTVerifyGetKey` + +JWT를 검증하는 데 사용되는 키를 조회하는 함수입니다. + +**참고** + +키 조회 함수의 타입 정의는 JWTVerifyGetKey를 참고하세요. + +### options? {#options} + +`JWTVerifyOptions` + +선택적으로 사용할 수 있는 JWT 검증 옵션입니다. + +**참고** + +옵션의 타입 정의는 JWTVerifyOptions를 참고하세요. + +## 반환값 {#returns} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +JWT 액세스 토큰 (Access token)을 검증하고, 토큰이 유효한 경우 AuthInfo 객체를 반환하는 함수입니다. 이 함수는 JWT의 페이로드에 `iss`, `client_id`, `sub` 필드가 반드시 포함되어야 하며, 선택적으로 `scope` 또는 `scopes` 필드를 포함할 수 있습니다. JWT 검증은 내부적으로 `jose` 라이브러리를 사용하여 수행됩니다. + +## 참고 {#see} + +반환되는 함수의 타입 정의는 [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md)을 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md new file mode 100644 index 0000000..5196a42 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md @@ -0,0 +1,60 @@ +--- +sidebar_label: fetchServerConfig +--- + +# 함수: fetchServerConfig() + +```ts +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +``` + +발급자 (Issuer)와 인가 서버 유형에 따라 서버 구성을 가져옵니다. + +이 함수는 서버 유형에 따라 well-known URL을 자동으로 결정합니다. OAuth 및 OpenID Connect 서버는 메타데이터 엔드포인트에 대해 서로 다른 규칙을 가지고 있기 때문입니다. + +## 매개변수 {#parameters} + +### issuer {#issuer} + +`string` + +인가 서버의 발급자 (Issuer) URL입니다. + +### config {#config} + +`ServerMetadataConfig` + +서버 유형 및 선택적 트랜스파일 함수가 포함된 구성 객체입니다. + +## 반환값 {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +서버 구성으로 해결되는 프로미스입니다. + +## 참고 {#see} + + - 기본 구현에 대해서는 [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) 을(를) 참조하세요. + - OAuth 2.0 인가 서버 메타데이터 사양은 [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) 를 참조하세요. + - OpenID Connect Discovery 사양은 [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) 를 참조하세요. + +## 예시 {#example} + +```ts +import { fetchServerConfig } from 'mcp-auth'; +// OAuth 서버 구성 가져오기 +// 이는 `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` 에서 메타데이터를 가져옵니다. +const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); + +// OpenID Connect 서버 구성 가져오기 +// 이는 `https://auth.logto.io/oidc/.well-known/openid-configuration` 에서 메타데이터를 가져옵니다. +const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); +``` + +## 예외 발생 {#throws} + +가져오기 작업이 실패할 경우 예외가 발생합니다. + +## 예외 발생 {#throws} + +서버 메타데이터가 유효하지 않거나 MCP 사양과 일치하지 않을 경우 예외가 발생합니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md new file mode 100644 index 0000000..5d27e6a --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md @@ -0,0 +1,41 @@ +--- +sidebar_label: fetchServerConfigByWellKnownUrl +--- + +# 함수: fetchServerConfigByWellKnownUrl() + +```ts +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +``` + +제공된 well-known URL에서 서버 구성을 가져오고 MCP 명세에 따라 유효성을 검사합니다. + +서버 메타데이터가 예상된 스키마와 일치하지 않지만, 호환된다고 확신하는 경우, `transpileData` 함수를 정의하여 메타데이터를 예상 형식으로 변환할 수 있습니다. + +## 매개변수 {#parameters} + +### wellKnownUrl {#wellknownurl} + +서버 구성을 가져올 well-known URL입니다. 문자열 또는 URL 객체일 수 있습니다. + +`string` | `URL` + +### config {#config} + +`ServerMetadataConfig` + +서버 유형과 선택적 변환 함수(transpile function)를 포함하는 구성 객체입니다. + +## 반환값 {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +서버 구성으로 resolve되는 promise입니다. + +## 예외 발생 {#throws} + +가져오기(fetch) 작업이 실패할 경우 예외가 발생합니다. + +## 예외 발생 {#throws} + +서버 메타데이터가 유효하지 않거나 MCP 명세와 일치하지 않을 경우 예외가 발생합니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md new file mode 100644 index 0000000..f7a3b50 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md @@ -0,0 +1,39 @@ +--- +sidebar_label: handleBearerAuth +--- + +# 함수: handleBearerAuth() + +```ts +function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; +``` + +Express 애플리케이션에서 Bearer 인증 (Authentication)을 처리하기 위한 미들웨어 함수를 생성합니다. + +이 미들웨어는 `Authorization` 헤더에서 Bearer 토큰을 추출하고, 제공된 `verifyAccessToken` 함수를 사용하여 토큰을 검증하며, 발급자 (Issuer), 대상 (Audience), 그리고 필요한 스코프 (Scope)를 확인합니다. + +- 토큰이 유효하면 인증 (Authentication) 정보를 `request.auth` 속성에 추가합니다. + 유효하지 않은 경우 적절한 오류 메시지로 응답합니다. +- 액세스 토큰 (Access token) 검증에 실패하면 401 Unauthorized 오류로 응답합니다. +- 토큰에 필요한 스코프 (Scope)가 없으면 403 Forbidden 오류로 응답합니다. +- 인증 (Authentication) 과정에서 예기치 않은 오류가 발생하면, 미들웨어가 해당 오류를 다시 throw 합니다. + +**참고:** `request.auth` 객체는 `@modelcontextprotocol/sdk` 모듈에 정의된 표준 AuthInfo 인터페이스보다 확장된 필드를 포함합니다. 자세한 내용은 이 파일의 확장 인터페이스를 참고하세요. + +## 매개변수 {#parameters} + +### param0 {#param0} + +[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) + +Bearer 인증 (Authentication) 핸들러를 위한 구성입니다. + +## 반환값 {#returns} + +`RequestHandler` + +Bearer 인증 (Authentication)을 처리하는 Express용 미들웨어 함수입니다. + +## 참고 {#see} + +구성 옵션에 대해서는 [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md)를 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md new file mode 100644 index 0000000..bf640e9 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md @@ -0,0 +1,47 @@ +--- +sidebar_label: AuthServerConfig +--- + +# 타입 별칭: AuthServerConfig + +```ts +type AuthServerConfig = { + metadata: CamelCaseAuthorizationServerMetadata; + type: AuthServerType; +}; +``` + +MCP 서버와 통합된 원격 인가 서버 (Authorization Server)에 대한 구성입니다. + +## 속성 {#properties} + +### metadata {#metadata} + +```ts +metadata: CamelCaseAuthorizationServerMetadata; +``` + +인가 서버 (Authorization Server)의 메타데이터로, MCP 명세 (OAuth 2.0 인가 서버 메타데이터 기반)를 따라야 합니다. + +이 메타데이터는 일반적으로 서버의 well-known 엔드포인트 (OAuth 2.0 인가 서버 메타데이터 또는 OpenID Connect Discovery)에서 가져오며, 서버가 해당 엔드포인트를 지원하지 않는 경우 구성에서 직접 제공할 수도 있습니다. + +**참고:** 메타데이터는 mcp-auth 라이브러리에서 선호하는 camelCase 형식이어야 합니다. + +#### 참고 {#see} + + - [OAuth 2.0 인가 서버 메타데이터 (Authorization Server Metadata)](https://datatracker.ietf.org/doc/html/rfc8414) + - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +*** + +### type {#type} + +```ts +type: AuthServerType; +``` + +인가 서버 (Authorization Server)의 유형입니다. + +#### 참고 {#see} + +가능한 값은 [AuthServerType](/references/js/type-aliases/AuthServerType.md)에서 확인하세요. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md new file mode 100644 index 0000000..86e0955 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md @@ -0,0 +1,45 @@ +--- +sidebar_label: AuthServerConfigError +--- + +# 타입 별칭: AuthServerConfigError + +```ts +type AuthServerConfigError = { + cause?: Error; + code: AuthServerConfigErrorCode; + description: string; +}; +``` + +인가 (Authorization) 서버 메타데이터의 검증 중에 발생하는 오류를 나타냅니다. + +## 속성 {#properties} + +### cause? {#cause} + +```ts +optional cause: Error; +``` + +오류의 선택적 원인으로, 일반적으로 더 많은 맥락을 제공하는 `Error` 인스턴스입니다. + +*** + +### code {#code} + +```ts +code: AuthServerConfigErrorCode; +``` + +특정 검증 오류를 나타내는 코드입니다. + +*** + +### description {#description} + +```ts +description: string; +``` + +오류에 대한 사람이 읽을 수 있는 설명입니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md new file mode 100644 index 0000000..b6ecf79 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: AuthServerConfigErrorCode +--- + +# 타입 별칭: AuthServerConfigErrorCode + +```ts +type AuthServerConfigErrorCode = + | "invalid_server_metadata" + | "code_response_type_not_supported" + | "authorization_code_grant_not_supported" + | "pkce_not_supported" + | "s256_code_challenge_method_not_supported"; +``` + +인가 서버 메타데이터를 검증할 때 발생할 수 있는 오류 코드입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md new file mode 100644 index 0000000..3870f76 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md @@ -0,0 +1,34 @@ +--- +sidebar_label: AuthServerConfigWarning +--- + +# 타입 별칭: AuthServerConfigWarning + +```ts +type AuthServerConfigWarning = { + code: AuthServerConfigWarningCode; + description: string; +}; +``` + +인가 서버 메타데이터 검증 중에 발생하는 경고를 나타냅니다. + +## 속성 {#properties} + +### code {#code} + +```ts +code: AuthServerConfigWarningCode; +``` + +특정 검증 경고를 나타내는 코드입니다. + +*** + +### description {#description} + +```ts +description: string; +``` + +경고에 대한 사람이 읽을 수 있는 설명입니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md new file mode 100644 index 0000000..c12a26a --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerConfigWarningCode +--- + +# 타입 별칭: AuthServerConfigWarningCode + +```ts +type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; +``` + +인가 (Authorization) 서버 메타데이터를 검증할 때 발생할 수 있는 경고 코드입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md new file mode 100644 index 0000000..a22222e --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md @@ -0,0 +1,12 @@ +--- +sidebar_label: AuthServerErrorCode +--- + +# 타입 별칭: AuthServerErrorCode + +```ts +type AuthServerErrorCode = + | "invalid_server_metadata" + | "invalid_server_config" + | "missing_jwks_uri"; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md new file mode 100644 index 0000000..a361233 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md @@ -0,0 +1,31 @@ +--- +sidebar_label: AuthServerModeConfig +--- + +# 타입 별칭: ~~AuthServerModeConfig~~ + +```ts +type AuthServerModeConfig = { + server: AuthServerConfig; +}; +``` + +레거시, MCP 서버를 인가 서버 모드로 사용하는 구성입니다. + +## 사용 중단됨 {#deprecated} + +대신 `ResourceServerModeConfig` 구성을 사용하세요. + +## 속성 {#properties} + +### ~~server~~ {#server} + +```ts +server: AuthServerConfig; +``` + +단일 인가 서버 구성입니다. + +#### 사용 중단됨 {#deprecated} + +대신 `protectedResources` 구성을 사용하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md new file mode 100644 index 0000000..d1236d8 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md @@ -0,0 +1,17 @@ +--- +sidebar_label: AuthServerSuccessCode +--- + +# 타입 별칭: AuthServerSuccessCode + +```ts +type AuthServerSuccessCode = + | "server_metadata_valid" + | "dynamic_registration_supported" + | "pkce_supported" + | "s256_code_challenge_method_supported" + | "authorization_code_grant_supported" + | "code_response_type_supported"; +``` + +인가 서버 메타데이터의 성공적인 검증을 나타내는 코드입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md new file mode 100644 index 0000000..df7aded --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerType +--- + +# 타입 별칭: AuthServerType + +```ts +type AuthServerType = "oauth" | "oidc"; +``` + +인가 서버의 타입입니다. 이 정보는 서버 구성에서 제공되어야 하며, 서버가 OAuth 2.0 또는 OpenID Connect (OIDC) 인가 서버인지 나타냅니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md new file mode 100644 index 0000000..d951130 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md @@ -0,0 +1,228 @@ +--- +sidebar_label: AuthorizationServerMetadata +--- + +# 타입 별칭: AuthorizationServerMetadata + +```ts +type AuthorizationServerMetadata = { + authorization_endpoint: string; + code_challenge_methods_supported?: string[]; + grant_types_supported?: string[]; + introspection_endpoint?: string; + introspection_endpoint_auth_methods_supported?: string[]; + introspection_endpoint_auth_signing_alg_values_supported?: string[]; + issuer: string; + jwks_uri?: string; + op_policy_uri?: string; + op_tos_uri?: string; + registration_endpoint?: string; + response_modes_supported?: string[]; + response_types_supported: string[]; + revocation_endpoint?: string; + revocation_endpoint_auth_methods_supported?: string[]; + revocation_endpoint_auth_signing_alg_values_supported?: string[]; + scopes_supported?: string[]; + service_documentation?: string; + token_endpoint: string; + token_endpoint_auth_methods_supported?: string[]; + token_endpoint_auth_signing_alg_values_supported?: string[]; + ui_locales_supported?: string[]; + userinfo_endpoint?: string; +}; +``` + +RFC 8414에서 정의된 OAuth 2.0 인가 서버 메타데이터 스키마입니다. + +## 타입 선언 {#type-declaration} + +### authorization\_endpoint {#authorization-endpoint} + +```ts +authorization_endpoint: string; +``` + +인가 서버의 인가 엔드포인트 URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. +인가 엔드포인트를 사용하는 grant type이 지원되지 않는 경우를 제외하고 필수입니다. + +#### 참고 {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.1 + +### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} + +```ts +optional code_challenge_methods_supported: string[]; +``` + +이 인가 서버가 지원하는 Proof Key for Code Exchange (PKCE) +[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] 코드 챌린지 방식의 목록을 포함하는 JSON 배열입니다. + +### grant\_types\_supported? {#grant-types-supported} + +```ts +optional grant_types_supported: string[]; +``` + +이 인가 서버가 지원하는 OAuth 2.0 grant type 값의 목록을 포함하는 JSON 배열입니다. 배열 값은 "OAuth 2.0 Dynamic Client Registration Protocol" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]에서 정의된 `grant_types` 파라미터와 동일하게 사용됩니다. +생략된 경우 기본값은 `["authorization_code", "implicit"]`입니다. + +### introspection\_endpoint? {#introspection-endpoint} + +```ts +optional introspection_endpoint: string; +``` + +인가 서버의 OAuth 2.0 인트로스펙션 엔드포인트 URL +[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. + +### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} + +```ts +optional introspection_endpoint_auth_methods_supported: string[]; +``` + +### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} + +```ts +optional introspection_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +인가 서버의 발급자 (Issuer) 식별자입니다. `https` 스킴을 사용하고 쿼리 또는 프래그먼트 컴포넌트가 없는 URL입니다. + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +인가 서버의 JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] +문서의 URL입니다. 참조된 문서는 인가 서버의 서명을 검증하기 위해 클라이언트가 사용하는 서명 키를 포함합니다. 이 URL은 반드시 `https` 스킴을 사용해야 합니다. + +### op\_policy\_uri? {#op-policy-uri} + +```ts +optional op_policy_uri: string; +``` + +### op\_tos\_uri? {#op-tos-uri} + +```ts +optional op_tos_uri: string; +``` + +### registration\_endpoint? {#registration-endpoint} + +```ts +optional registration_endpoint: string; +``` + +인가 서버의 OAuth 2.0 동적 클라이언트 등록 엔드포인트 URL +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. + +### response\_modes\_supported? {#response-modes-supported} + +```ts +optional response_modes_supported: string[]; +``` + +이 인가 서버가 지원하는 OAuth 2.0 `response_mode` 값의 목록을 포함하는 JSON 배열입니다. "OAuth 2.0 Multiple Response Type Encoding Practices" +[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]에서 명시되어 있습니다. + +생략된 경우 기본값은 `["query", "fragment"]`입니다. `"form_post"` 응답 모드는 "OAuth 2.0 Form Post Response Mode" +[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]에서 정의되어 있습니다. + +### response\_types\_supported {#response-types-supported} + +```ts +response_types_supported: string[]; +``` + +이 인가 서버가 지원하는 OAuth 2.0 `response_type` 값의 목록을 포함하는 JSON 배열입니다. 배열 값은 "OAuth 2.0 Dynamic Client Registration Protocol" +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]에서 정의된 `response_types` 파라미터와 동일하게 사용됩니다. + +### revocation\_endpoint? {#revocation-endpoint} + +```ts +optional revocation_endpoint: string; +``` + +인가 서버의 OAuth 2.0 토큰 폐기 엔드포인트 URL +[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. + +### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} + +```ts +optional revocation_endpoint_auth_methods_supported: string[]; +``` + +### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} + +```ts +optional revocation_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +이 인가 서버가 지원하는 OAuth 2.0 `scope` 값의 목록을 포함하는 JSON 배열입니다. +[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] + +### service\_documentation? {#service-documentation} + +```ts +optional service_documentation: string; +``` + +### token\_endpoint {#token-endpoint} + +```ts +token_endpoint: string; +``` + +인가 서버의 토큰 엔드포인트 URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. +암시적 grant type만 지원하는 경우를 제외하고 필수입니다. + +#### 참고 {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.2 + +### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} + +```ts +optional token_endpoint_auth_methods_supported: string[]; +``` + +### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} + +```ts +optional token_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### ui\_locales\_supported? {#ui-locales-supported} + +```ts +optional ui_locales_supported: string[]; +``` + +### userinfo\_endpoint? {#userinfo-endpoint} + +```ts +optional userinfo_endpoint: string; +``` + +OpenID Connect [userinfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) 의 URL입니다. +이 엔드포인트는 인증된 사용자에 대한 정보를 가져오는 데 사용됩니다. + +## 참고 {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md new file mode 100644 index 0000000..da25b16 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md @@ -0,0 +1,107 @@ +--- +sidebar_label: BearerAuthConfig +--- + +# 타입 별칭: BearerAuthConfig + +```ts +type BearerAuthConfig = { + audience?: string; + issuer: | string + | ValidateIssuerFunction; + requiredScopes?: string[]; + resource?: string; + showErrorDetails?: boolean; + verifyAccessToken: VerifyAccessTokenFunction; +}; +``` + +## 속성(Properties) {#properties} + +### audience? {#audience} + +```ts +optional audience: string; +``` + +액세스 토큰 (Access token)의 예상 대상 (audience) (`aud` 클레임 (Claim)). 일반적으로 토큰이 의도된 리소스 서버 (API)를 의미합니다. 제공하지 않으면 대상 (Audience) 확인이 건너뜁니다. + +**참고:** 인가 (Authorization) 서버가 리소스 지표 (Resource Indicators, RFC 8707)를 지원하지 않는 경우, 대상 (Audience)이 관련 없을 수 있으므로 이 필드는 생략할 수 있습니다. + +#### 참고 {#see} + +https://datatracker.ietf.org/doc/html/rfc8707 + +*** + +### issuer {#issuer} + +```ts +issuer: + | string + | ValidateIssuerFunction; +``` + +유효한 발급자 (Issuer)를 나타내는 문자열 또는 액세스 토큰의 발급자를 검증하는 함수입니다. + +문자열이 제공되면, 직접 비교를 위해 예상 발급자 (Issuer) 값으로 사용됩니다. + +함수가 제공되면, [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md)의 규칙에 따라 발급자 (Issuer)를 검증해야 합니다. + +#### 참고 {#see} + +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md)에서 검증 함수에 대한 자세한 내용을 확인하세요. + +*** + +### requiredScopes? {#requiredscopes} + +```ts +optional requiredScopes: string[]; +``` + +액세스 토큰 (Access token)이 반드시 가져야 하는 필수 스코프 (Scope) 배열입니다. 토큰에 이 모든 스코프 (Scope)가 포함되어 있지 않으면 오류가 발생합니다. + +**참고:** 핸들러는 토큰의 `scope` 클레임 (Claim)을 확인합니다. 이 값은 인가 (Authorization) 서버의 구현에 따라 공백으로 구분된 문자열이거나 문자열 배열일 수 있습니다. `scope` 클레임 (Claim)이 없으면, 핸들러는 `scopes` 클레임 (Claim)이 있는지 확인합니다. + +*** + +### resource? {#resource} + +```ts +optional resource: string; +``` + +보호된 리소스의 식별자입니다. 제공된 경우, 핸들러는 이 리소스에 대해 구성된 인가 (Authorization) 서버를 사용하여 받은 토큰을 검증합니다. `protectedResources` 구성과 함께 핸들러를 사용할 때 필수입니다. + +*** + +### showErrorDetails? {#showerrordetails} + +```ts +optional showErrorDetails: boolean; +``` + +응답에 상세 오류 정보를 표시할지 여부입니다. 개발 중 디버깅에 유용하지만, 민감한 정보 노출을 방지하기 위해 운영 환경에서는 비활성화해야 합니다. + +#### 기본값 {#default} + +```ts +false +``` + +*** + +### verifyAccessToken {#verifyaccesstoken} + +```ts +verifyAccessToken: VerifyAccessTokenFunction; +``` + +액세스 토큰 (Access token)을 검증하는 함수 타입입니다. + +이 함수는 토큰이 유효하지 않은 경우 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md)를 발생시키거나, 토큰이 유효한 경우 AuthInfo 객체를 반환해야 합니다. + +#### 참고 {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md)에서 자세한 내용을 확인하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md new file mode 100644 index 0000000..ae5ae5d --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: BearerAuthErrorCode +--- + +# 타입 별칭: BearerAuthErrorCode (BearerAuthErrorCode) + +```ts +type BearerAuthErrorCode = + | "missing_auth_header" + | "invalid_auth_header_format" + | "missing_bearer_token" + | "invalid_issuer" + | "invalid_audience" + | "missing_required_scopes" + | "invalid_token"; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md new file mode 100644 index 0000000..7af1255 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md @@ -0,0 +1,179 @@ +--- +sidebar_label: CamelCaseAuthorizationServerMetadata +--- + +# 타입 별칭: CamelCaseAuthorizationServerMetadata + +```ts +type CamelCaseAuthorizationServerMetadata = { + authorizationEndpoint: string; + codeChallengeMethodsSupported?: string[]; + grantTypesSupported?: string[]; + introspectionEndpoint?: string; + introspectionEndpointAuthMethodsSupported?: string[]; + introspectionEndpointAuthSigningAlgValuesSupported?: string[]; + issuer: string; + jwksUri?: string; + opPolicyUri?: string; + opTosUri?: string; + registrationEndpoint?: string; + responseModesSupported?: string[]; + responseTypesSupported: string[]; + revocationEndpoint?: string; + revocationEndpointAuthMethodsSupported?: string[]; + revocationEndpointAuthSigningAlgValuesSupported?: string[]; + scopesSupported?: string[]; + serviceDocumentation?: string; + tokenEndpoint: string; + tokenEndpointAuthMethodsSupported?: string[]; + tokenEndpointAuthSigningAlgValuesSupported?: string[]; + uiLocalesSupported?: string[]; + userinfoEndpoint?: string; +}; +``` + +OAuth 2.0 인가 서버 메타데이터 타입의 camelCase 버전입니다. + +## 타입 선언 {#type-declaration} + +### authorizationEndpoint {#authorizationendpoint} + +```ts +authorizationEndpoint: string; +``` + +### codeChallengeMethodsSupported? {#codechallengemethodssupported} + +```ts +optional codeChallengeMethodsSupported: string[]; +``` + +### grantTypesSupported? {#granttypessupported} + +```ts +optional grantTypesSupported: string[]; +``` + +### introspectionEndpoint? {#introspectionendpoint} + +```ts +optional introspectionEndpoint: string; +``` + +### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} + +```ts +optional introspectionEndpointAuthMethodsSupported: string[]; +``` + +### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} + +```ts +optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### opPolicyUri? {#oppolicyuri} + +```ts +optional opPolicyUri: string; +``` + +### opTosUri? {#optosuri} + +```ts +optional opTosUri: string; +``` + +### registrationEndpoint? {#registrationendpoint} + +```ts +optional registrationEndpoint: string; +``` + +### responseModesSupported? {#responsemodessupported} + +```ts +optional responseModesSupported: string[]; +``` + +### responseTypesSupported {#responsetypessupported} + +```ts +responseTypesSupported: string[]; +``` + +### revocationEndpoint? {#revocationendpoint} + +```ts +optional revocationEndpoint: string; +``` + +### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} + +```ts +optional revocationEndpointAuthMethodsSupported: string[]; +``` + +### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} + +```ts +optional revocationEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### serviceDocumentation? {#servicedocumentation} + +```ts +optional serviceDocumentation: string; +``` + +### tokenEndpoint {#tokenendpoint} + +```ts +tokenEndpoint: string; +``` + +### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} + +```ts +optional tokenEndpointAuthMethodsSupported: string[]; +``` + +### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} + +```ts +optional tokenEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### uiLocalesSupported? {#uilocalessupported} + +```ts +optional uiLocalesSupported: string[]; +``` + +### userinfoEndpoint? {#userinfoendpoint} + +```ts +optional userinfoEndpoint: string; +``` + +## 참고 {#see} + +원본 타입 및 필드 정보는 [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) 를 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md new file mode 100644 index 0000000..e6929c8 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md @@ -0,0 +1,123 @@ +--- +sidebar_label: CamelCaseProtectedResourceMetadata +--- + +# 타입 별칭: CamelCaseProtectedResourceMetadata + +```ts +type CamelCaseProtectedResourceMetadata = { + authorizationDetailsTypesSupported?: string[]; + authorizationServers?: string[]; + bearerMethodsSupported?: string[]; + dpopBoundAccessTokensRequired?: boolean; + dpopSigningAlgValuesSupported?: string[]; + jwksUri?: string; + resource: string; + resourceDocumentation?: string; + resourceName?: string; + resourcePolicyUri?: string; + resourceSigningAlgValuesSupported?: string[]; + resourceTosUri?: string; + scopesSupported?: string[]; + signedMetadata?: string; + tlsClientCertificateBoundAccessTokens?: boolean; +}; +``` + +OAuth 2.0 불투명 토큰 (Opaque token) 보호 리소스 메타데이터 타입의 camelCase 버전입니다. + +## 타입 선언 {#type-declaration} + +### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} + +```ts +optional authorizationDetailsTypesSupported: string[]; +``` + +### authorizationServers? {#authorizationservers} + +```ts +optional authorizationServers: string[]; +``` + +### bearerMethodsSupported? {#bearermethodssupported} + +```ts +optional bearerMethodsSupported: string[]; +``` + +### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} + +```ts +optional dpopBoundAccessTokensRequired: boolean; +``` + +### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} + +```ts +optional dpopSigningAlgValuesSupported: string[]; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### resource {#resource} + +```ts +resource: string; +``` + +### resourceDocumentation? {#resourcedocumentation} + +```ts +optional resourceDocumentation: string; +``` + +### resourceName? {#resourcename} + +```ts +optional resourceName: string; +``` + +### resourcePolicyUri? {#resourcepolicyuri} + +```ts +optional resourcePolicyUri: string; +``` + +### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} + +```ts +optional resourceSigningAlgValuesSupported: string[]; +``` + +### resourceTosUri? {#resourcetosuri} + +```ts +optional resourceTosUri: string; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### signedMetadata? {#signedmetadata} + +```ts +optional signedMetadata: string; +``` + +### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} + +```ts +optional tlsClientCertificateBoundAccessTokens: boolean; +``` + +## 참고 {#see} + +원본 타입 및 필드 정보는 [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) 를 참조하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md new file mode 100644 index 0000000..a1407ff --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md @@ -0,0 +1,55 @@ +--- +sidebar_label: MCPAuthBearerAuthErrorDetails +--- + +# 타입 별칭: MCPAuthBearerAuthErrorDetails + +```ts +type MCPAuthBearerAuthErrorDetails = { + actual?: unknown; + cause?: unknown; + expected?: unknown; + missingScopes?: string[]; + uri?: URL; +}; +``` + +## 속성 {#properties} + +### actual? {#actual} + +```ts +optional actual: unknown; +``` + +*** + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +*** + +### expected? {#expected} + +```ts +optional expected: unknown; +``` + +*** + +### missingScopes? {#missingscopes} + +```ts +optional missingScopes: string[]; +``` + +*** + +### uri? {#uri} + +```ts +optional uri: URL; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md new file mode 100644 index 0000000..879159d --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md @@ -0,0 +1,13 @@ +--- +sidebar_label: MCPAuthConfig +--- + +# 타입 별칭: MCPAuthConfig + +```ts +type MCPAuthConfig = + | AuthServerModeConfig + | ResourceServerModeConfig; +``` + +[MCPAuth](/references/js/classes/MCPAuth.md) 클래스의 설정으로, 단일 레거시 `인가 서버 (authorization server)` 또는 `리소스 서버 (resource server)` 구성을 지원합니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md new file mode 100644 index 0000000..cecafed --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md @@ -0,0 +1,9 @@ +--- +sidebar_label: MCPAuthTokenVerificationErrorCode +--- + +# 타입 별칭: MCPAuthTokenVerificationErrorCode + +```ts +type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md new file mode 100644 index 0000000..e55c72a --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md @@ -0,0 +1,150 @@ +--- +sidebar_label: ProtectedResourceMetadata +--- + +# 타입 별칭: ProtectedResourceMetadata + +```ts +type ProtectedResourceMetadata = { + authorization_details_types_supported?: string[]; + authorization_servers?: string[]; + bearer_methods_supported?: string[]; + dpop_bound_access_tokens_required?: boolean; + dpop_signing_alg_values_supported?: string[]; + jwks_uri?: string; + resource: string; + resource_documentation?: string; + resource_name?: string; + resource_policy_uri?: string; + resource_signing_alg_values_supported?: string[]; + resource_tos_uri?: string; + scopes_supported?: string[]; + signed_metadata?: string; + tls_client_certificate_bound_access_tokens?: boolean; +}; +``` + +OAuth 2.0 보호된 리소스 메타데이터 스키마입니다. + +## 타입 선언 {#type-declaration} + +### authorization\_details\_types\_supported? {#authorization-details-types-supported} + +```ts +optional authorization_details_types_supported: string[]; +``` + +authorization_details 요청 파라미터를 사용할 때 지원되는 인가 세부 정보 타입 값입니다. + +### authorization\_servers? {#authorization-servers} + +```ts +optional authorization_servers: string[]; +``` + +이 보호된 리소스와 함께 사용할 수 있는 OAuth 인가 서버 발급자 식별자 목록입니다. + +### bearer\_methods\_supported? {#bearer-methods-supported} + +```ts +optional bearer_methods_supported: string[]; +``` + +OAuth 2.0 베어러 토큰을 전송할 때 지원되는 방법입니다. 값: ["header", "body", "query"]. + +### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} + +```ts +optional dpop_bound_access_tokens_required: boolean; +``` + +이 보호된 리소스가 항상 DPoP-바인딩 액세스 토큰 (액세스 토큰)을 요구하는지 여부입니다. + +### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} + +```ts +optional dpop_signing_alg_values_supported: string[]; +``` + +DPoP 증명 JWT (JWT)를 검증할 때 지원되는 JWS 알고리즘입니다. + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +보호된 리소스의 JSON Web Key (JWK) 세트 문서의 URL입니다. 이 문서에는 이 보호된 리소스가 반환하는 응답 또는 데이터의 디지털 서명을 검증하는 데 사용할 수 있는 공개 키가 포함되어 있습니다. +이는 토큰 검증에 사용되는 인가 서버의 jwks_uri와 다릅니다. 보호된 리소스가 응답에 서명하는 경우, 클라이언트는 이 공개 키를 가져와 수신 데이터의 진위성과 무결성을 검증할 수 있습니다. + +### resource {#resource} + +```ts +resource: string; +``` + +보호된 리소스의 리소스 식별자입니다. + +### resource\_documentation? {#resource-documentation} + +```ts +optional resource_documentation: string; +``` + +보호된 리소스를 사용하는 방법에 대한 개발자 문서가 포함된 URL입니다. + +### resource\_name? {#resource-name} + +```ts +optional resource_name: string; +``` + +최종 사용자에게 표시할 보호된 리소스의 사람이 읽을 수 있는 이름입니다. + +### resource\_policy\_uri? {#resource-policy-uri} + +```ts +optional resource_policy_uri: string; +``` + +보호된 리소스의 데이터 사용 요구 사항에 대한 정보가 포함된 URL입니다. + +### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} + +```ts +optional resource_signing_alg_values_supported: string[]; +``` + +리소스 응답에 서명할 때 보호된 리소스가 지원하는 JWS 서명 알고리즘입니다. + +### resource\_tos\_uri? {#resource-tos-uri} + +```ts +optional resource_tos_uri: string; +``` + +보호된 리소스의 서비스 약관이 포함된 URL입니다. + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +이 보호된 리소스에 접근하기 위한 인가 요청에서 사용되는 스코프 (Scope) 값 목록입니다. + +### signed\_metadata? {#signed-metadata} + +```ts +optional signed_metadata: string; +``` + +클레임으로 메타데이터 파라미터를 포함하는 서명된 JWT (JWT)입니다. JWT는 JWS를 사용하여 서명되어야 하며 'iss' 클레임을 포함해야 합니다. 이 필드는 메타데이터 자체의 진위성을 암호학적으로 검증할 수 있는 방법을 제공합니다. 서명은 jwks_uri 엔드포인트에서 제공되는 공개 키를 사용하여 검증할 수 있습니다. 이 값이 존재할 경우, 이 서명된 메타데이터의 값이 이 메타데이터 문서의 해당 일반 JSON 값보다 우선합니다. 이는 리소스 메타데이터의 변조를 방지하는 데 도움이 됩니다. + +### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} + +```ts +optional tls_client_certificate_bound_access_tokens: boolean; +``` + +보호된 리소스가 상호-TLS 클라이언트 인증서-바인딩 액세스 토큰 (액세스 토큰)을 지원하는지 여부입니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md new file mode 100644 index 0000000..f5765ea --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md @@ -0,0 +1,23 @@ +--- +sidebar_label: ResourceServerModeConfig +--- + +# 타입 별칭: ResourceServerModeConfig + +```ts +type ResourceServerModeConfig = { + protectedResources: ResourceServerConfig | ResourceServerConfig[]; +}; +``` + +MCP 서버를 리소스 서버 모드로 설정하는 구성입니다. + +## 속성 {#properties} + +### protectedResources {#protectedresources} + +```ts +protectedResources: ResourceServerConfig | ResourceServerConfig[]; +``` + +단일 리소스 서버 구성 또는 그 배열입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md new file mode 100644 index 0000000..9eb9e2e --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md @@ -0,0 +1,30 @@ +--- +sidebar_label: ValidateIssuerFunction +--- + +# 타입 별칭: ValidateIssuerFunction() + +```ts +type ValidateIssuerFunction = (tokenIssuer: string) => void; +``` + +액세스 토큰 (Access token)의 발급자 (Issuer)를 검증하는 함수 타입입니다. + +이 함수는 발급자가 유효하지 않은 경우 코드가 'invalid_issuer'인 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)를 throw해야 합니다. 발급자는 다음을 기준으로 검증되어야 합니다: + +1. MCP-Auth의 인증 서버 메타데이터에 구성된 인가 서버 (Authorization server) +2. 보호된 리소스의 메타데이터에 나열된 인가 서버 (Authorization server) + +## 매개변수 {#parameters} + +### tokenIssuer {#tokenissuer} + +`string` + +## 반환값 {#returns} + +`void` + +## 예외 발생 {#throws} + +발급자가 인식되지 않거나 유효하지 않은 경우 예외가 발생합니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md new file mode 100644 index 0000000..1feef1b --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md @@ -0,0 +1,37 @@ +--- +sidebar_label: VerifyAccessTokenFunction +--- + +# 타입 별칭: VerifyAccessTokenFunction() + +```ts +type VerifyAccessTokenFunction = (token: string) => MaybePromise; +``` + +액세스 토큰 (Access token)을 검증하는 함수 타입입니다. + +이 함수는 토큰이 유효하지 않은 경우 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md)를 throw 해야 하며, +토큰이 유효한 경우 AuthInfo 객체를 반환해야 합니다. + +예를 들어, JWT 검증 함수가 있다면 최소한 토큰의 서명, 만료 여부를 확인하고 필요한 클레임 (Claim)을 추출하여 `AuthInfo` +객체를 반환해야 합니다. + +**참고:** 다음 필드는 핸들러에서 확인하므로 토큰에서 별도로 검증할 필요가 없습니다: + +- `iss` (발급자 (Issuer)) +- `aud` (대상 (Audience)) +- `scope` (스코프 (Scopes)) + +## 매개변수 {#parameters} + +### token {#token} + +`string` + +검증할 액세스 토큰 (Access token) 문자열입니다. + +## 반환값 {#returns} + +`MaybePromise`\<`AuthInfo`\> + +토큰이 유효한 경우 AuthInfo 객체 또는 동기 값으로 resolve 되는 프로미스입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md new file mode 100644 index 0000000..e66f87b --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: VerifyAccessTokenMode +--- + +# 타입 별칭: VerifyAccessTokenMode + +```ts +type VerifyAccessTokenMode = "jwt"; +``` + +`bearerAuth`에서 지원하는 내장 검증 모드입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md new file mode 100644 index 0000000..4c3c8d0 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: authServerErrorDescription +--- + +# 변수: authServerErrorDescription (authServerErrorDescription) + +```ts +const authServerErrorDescription: Readonly>; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md new file mode 100644 index 0000000..b9db02f --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: authorizationServerMetadataSchema +--- + +# 변수: authorizationServerMetadataSchema + +```ts +const authorizationServerMetadataSchema: ZodObject; +``` + +RFC 8414에 정의된 OAuth 2.0 인가 서버 메타데이터 (Authorization Server Metadata)를 위한 Zod 스키마입니다. + +## 참고 {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md new file mode 100644 index 0000000..a5eaf5d --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: bearerAuthErrorDescription +--- + +# 변수: bearerAuthErrorDescription + +```ts +const bearerAuthErrorDescription: Readonly>; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md new file mode 100644 index 0000000..0cab425 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseAuthorizationServerMetadataSchema +--- + +# 변수: camelCaseAuthorizationServerMetadataSchema + +```ts +const camelCaseAuthorizationServerMetadataSchema: ZodObject; +``` + +OAuth 2.0 인가 서버 메타데이터 (Authorization Server Metadata)의 camelCase 버전 Zod 스키마입니다. + +## 참고 {#see} + +원본 스키마 및 필드 정보는 [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) 를 참조하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md new file mode 100644 index 0000000..82414a5 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseProtectedResourceMetadataSchema +--- + +# 변수: camelCaseProtectedResourceMetadataSchema + +```ts +const camelCaseProtectedResourceMetadataSchema: ZodObject; +``` + +OAuth 2.0 보호된 리소스 메타데이터 Zod 스키마의 camelCase 버전입니다. + +## 참고 {#see} + +원본 스키마 및 필드 정보는 [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) 를 참조하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md new file mode 100644 index 0000000..90accbb --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md @@ -0,0 +1,9 @@ +--- +sidebar_label: defaultValues +--- + +# 변수: defaultValues + +```ts +const defaultValues: Readonly>; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md new file mode 100644 index 0000000..b230720 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md @@ -0,0 +1,11 @@ +--- +sidebar_label: protectedResourceMetadataSchema +--- + +# 변수: protectedResourceMetadataSchema + +```ts +const protectedResourceMetadataSchema: ZodObject; +``` + +OAuth 2.0 보호된 리소스 메타데이터를 위한 Zod 스키마입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md new file mode 100644 index 0000000..81b2ee3 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md @@ -0,0 +1,12 @@ +--- +sidebar_label: serverMetadataPaths +--- + +# 변수: serverMetadataPaths + +```ts +const serverMetadataPaths: Readonly<{ + oauth: "/.well-known/oauth-authorization-server"; + oidc: "/.well-known/openid-configuration"; +}>; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md new file mode 100644 index 0000000..8442d41 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: tokenVerificationErrorDescription +--- + +# 변수: tokenVerificationErrorDescription (tokenVerificationErrorDescription) + +```ts +const tokenVerificationErrorDescription: Readonly>; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md new file mode 100644 index 0000000..b686996 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md @@ -0,0 +1,9 @@ +--- +sidebar_label: validateServerConfig +--- + +# 변수: validateServerConfig + +```ts +const validateServerConfig: ValidateServerConfig; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx b/i18n/ko/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx new file mode 100644 index 0000000..00f677a --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx @@ -0,0 +1,73 @@ +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + + + + +```python +mcp = FastMCP("MyMCPServer") +resource_identifier = "https://api.example.com" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_identifier, + authorization_servers=[fetch_server_config('', AuthServerType.OIDC)], + scopes_supported=["read", "write"], + ) + ) +) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + Mount('/', app=mcp.sse_app(), middleware=[Middleware( + mcp_auth.bearer_auth_middleware("jwt", + resource=resource_identifier, + audience=resource_identifier, + required_scopes=["read", "write"] + ) + )]) + ] +) + +@mcp.tool() +def whoami(): + return mcp_auth.auth_info.claims +``` + + + + +```ts +const server = new McpServer(/* ... */); +const resourceIdentifier = 'https://api.example.com'; + +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceIdentifier, + authorizationServers: [await fetchServerConfig('', { type: 'oidc' })], + scopesSupported: ['read', 'write'], + } + } +}); + +const app = express(); + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +app.use(mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, + requiredScopes: ['read', 'write'] +})); + +server.tool('whoami', ({ authInfo }) => { + return authInfo.claims; +}); +``` + + + diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx b/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx new file mode 100644 index 0000000..a8dde71 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx @@ -0,0 +1,1387 @@ +--- +sidebar_position: 2 +sidebar_label: '튜토리얼: Todo 매니저 만들기' +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + +# 튜토리얼: Todo 매니저 만들기 + +이 튜토리얼에서는 사용자 인증 (Authentication) 및 인가 (Authorization)가 적용된 todo 매니저 MCP 서버를 구축합니다. 최신 MCP 명세를 따라, 우리의 MCP 서버는 액세스 토큰 (Access token)을 검증하고 스코프 기반 권한 (Permission)을 적용하는 OAuth 2.0 **리소스 서버 (Resource Server)** 역할을 하게 됩니다. + +이 튜토리얼을 완료하면 다음을 얻게 됩니다: + +- ✅ MCP 서버에서 역할 기반 접근 제어 (RBAC)를 설정하는 방법에 대한 기본 이해 +- ✅ 인가 서버 (Authorization Server)가 발급한 액세스 토큰을 사용하는 리소스 서버 역할의 MCP 서버 +- ✅ todo 작업에 대한 스코프 기반 권한 적용의 동작 구현 + +## 개요 (Overview) \{#overview} + +이 튜토리얼에는 다음과 같은 구성 요소가 포함됩니다: + +- **MCP 클라이언트 (MCP Inspector)**: OAuth 2.0 / OIDC 클라이언트 역할을 하는 MCP 서버용 시각적 테스트 도구입니다. 인가 서버와 인가 플로우를 시작하고, MCP 서버에 요청을 인증하기 위해 액세스 토큰을 획득합니다. +- **인가 서버 (Authorization Server)**: 사용자 아이덴티티를 관리하고, 사용자를 인증 (Authentication)하며, 인가된 클라이언트에 적절한 스코프가 포함된 액세스 토큰을 발급하는 OAuth 2.1 또는 OpenID Connect 제공자입니다. +- **MCP 서버 (Resource Server)**: 최신 MCP 명세에 따라, MCP 서버는 OAuth 2.0 프레임워크에서 리소스 서버 역할을 합니다. 인가 서버가 발급한 액세스 토큰을 검증하고, todo 작업에 대해 스코프 기반 권한을 적용합니다. + +이 아키텍처는 표준 OAuth 2.0 플로우를 따릅니다: +- **MCP Inspector**가 사용자를 대신하여 보호된 리소스를 요청합니다 +- **인가 서버**가 사용자를 인증하고 액세스 토큰을 발급합니다 +- **MCP 서버**가 토큰을 검증하고, 부여된 권한에 따라 보호된 리소스를 제공합니다 + +다음은 이 구성 요소들 간 상호작용의 상위 다이어그램입니다: + +```mermaid +sequenceDiagram + autonumber + participant Client as MCP Inspector
(OAuth 클라이언트) + participant RS as MCP 서버
(리소스 서버) + participant AS as 인가 서버 + + Client->>RS: MCP 요청 (토큰 없음) + RS-->>Client: 401 인증되지 않음 (WWW-Authenticate) + Note over Client: WWW-Authenticate 헤더에서
resource_metadata URL 추출 + + Client->>RS: GET /.well-known/oauth-protected-resource (resource_metadata) + RS-->>Client: 보호된 리소스 메타데이터
(인가 서버 URL 포함) + + Client->>AS: GET /.well-known/oauth-authorization-server + AS-->>Client: 인가 서버 메타데이터 + Client->>AS: OAuth 인가 (로그인 & 동의) + AS-->>Client: 액세스 토큰 + + Client->>RS: MCP 요청 (Authorization: Bearer ) + RS->>RS: 액세스 토큰이 유효하고 인가되었는지 검증 + RS-->>Client: MCP 응답 +``` + +## 인가 서버 이해하기 \{#understand-your-authorization-server} + +### 스코프가 포함된 액세스 토큰 (Access tokens with scopes) \{#access-tokens-with-scopes} + +[역할 기반 접근 제어 (RBAC)](https://auth.wiki/rbac)를 MCP 서버에 구현하려면, 인가 서버가 스코프가 포함된 액세스 토큰을 발급할 수 있어야 합니다. 스코프는 사용자가 부여받은 권한 (Permission)을 나타냅니다. + + + + +[Logto](https://logto.io)는 API 리소스 ([RFC 8707: OAuth 2.0을 위한 리소스 지표](https://datatracker.ietf.org/doc/html/rfc8707)) 및 역할 (Role) 기능을 통해 RBAC를 지원합니다. 설정 방법은 다음과 같습니다: + +1. [Logto Console](https://cloud.logto.io) (또는 자체 호스팅 Logto Console)에 로그인하세요. + +2. API 리소스 및 스코프 생성: + + - "API 리소스"로 이동 + - "Todo Manager"라는 새 API 리소스 생성 + - 다음 스코프 추가: + - `create:todos`: "새 todo 항목 생성" + - `read:todos`: "모든 todo 항목 읽기" + - `delete:todos`: "모든 todo 항목 삭제" + +3. 역할 생성 (관리가 쉬워지므로 권장): + + - "역할"로 이동 + - "Admin" 역할을 생성하고 모든 스코프(`create:todos`, `read:todos`, `delete:todos`) 할당 + - "User" 역할을 생성하고 `create:todos` 스코프만 할당 + +4. 권한 할당: + - "사용자"로 이동 + - 사용자를 선택 + - "Roles" 탭에서 역할 할당 (권장) + - 또는 "Permissions" 탭에서 직접 스코프 할당 + +스코프는 JWT 액세스 토큰의 `scope` 클레임에 공백으로 구분된 문자열로 포함됩니다. + + + + +OAuth 2.0 / OIDC 제공자는 일반적으로 스코프 기반 접근 제어를 지원합니다. RBAC 구현 시: + +1. 인가 서버에서 필요한 스코프 정의 +2. 클라이언트가 인가 플로우 중에 이 스코프를 요청하도록 구성 +3. 인가 서버가 부여된 스코프를 액세스 토큰에 포함하는지 확인 +4. 스코프는 보통 JWT 액세스 토큰의 `scope` 클레임에 포함됨 + +스코프 정의 및 관리 방법, 액세스 토큰에 스코프가 포함되는 방식, 역할 관리 등 추가 RBAC 기능은 제공자 문서를 참고하세요. + + + + +### 토큰 검증 및 권한 확인 (Validating tokens and checking permissions) \{#validating-tokens-and-checking-permissions} + +최신 MCP 명세에 따르면, MCP 서버는 OAuth 2.0 프레임워크에서 **리소스 서버 (Resource Server)** 역할을 합니다. 리소스 서버로서 MCP 서버의 주요 책임은 다음과 같습니다: + +1. **토큰 검증**: MCP 클라이언트로부터 받은 액세스 토큰의 진위 및 무결성 검증 +2. **스코프 적용**: 액세스 토큰에서 스코프를 추출 및 검증하여 클라이언트가 수행할 수 있는 작업 결정 +3. **리소스 보호**: 유효한 토큰과 충분한 권한이 있는 경우에만 보호된 리소스(도구 실행) 제공 + +MCP 서버가 요청을 받으면 다음과 같은 검증 과정을 거칩니다: + +1. `Authorization` 헤더에서 액세스 토큰 추출 (Bearer 토큰 형식) +2. 액세스 토큰의 서명 및 만료 검증 +3. 검증된 토큰에서 스코프 및 사용자 정보 추출 +4. 요청 작업에 필요한 스코프가 토큰에 포함되어 있는지 확인 + +예를 들어, 사용자가 새 todo 항목을 생성하려면 액세스 토큰에 `create:todos` 스코프가 포함되어야 합니다. 리소스 서버 검증 플로우는 다음과 같습니다: + +```mermaid +sequenceDiagram + participant Client as MCP 클라이언트 + participant Server as MCP 서버
(리소스 서버) + participant Auth as 인가 서버 + + Client->>Server: 액세스 토큰과 함께 요청
(Authorization: Bearer ) + + alt JWT 검증 (권장) + Server->>Auth: JWKS 가져오기 (캐시 안 된 경우) + Auth-->>Server: JWKS 반환 + Server->>Server: JWT 서명 및 클레임 로컬 검증 + else 토큰 인트로스펙션 (대체) + Server->>Auth: POST /introspect
(token=access_token) + Auth-->>Server: 토큰 정보 반환
(active, scope, user_id 등) + end + + Server->>Server: 검증된 토큰에서 스코프 및 사용자 컨텍스트 추출 + + alt 필요한 스코프 있음 + Server->>Server: 요청된 작업 실행 + Server->>Client: 작업 결과 반환 + else 필요한 스코프 없음 + Server->>Client: 403 Forbidden 반환
(insufficient_scope 오류) + end +``` + +### 동적 클라이언트 등록 (Dynamic Client Registration) \{#dynamic-client-registration} + +이 튜토리얼에서는 필수는 아니지만, 인가 서버에 MCP 클라이언트 등록을 자동화하고 싶다면 유용할 수 있습니다. 자세한 내용은 [동적 클라이언트 등록이 필요한가요?](/provider-list#is-dcr-required)를 참고하세요. + +## Todo 매니저에서 RBAC 이해하기 \{#understand-rbac-in-todo-manager} + +데모 목적을 위해, todo 매니저 MCP 서버에 간단한 역할 기반 접근 제어 (RBAC) 시스템을 구현합니다. 이를 통해 RBAC의 기본 원리를 쉽게 이해할 수 있습니다. + +:::note +이 튜토리얼은 RBAC 기반 스코프 관리를 시연하지만, 모든 인증 (Authentication) 제공자가 역할을 통한 스코프 관리를 구현하는 것은 아닙니다. 일부 제공자는 자체적인 접근 제어 및 권한 관리 방식을 가질 수 있습니다. +::: + +### 도구와 스코프 (Tools and scopes) \{#tools-and-scopes} + +우리 todo 매니저 MCP 서버는 세 가지 주요 도구를 제공합니다: + +- `create-todo`: 새 todo 항목 생성 +- `get-todos`: 모든 todo 목록 조회 +- `delete-todo`: ID로 todo 삭제 + +이 도구들에 대한 접근을 제어하기 위해 다음과 같은 스코프를 정의합니다: + +- `create:todos`: 새 todo 항목 생성 허용 +- `delete:todos`: 기존 todo 항목 삭제 허용 +- `read:todos`: 모든 todo 항목 조회 및 검색 허용 + +### 역할과 권한 (Roles and permissions) \{#roles-and-permissions} + +다음과 같이 서로 다른 접근 수준을 가진 두 가지 역할을 정의합니다: + +| 역할 | create:todos | read:todos | delete:todos | +| ----- | ------------ | ---------- | ------------ | +| Admin | ✅ | ✅ | ✅ | +| User | ✅ | | | + +- **User**: 자신의 todo만 생성, 조회, 삭제할 수 있는 일반 사용자 +- **Admin**: 소유자와 상관없이 모든 todo를 생성, 조회, 삭제할 수 있는 관리자 + +### 리소스 소유권 (Resource ownership) \{#resource-ownership} + +위 권한 테이블은 각 역할에 명시적으로 할당된 스코프를 보여주지만, 리소스 소유권의 중요한 원칙이 있습니다: + +- **User**는 `read:todos` 또는 `delete:todos` 스코프가 없지만, + - 자신의 todo 항목은 조회할 수 있습니다 + - 자신의 todo 항목은 삭제할 수 있습니다 +- **Admin**은 전체 권한 (`read:todos`, `delete:todos`)을 가지므로, + - 시스템의 모든 todo 항목을 볼 수 있습니다 + - 소유자와 상관없이 모든 todo 항목을 삭제할 수 있습니다 + +이는 RBAC 시스템에서 리소스 소유권이 사용자의 소유 리소스에 대한 암묵적 권한을 부여하고, 관리 역할은 모든 리소스에 대한 명시적 권한을 받는 일반적인 패턴을 보여줍니다. + +:::tip 더 알아보기 +RBAC 개념과 모범 사례를 더 깊이 이해하려면 [Mastering RBAC: A Comprehensive Real-World Example](https://blog.logto.io/mastering-rbac)을 참고하세요. +::: + +## 제공자에서 인가 (Authorization) 구성하기 \{#configure-authorization-in-your-provider} + +앞서 설명한 접근 제어 시스템을 구현하려면, 인가 서버에서 필요한 스코프를 지원하도록 구성해야 합니다. 제공자별 설정 방법은 다음과 같습니다: + + + + +[Logto](https://logto.io)는 API 리소스와 역할 기능을 통해 RBAC를 지원합니다. 설정 방법은 다음과 같습니다: + +1. [Logto Console](https://cloud.logto.io) (또는 자체 호스팅 Logto Console)에 로그인하세요. + +2. API 리소스 및 스코프 생성: + + - "API 리소스"로 이동 + - "Todo Manager"라는 새 API 리소스를 생성하고, 리소스 지표 (Resource indicator)로 `http://localhost:3001`을 사용합니다. + - **중요**: 리소스 지표는 MCP 서버의 URL과 일치해야 합니다. 이 튜토리얼에서는 MCP 서버가 3001 포트에서 실행되므로 `http://localhost:3001`을 사용합니다. 운영 환경에서는 실제 MCP 서버 URL (예: `https://your-mcp-server.example.com`)을 사용하세요. + - 다음 스코프 생성: + - `create:todos`: "새 todo 항목 생성" + - `read:todos`: "모든 todo 항목 읽기" + - `delete:todos`: "모든 todo 항목 삭제" + +3. 역할 생성 (관리가 쉬워지므로 권장): + + - "Roles"로 이동 + - "Admin" 역할을 생성하고 모든 스코프(`create:todos`, `read:todos`, `delete:todos`) 할당 + - "User" 역할을 생성하고 `create:todos` 스코프만 할당 + - "User" 역할 상세 페이지에서 "일반" 탭으로 이동하여 "User" 역할을 "기본 역할"로 설정 + +4. 사용자 역할 및 권한 관리: + - 신규 사용자: + - "User" 역할이 기본 역할로 설정되어 있으므로 자동으로 할당됨 + - 기존 사용자: + - "사용자 관리"로 이동 + - 사용자를 선택 + - "Roles" 탭에서 역할 할당 + +:::tip 프로그래밍 방식의 역할 관리 +Logto의 [Management API](https://docs.logto.io/integrate-logto/interact-with-management-api)를 사용하여 프로그래밍 방식으로 사용자 역할을 관리할 수 있습니다. 자동화된 사용자 관리나 관리자 패널 구축 시 유용합니다. +::: + +액세스 토큰을 요청할 때, Logto는 사용자 역할 권한에 따라 토큰의 `scope` 클레임에 스코프를 포함합니다. + + + + +OAuth 2.0 또는 OpenID Connect 제공자의 경우, 서로 다른 권한을 나타내는 스코프를 구성해야 합니다. 구체적인 단계는 제공자마다 다르지만, 일반적으로: + +1. 스코프 정의: + + - 인가 서버에서 다음 스코프 지원하도록 구성: + - `create:todos` + - `read:todos` + - `delete:todos` + +2. 클라이언트 구성: + + - 클라이언트를 등록하거나 업데이트하여 이 스코프를 요청하도록 설정 + - 액세스 토큰에 스코프가 포함되는지 확인 + +3. 권한 할당: + - 제공자 인터페이스를 통해 사용자에게 적절한 스코프 부여 + - 일부 제공자는 역할 기반 관리, 일부는 직접 스코프 할당 지원 + - 권장 방식은 제공자 문서를 참고 + +:::tip +대부분의 제공자는 부여된 스코프를 액세스 토큰의 `scope` 클레임에 포함합니다. 형식은 일반적으로 공백으로 구분된 스코프 값 문자열입니다. +::: + + + + +인가 서버를 구성한 후, 사용자는 부여된 스코프가 포함된 액세스 토큰을 받게 됩니다. MCP 서버는 이 스코프를 사용하여 다음을 결정합니다: + +- 사용자가 새 todo를 생성할 수 있는지 (`create:todos`) +- 사용자가 모든 todo를 볼 수 있는지 (`read:todos`) 또는 자신의 todo만 볼 수 있는지 +- 사용자가 모든 todo를 삭제할 수 있는지 (`delete:todos`) 또는 자신의 todo만 삭제할 수 있는지 + +## MCP 서버 설정하기 \{#set-up-the-mcp-server} + +[MCP 공식 SDK](https://github.com/modelcontextprotocol)를 사용하여 todo 매니저 MCP 서버를 만듭니다. + +### 새 프로젝트 생성 \{#create-a-new-project} + + + + +새 Python 프로젝트를 설정하세요: + +```bash +mkdir mcp-todo-server +cd mcp-todo-server + +# 새 Python 프로젝트 초기화 +uv init + +# uv로 가상환경 생성 +uv venv + +# 가상환경 활성화 (uv run 사용 시 선택 사항) +source .venv/bin/activate +``` + +:::note +이 프로젝트는 패키지 관리를 위해 `uv`를 사용하지만, `pip`, `poetry`, `conda` 등 다른 패키지 매니저도 사용할 수 있습니다. +::: + + + + +새 Node.js 프로젝트를 설정하세요: + +```bash +mkdir mcp-server +cd mcp-server +npm init -y # 또는 `pnpm init` 사용 +npm pkg set type="module" +npm pkg set main="todo-manager.ts" +npm pkg set scripts.start="node --experimental-strip-types todo-manager.ts" +``` + +:::note +예제에서는 TypeScript를 사용합니다. Node.js v22.6.0+에서는 `--experimental-strip-types` 플래그로 TypeScript를 네이티브로 실행할 수 있습니다. JavaScript를 사용하는 경우 코드가 유사하며, Node.js v22.6.0 이상을 사용해야 합니다. 자세한 내용은 Node.js 문서를 참고하세요. +::: + + + + +### MCP SDK 및 의존성 설치 \{#install-the-mcp-sdk-and-dependencies} + + + + +필요한 의존성 설치: + +```bash +uv add "mcp[cli]" uvicorn starlette +``` + + + + +```bash +npm install @modelcontextprotocol/sdk express zod +``` + +또는 `pnpm`, `yarn` 등 원하는 패키지 매니저를 사용할 수 있습니다. + + + + +### MCP 서버 만들기 \{#create-the-mcp-server} + +먼저, 도구 정의가 포함된 기본 MCP 서버를 만듭니다: + + + + +`server.py` 파일을 만들고 다음 코드를 추가하세요: + +```python +# server.py + +import contextlib +from typing import Any +from mcp.server.fastmcp import FastMCP +from starlette.applications import Starlette +from starlette.routing import Mount + +# FastMCP 서버 초기화 +mcp = FastMCP(name="Todo Manager", stateless_http=True, streamable_http_path='/') + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """새 todo 생성. 'create:todos' 스코프 필요.""" + return {"error": "Not implemented"} + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """todo 목록 조회. 'read:todos' 스코프가 있으면 전체 조회 가능.""" + return {"error": "Not implemented"} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """ID로 todo 삭제. 사용자는 자신의 todo만 삭제 가능.""" + return {"error": "Not implemented"} + +@contextlib.asynccontextmanager +async def lifespan(app: Starlette): + async with contextlib.AsyncExitStack() as stack: + await stack.enter_async_context(mcp.session_manager.run()) + yield + +# 앱 생성 +app = Starlette( + routes=[ + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + +서버 실행: + +```bash +# uvicorn으로 Todo Manager 서버 시작 +uvicorn server:app --host 127.0.0.1 --port 3001 + +# 또는 uv 사용: +# uv run uvicorn server:app --host 127.0.0.1 --port 3001 +``` + + + + +`todo-manager.ts` 파일을 만들고 다음 코드를 추가하세요: + +```ts +// todo-manager.ts + +import { z } from 'zod'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import express, { type Request, type Response } from 'express'; + +// MCP 서버 생성 +const server = new McpServer({ + name: 'Todo Manager', + version: '0.0.0', +}); + +server.tool('create-todo', '새 todo 생성', { content: z.string() }, async ({ content }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('get-todos', '모든 todo 목록 조회', async () => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('delete-todo', 'ID로 todo 삭제', { id: z.string() }, async ({ id }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +// 아래는 MCP SDK 문서의 보일러플레이트 코드입니다 +const PORT = 3001; +const app = express(); + +app.post('/', async (request: Request, response: Response) => { + // Stateless 모드에서는 각 요청마다 transport와 server 인스턴스를 새로 생성해야 완전한 격리가 보장됩니다. + // 단일 인스턴스 사용 시 여러 클라이언트 동시 접속 시 request ID 충돌이 발생할 수 있습니다. + + try { + const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + }); + response.on('close', async () => { + console.log('Request closed'); + await transport.close(); + await server.close(); + }); + await server.connect(transport); + await transport.handleRequest(request, response, request.body); + } catch (error) { + console.error('Error handling MCP request:', error); + if (!response.headersSent) { + response.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32_603, + message: 'Internal server error', + }, + id: null, + }); + } + } +}); + +// Stateless 모드에서는 SSE 알림 미지원 +app.get('/', async (request: Request, response: Response) => { + console.log('Received GET MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +// Stateless 모드에서는 세션 종료 불필요 +app.delete('/', async (request: Request, response: Response) => { + console.log('Received DELETE MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +app.listen(PORT); +``` + +서버 실행: + +```bash +npm start +``` + + + + +## MCP 서버 검사하기 \{#inspect-the-mcp-server} + +### MCP inspector 클론 및 실행 \{#clone-and-run-mcp-inspector} + +이제 MCP 서버가 실행 중이므로, MCP inspector를 사용해 도구가 노출되는지 확인할 수 있습니다. + +공식 MCP inspector v0.16.2에는 인증 (Authentication) 기능에 영향을 주는 버그가 있습니다. 이를 해결하기 위해 OAuth / OIDC 인증 플로우 관련 패치가 적용된 [MCP inspector 패치 버전](https://github.com/mcp-auth/inspector/tree/patch/0.16.2-fixes)을 제공합니다. 또한 공식 저장소에 PR도 제출하였습니다. + +MCP inspector를 실행하려면 (Node.js 필요): + +```bash +git clone https://github.com/mcp-auth/inspector.git -b patch/0.16.2-fixes +cd inspector +npm install +npm run dev +``` + +MCP inspector는 기본 브라우저에서 자동으로 열리며, 터미널 출력의 링크(예: `http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=458ae4a4...acab1907`)를 클릭해 직접 접근할 수도 있습니다. + +### MCP inspector를 MCP 서버에 연결 \{#connect-mcp-inspector-to-the-mcp-server} + +진행 전, MCP inspector에서 다음 설정을 확인하세요: + +- **Transport Type**: `Streamable HTTP`로 설정 +- **URL**: MCP 서버의 URL로 설정 (`http://localhost:3001`) + +이제 "Connect" 버튼을 클릭하여 MCP inspector가 MCP 서버에 연결되는지 확인하세요. 정상적으로 연결되면 MCP inspector에서 "Connected" 상태를 볼 수 있습니다. + +### 체크포인트: Todo 매니저 도구 실행 \{#checkpoint-run-todo-manager-tools} + +1. MCP inspector 상단 메뉴에서 "Tools" 탭 클릭 +2. "List Tools" 버튼 클릭 +3. `create-todo`, `get-todos`, `delete-todo` 도구가 페이지에 표시되어야 합니다. 클릭하여 도구 상세 보기 +4. 우측에 "Run Tool" 버튼이 보입니다. 클릭 후 필요한 파라미터를 입력해 도구 실행 +5. JSON 응답 `{"error": "Not implemented"}`가 표시되어야 합니다. + +![MCP inspector 첫 실행](/docs-assets/images/tutorials/todo-manager/inspector-first-run.png) + +## 인가 서버와 통합하기 \{#integrate-with-your-authorization-server} + +이 섹션을 완료하려면 다음 사항을 고려해야 합니다: + +
+**인가 서버의 발급자 (Issuer) URL** + +일반적으로 인가 서버의 기본 URL입니다. 예: `https://auth.example.com`. 일부 제공자는 `https://example.logto.app/oidc`와 같이 경로가 포함될 수 있으니, 제공자 문서를 확인하세요. + +
+ +
+**인가 서버 메타데이터 조회 방법** + +- 인가 서버가 [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) 또는 [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html)를 준수한다면, MCP Auth 내장 유틸리티로 자동 조회할 수 있습니다. +- 준수하지 않는 경우, MCP 서버 설정에서 메타데이터 URL 또는 엔드포인트를 수동 지정해야 합니다. 제공자 문서를 참고하세요. + +
+ +
+**MCP inspector를 인가 서버에 클라이언트로 등록하는 방법** + +- 인가 서버가 [동적 클라이언트 등록 (Dynamic Client Registration)](https://datatracker.ietf.org/doc/html/rfc7591)을 지원하면, MCP inspector가 자동으로 클라이언트로 등록됩니다. +- 지원하지 않는 경우, MCP inspector를 인가 서버에 수동으로 클라이언트로 등록해야 합니다. + +
+ +
+**토큰 요청 파라미터 이해하기** + +인가 서버마다 대상 리소스 및 권한 지정 방식이 다릅니다. 주요 패턴은 다음과 같습니다: + +- **리소스 지표 기반**: + + - `resource` 파라미터로 대상 API 지정 ([RFC 8707: OAuth 2.0을 위한 리소스 지표](https://datatracker.ietf.org/doc/html/rfc8707) 참고) + - 최신 OAuth 2.0 구현에서 일반적 + - 예시 요청: + ```json + { + "resource": "http://localhost:3001", + "scope": "create:todos read:todos" + } + ``` + - 서버는 요청된 리소스에 바인딩된 토큰 발급 + +- **Audience 기반**: + + - `audience` 파라미터로 토큰 수신자 지정 + - 리소스 지표와 유사하나 의미가 다름 + - 예시 요청: + ```json + { + "audience": "todo-api", + "scope": "create:todos read:todos" + } + ``` + +- **순수 스코프 기반**: + - resource/audience 파라미터 없이 스코프만 사용 + - 전통적인 OAuth 2.0 방식 + - 예시 요청: + ```json + { + "scope": "todo-api:create todo-api:read openid profile" + } + ``` + - 권한 네임스페이스를 위해 접두사 스코프 사용 + - 단순한 OAuth 2.0 구현에서 일반적 + +:::tip 모범 사례 + +- 제공자 문서에서 지원 파라미터 확인 +- 일부 제공자는 여러 방식을 동시에 지원 +- 리소스 지표는 audience 제한을 통해 더 나은 보안 제공 +- 가능하다면 리소스 지표 사용을 권장 + ::: + +
+ +제공자마다 세부 요구사항이 다를 수 있지만, 아래 단계에 따라 MCP inspector와 MCP 서버를 제공자별로 통합할 수 있습니다. + +### MCP inspector를 클라이언트로 등록 \{#register-mcp-inspector-as-a-client} + + + + +[Logto](https://logto.io)는 OpenID Connect 제공자로, 리소스 지표와 스코프를 지원하므로 `http://localhost:3001` 리소스 지표로 todo API를 안전하게 보호할 수 있습니다. + +Logto는 아직 동적 클라이언트 등록을 지원하지 않으므로, MCP inspector를 Logto 테넌트에 수동으로 클라이언트로 등록해야 합니다: + +1. MCP inspector에서 Authentication 설정으로 이동, "OAuth2.0 Flow" 설정을 클릭하고 **Redirect URI** 값을 복사하세요. 예: `http://localhost:6274/oauth/callback` +2. [Logto Console](https://cloud.logto.io) (또는 자체 호스팅 Logto Console)에 로그인 +3. "Applications" 탭에서 "Create application" 클릭. 페이지 하단에서 "Create app without framework" 클릭 +4. 애플리케이션 정보 입력 후 "Create application" 클릭: + - **애플리케이션 유형 선택**: "Single-page application" 선택 + - **애플리케이션 이름**: 예: "MCP Inspector" +5. "Settings / Redirect URIs" 섹션에 MCP inspector에서 복사한 **Redirect URI** 값 붙여넣기. 하단 바에서 "Save changes" 클릭 +6. 상단 카드에서 "App ID" 값을 복사 +7. MCP inspector로 돌아가 "OAuth2.0 Flow"의 "Client ID" 필드에 "App ID" 값 붙여넣기 +8. "Scope" 필드에 `create:todos read:todos delete:todos` 입력. Logto가 todo 매니저에 필요한 스코프가 포함된 액세스 토큰을 반환하도록 합니다. + + + + +:::note +이 가이드는 일반적인 OAuth 2.0 / OpenID Connect 제공자 통합 안내입니다. OIDC는 OAuth 2.0 위에 구축되어 있으므로 단계가 유사합니다. 제공자 문서를 참고하세요. +::: + +제공자가 동적 클라이언트 등록을 지원한다면 아래 8번 단계로 바로 진행, 그렇지 않으면 MCP inspector를 수동으로 클라이언트로 등록해야 합니다: + +1. MCP inspector에서 Authentication 설정으로 이동, "OAuth2.0 Flow" 설정을 클릭하고 **Redirect URI** 값을 복사하세요. 예: `http://localhost:6274/oauth/callback` + +2. 제공자 콘솔에 로그인 + +3. "Applications" 또는 "Clients" 섹션에서 새 애플리케이션 또는 클라이언트 생성 + +4. 클라이언트 유형이 필요하다면 "Single-page application" 또는 "Public client" 선택 + +5. 애플리케이션 생성 후 Redirect URI 설정. 복사한 **Redirect URI** 값 붙여넣기 + +6. 새 애플리케이션의 "Client ID" 또는 "Application ID" 복사 + +7. MCP inspector로 돌아가 "OAuth2.0 Flow"의 "Client ID" 필드에 "Client ID" 값 붙여넣기 + +8. "Scope" 필드에 todo 작업에 필요한 다음 스코프 입력: + +```text +create:todos read:todos delete:todos +``` + + + + +### MCP Auth 설정 \{#set-up-mcp-auth} + +먼저, MCP 서버 프로젝트에 MCP Auth SDK를 설치하세요. + + + + +```bash +uv add mcpauth==0.2.0b1 +``` + + + + +```bash +npm install mcp-auth@0.2.0-beta.1 +``` + + + + +이제 MCP 서버에서 MCP Auth를 초기화해야 합니다. 주요 단계는 두 가지입니다: + +1. **인가 서버 메타데이터 가져오기**: 이후 MCP Auth가 인가 서버가 발급한 액세스 토큰을 검증하고, 리소스 메타데이터에 인가 서버의 발급자 식별자를 포함하는 데 사용 +2. **보호된 리소스 메타데이터 구성**: MCP 서버의 리소스 식별자와 지원하는 스코프 정의 + +#### 1단계: 인가 서버 메타데이터 가져오기 \{#step-1-fetch-authorization-server-metadata\} + +OAuth / OIDC 명세에 따라, 인가 서버의 발급자 (Issuer) URL을 기반으로 인가 서버 메타데이터를 조회할 수 있습니다. + + + + + +Logto에서는 Logto Console의 애플리케이션 상세 페이지 "Endpoints & Credentials / Issuer endpoint" 섹션에서 발급자 URL을 확인할 수 있습니다. 예: `https://my-project.logto.app/oidc` + + + + + +OAuth 2.0 제공자의 경우: + +1. 제공자 문서에서 인가 서버 URL(발급자 URL 또는 base URL) 확인 +2. 일부 제공자는 `https://{your-domain}/.well-known/oauth-authorization-server`에서 노출 +3. 제공자 관리자 콘솔의 OAuth / API 설정에서 확인 + + + + + +이제 MCP Auth 유틸리티 함수로 인가 서버 메타데이터를 가져옵니다: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +issuer_url = "" # 인가 서버의 발급자 URL로 대체 + +# 인가 서버 구성 가져오기 +auth_server_config = fetch_server_config(issuer_url, AuthServerType.OIDC) # 또는 AuthServerType.OAUTH +``` + + + +```js +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const issuerUrl = ''; // 인가 서버의 발급자 URL로 대체 + +// 인가 서버 구성 가져오기 (OIDC Discovery) +const authServerConfig = await fetchServerConfig(issuerUrl, { type: 'oidc' }); // 또는 { type: 'oauth' } +``` + + + + +인가 서버 메타데이터를 가져오는 다른 방법이나 구성을 커스터마이즈하고 싶다면 [인가 서버 메타데이터 구성의 다른 방법](/docs/configure-server/mcp-auth#other-ways)을 참고하세요. + +#### 2단계: 보호된 리소스 메타데이터 구성 \{#step-2-configure-protected-resource-metadata} + +다음으로, MCP Auth 인스턴스 생성 시 보호된 리소스 메타데이터를 구성합니다. 이후 MCP 서버는 MCP Auth에 구성된 리소스 메타데이터를 노출합니다. + + + + +```python +# server.py + +# 기타 import... +from mcpauth.types import ResourceServerConfig, ResourceServerMetadata + +# 이 MCP 서버의 리소스 식별자 정의 +resource_id = "http://localhost:3001" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + # 이전 단계에서 가져온 인가 서버 메타데이터 + authorization_servers=[auth_server_config], + # MCP 서버가 이해하는 스코프 + scopes_supported=[ + "create:todos", + "read:todos", + "delete:todos" + ] + ) + ) +) +``` + + + +```js +// todo-manager.ts + +// 이 MCP 서버의 리소스 식별자 정의 +const resourceId = 'http://localhost:3001'; + +// MCP Auth에 보호된 리소스 메타데이터 구성 +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceId, + // 이전 단계에서 가져온 인가 서버 메타데이터 + authorizationServers: [authServerConfig], + // MCP 서버가 이해하는 스코프 + scopesSupported: [ + "create:todos", + "read:todos", + "delete:todos" + ] + } + } +}); +``` + + + + +### MCP 서버 업데이트 \{#update-mcp-server} + +거의 다 왔습니다! 이제 MCP Auth 라우트와 미들웨어 함수를 MCP 서버에 적용하고, 사용자의 스코프에 따라 todo 매니저 도구에 권한 기반 접근 제어를 구현합니다. + +먼저, 보호된 리소스 메타데이터 라우트를 적용하여 MCP 클라이언트가 MCP 서버에서 리소스 메타데이터를 조회할 수 있도록 합니다. + + + +```python +# server.py + +# ..기타 코드 + +app = Starlette( + routes=[ + # 보호된 리소스 메타데이터 라우트 설정 + # OAuth 클라이언트를 위한 이 리소스 서버의 메타데이터 노출 + *mcp_auth.resource_metadata_router().routes, + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +// 보호된 리소스 메타데이터 라우트 설정 +// OAuth 클라이언트를 위한 이 리소스 서버의 메타데이터 노출 +app.use(mcpAuth.protectedResourceMetadataRouter()); + +``` + + + +다음으로, MCP Auth 미들웨어를 MCP 서버에 적용합니다. 이 미들웨어는 들어오는 요청에 대해 인증 (Authentication) 및 인가 (Authorization)를 처리하여, 인가된 사용자만 todo 매니저 도구에 접근할 수 있도록 합니다. + + + +```python +# server.py + +# 기타 import... +from starlette.middleware import Middleware + +# 기타 코드... + +# 미들웨어 생성 +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', resource=resource_id, audience=resource_id)) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # MCP Auth 미들웨어 적용 + Mount("/", app=mcp.streamable_http_app(), middleware=[bearer_auth]), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// MCP Auth 미들웨어 적용 +app.use( + mcpAuth.bearerAuth('jwt', { + resource: resourceId, + audience: resourceId, + }) +); +``` + + + +이제 todo 매니저 도구 구현을 MCP Auth 미들웨어를 활용하여 인증 (Authentication) 및 인가 (Authorization)를 적용하도록 업데이트할 수 있습니다. + +도구 구현을 업데이트해봅시다. + + + +```python +# server.py + +# 기타 import... + +from typing import Any, List, Optional +from mcpauth.exceptions import MCPAuthBearerAuthException, BearerAuthExceptionCode +from mcpauth.types import AuthInfo, ResourceServerConfig, ResourceServerMetadata + +# 다음 섹션에서 언급 +from service import TodoService + +def assert_user_id(auth_info: Optional[AuthInfo]) -> str: + """auth_info에 유효한 사용자 ID가 있는지 확인하고 반환.""" + if not auth_info or not auth_info.subject: + raise Exception("Invalid auth info") + return auth_info.subject + +def has_required_scopes(user_scopes: List[str], required_scopes: List[str]) -> bool: + """사용자가 모든 필수 스코프를 가지고 있는지 확인.""" + return all(scope in user_scopes for scope in required_scopes) + +# TodoService 인스턴스 생성 +todo_service = TodoService() + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """새 todo 생성. 'create:todos' 스코프 필요.""" + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # 'create:todos' 스코프가 있어야 todo 생성 가능 + user_scopes = auth_info.scopes if auth_info else [] + if not has_required_scopes(user_scopes, ["create:todos"]): + raise MCPAuthBearerAuthException(BearerAuthExceptionCode.MISSING_REQUIRED_SCOPES) + + created_todo = todo_service.create_todo(content=content, owner_id=user_id) + return created_todo + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """ + todo 목록 조회. 'read:todos' 스코프가 있으면 전체, 없으면 본인 것만 조회. + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # 'read:todos' 스코프가 있으면 전체, 없으면 본인 것만 + user_scopes = auth_info.scopes if auth_info else [] + todo_owner_id = None if has_required_scopes(user_scopes, ["read:todos"]) else user_id + + todos = todo_service.get_all_todos(todo_owner_id) + return {"todos": todos} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """ + ID로 todo 삭제. 사용자는 자신의 todo만 삭제 가능. + 'delete:todos' 스코프가 있으면 모든 todo 삭제 가능. + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + todo = todo_service.get_todo_by_id(id) + + if not todo: + return {"error": "Failed to delete todo"} + + # 사용자는 자신의 todo만 삭제 가능 + # 'delete:todos' 스코프가 있으면 모든 todo 삭제 가능 + user_scopes = auth_info.scopes if auth_info else [] + if todo.owner_id != user_id and not has_required_scopes(user_scopes, ["delete:todos"]): + return {"error": "Failed to delete todo"} + + deleted_todo = todo_service.delete_todo(id) + + if deleted_todo: + return { + "message": f"Todo {id} deleted", + "details": deleted_todo + } + else: + return {"error": "Failed to delete todo"} +``` + + + +```js +// todo-manager.ts + +// 기타 import... +import assert from 'node:assert'; +import { fetchServerConfig, MCPAuth, MCPAuthBearerAuthError } from 'mcp-auth'; +import { type AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js'; + +// 다음 섹션에서 언급 +import { TodoService } from './todo-service.js'; + +const assertUserId = (authInfo?: AuthInfo) => { + const { subject } = authInfo ?? {}; + assert(subject, 'Invalid auth info'); + return subject; +}; + +const hasRequiredScopes = (userScopes: string[], requiredScopes: string[]): boolean => { + return requiredScopes.every((scope) => userScopes.includes(scope)); +}; + +const todoService = new TodoService(); + +server.tool( + 'create-todo', + '새 todo 생성', + { content: z.string() }, + ({ content }: { content: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * 'create:todos' 스코프가 있어야 todo 생성 가능 + */ + if (!hasRequiredScopes(authInfo?.scopes ?? [], ['create:todos'])) { + throw new MCPAuthBearerAuthError('missing_required_scopes'); + } + + const createdTodo = todoService.createTodo({ content, ownerId: userId }); + + return { + content: [{ type: 'text', text: JSON.stringify(createdTodo) }], + }; + } +); + +server.tool('get-todos', '모든 todo 목록 조회', ({ authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * 'read:todos' 스코프가 있으면 전체(todoOwnerId = undefined) + * 없으면 본인 것만(todoOwnerId = userId) + */ + const todoOwnerId = hasRequiredScopes(authInfo?.scopes ?? [], ['read:todos']) + ? undefined + : userId; + + const todos = todoService.getAllTodos(todoOwnerId); + + return { + content: [{ type: 'text', text: JSON.stringify(todos) }], + }; +}); + +server.tool( + 'delete-todo', + 'ID로 todo 삭제', + { id: z.string() }, + ({ id }: { id: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + const todo = todoService.getTodoById(id); + + if (!todo) { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Failed to delete todo' }) }], + }; + } + + /** + * 사용자는 자신의 todo만 삭제 가능 + * 'delete:todos' 스코프가 있으면 모든 todo 삭제 가능 + */ + if (todo.ownerId !== userId && !hasRequiredScopes(authInfo?.scopes ?? [], ['delete:todos'])) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ error: 'Failed to delete todo' }), + }, + ], + }; + } + + const deletedTodo = todoService.deleteTodo(id); + + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + message: `Todo ${id} deleted`, + details: deletedTodo, + }), + }, + ], + }; + } +); +``` + + + +이제 위 코드에서 사용된 "Todo 서비스"를 구현합니다: + + + + +Todo 서비스용 `service.py` 파일을 생성하세요: + +```python +""" +데모용 간단한 Todo 서비스. +메모리 내 리스트에 todo를 저장합니다. +""" + +from datetime import datetime +from typing import List, Optional, Dict, Any +import random +import string + +class Todo: + """todo 항목을 나타냅니다.""" + + def __init__(self, id: str, content: str, owner_id: str, created_at: str): + self.id = id + self.content = content + self.owner_id = owner_id + self.created_at = created_at + + def to_dict(self) -> Dict[str, Any]: + """todo를 JSON 직렬화를 위한 dict로 변환.""" + return { + "id": self.id, + "content": self.content, + "ownerId": self.owner_id, + "createdAt": self.created_at + } + + +class TodoService: + """데모용 간단한 Todo 서비스.""" + + def __init__(self): + self._todos: List[Todo] = [] + + def get_all_todos(self, owner_id: Optional[str] = None) -> List[Dict[str, Any]]: + """ + 모든 todo 조회, owner_id로 필터링 가능. + + Args: + owner_id: 지정 시 해당 사용자의 todo만 반환 + + Returns: + todo dict 리스트 + """ + if owner_id: + filtered_todos = [todo for todo in self._todos if todo.owner_id == owner_id] + return [todo.to_dict() for todo in filtered_todos] + return [todo.to_dict() for todo in self._todos] + + def get_todo_by_id(self, todo_id: str) -> Optional[Todo]: + """ + ID로 todo 조회. + + Args: + todo_id: 조회할 todo의 ID + + Returns: + 찾으면 Todo 객체, 없으면 None + """ + for todo in self._todos: + if todo.id == todo_id: + return todo + return None + + def create_todo(self, content: str, owner_id: str) -> Dict[str, Any]: + """ + 새 todo 생성. + + Args: + content: todo 내용 + owner_id: todo 소유자 ID + + Returns: + 생성된 todo의 dict 표현 + """ + todo = Todo( + id=self._generate_id(), + content=content, + owner_id=owner_id, + created_at=datetime.now().isoformat() + ) + self._todos.append(todo) + return todo.to_dict() + + def delete_todo(self, todo_id: str) -> Optional[Dict[str, Any]]: + """ + ID로 todo 삭제. + + Args: + todo_id: 삭제할 todo의 ID + + Returns: + 삭제된 todo의 dict 표현(성공 시), 없으면 None + """ + for i, todo in enumerate(self._todos): + if todo.id == todo_id: + deleted_todo = self._todos.pop(i) + return deleted_todo.to_dict() + return None + + def _generate_id(self) -> str: + """todo용 랜덤 ID 생성.""" + return ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)) +``` + + + + +Todo 서비스용 `todo-service.ts` 파일을 생성하세요: + +```ts +// todo-service.ts + +type Todo = { + id: string; + content: string; + ownerId: string; + createdAt: string; +}; + +/** + * 데모용 간단한 Todo 서비스. + * 메모리 배열에 todo 저장 + */ +export class TodoService { + private readonly todos: Todo[] = []; + + getAllTodos(ownerId?: string): Todo[] { + if (ownerId) { + return this.todos.filter((todo) => todo.ownerId === ownerId); + } + return this.todos; + } + + getTodoById(id: string): Todo | undefined { + return this.todos.find((todo) => todo.id === id); + } + + createTodo({ content, ownerId }: { content: string; ownerId: string }): Todo { + const todo: Todo = { + id: this.genId(), + content, + ownerId, + createdAt: new Date().toISOString(), + }; + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + this.todos.push(todo); + return todo; + } + + deleteTodo(id: string): Todo | undefined { + const index = this.todos.findIndex((todo) => todo.id === id); + + if (index === -1) { + return undefined; + } + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + const [deleted] = this.todos.splice(index, 1); + return deleted; + } + + private genId(): string { + return Math.random().toString(36).slice(2, 10); + } +} +``` + + + + +🎉 축하합니다! 인증 (Authentication) 및 인가 (Authorization)가 적용된 완전한 MCP 서버를 성공적으로 구현했습니다! + +샘플 코드를 참고할 수도 있습니다: + + + + +:::info +[MCP Auth Python SDK 저장소](https://github.com/mcp-auth/python/tree/master/samples/current/todo-manager)에서 MCP 서버(OIDC 버전) 전체 코드를 확인하세요. +::: + + + + +:::info +[MCP Auth Node.js SDK 저장소](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src)에서 MCP 서버(OIDC 버전) 전체 코드를 확인하세요. +::: + + + + +## 체크포인트: `todo-manager` 도구 실행 \{#checkpoint-run-the-todo-manager-tools} + +MCP 서버를 재시작하고 브라우저에서 MCP inspector를 엽니다. "Connect" 버튼을 클릭하면 인가 서버의 로그인 페이지로 리디렉션됩니다. + +로그인 후 MCP inspector로 돌아오면, 이전 체크포인트에서 했던 것처럼 todo 매니저 도구를 실행해보세요. 이번에는 인증된 사용자 아이덴티티로 도구를 사용할 수 있습니다. 도구의 동작은 사용자에게 할당된 역할과 권한에 따라 달라집니다: + +- **User**(오직 `create:todos` 스코프만 가진 경우)로 로그인하면: + - `create-todo` 도구로 새 todo 생성 가능 + - 자신의 todo만 조회 및 삭제 가능 + - 다른 사용자의 todo는 볼 수 없고 삭제도 불가 + +- **Admin**(모든 스코프: `create:todos`, `read:todos`, `delete:todos` 보유)로 로그인하면: + - 새 todo 생성 가능 + - `get-todos` 도구로 시스템의 모든 todo 조회 가능 + - `delete-todo` 도구로 소유자와 상관없이 모든 todo 삭제 가능 + +다른 권한 수준을 테스트하려면: + +1. 현재 세션에서 로그아웃(MCP inspector의 "Disconnect" 클릭) +2. 다른 역할/권한을 가진 사용자 계정으로 로그인 +3. 동일한 도구를 다시 실행하여 권한에 따라 동작이 어떻게 달라지는지 확인 + +이렇게 하면 역할 기반 접근 제어 (RBAC)가 실제로 어떻게 동작하는지 확인할 수 있습니다. + +![MCP inspector todo 매니저 도구 결과](/docs-assets/images/tutorials/todo-manager/result.png) + + + + +:::info +[MCP Auth Python SDK 저장소](https://github.com/mcp-auth/python)에서 MCP 서버(OIDC 버전) 전체 코드를 확인하세요. +::: + + + + +:::info +[MCP Auth Node.js SDK 저장소](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src)에서 MCP 서버(OIDC 버전) 전체 코드를 확인하세요. +::: + + + + +## 마무리 (Closing notes) \{#closing-notes} + +🎊 축하합니다! 튜토리얼을 성공적으로 완료했습니다. 지금까지 한 일을 요약해봅시다: + +- todo 관리 도구(`create-todo`, `get-todos`, `delete-todo`)가 포함된 기본 MCP 서버 설정 +- 사용자와 관리자를 위한 다양한 권한 수준의 역할 기반 접근 제어 (RBAC) 구현 +- MCP Auth를 사용하여 MCP 서버를 인가 서버와 통합 +- MCP Inspector를 구성하여 사용자를 인증하고, 스코프가 포함된 액세스 토큰으로 도구 호출 + +MCP Auth를 최대한 활용하려면 다른 튜토리얼과 문서도 꼭 확인해보세요. diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/README.mdx b/i18n/pt-BR/docusaurus-plugin-content-docs/current/README.mdx new file mode 100644 index 0000000..2b2b0bb --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/README.mdx @@ -0,0 +1,297 @@ +--- +sidebar_position: 1 +sidebar_label: Primeiros passos +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# Primeiros passos + +:::info Suporte à especificação de autorização MCP +Esta versão oferece suporte à [especificação de autorização MCP (versão 2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization). +::: + + +## Escolha um provedor compatível com OAuth 2.1 ou OpenID Connect \{#choose-a-compatible-oauth-2-1-or-openid-connect-provider} + +A especificação MCP possui [requisitos específicos](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#standards-compliance) para autorização. O mecanismo de autorização é baseado em especificações estabelecidas, implementando um subconjunto selecionado de seus recursos para garantir segurança e interoperabilidade, mantendo a simplicidade: + +- OAuth 2.1 IETF DRAFT ([draft-ietf-oauth-v2-1-13](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13)) +- OAuth 2.0 Authorization Server Metadata ([RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)) +- OAuth 2.0 Dynamic Client Registration Protocol ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) +- OAuth 2.0 Protected Resource Metadata ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)) + +Essas especificações trabalham juntas para fornecer uma estrutura de autorização segura e padronizada para implementações MCP. + +Você pode conferir a [lista de provedores compatíveis com MCP](/provider-list) para ver se seu provedor é suportado. + +## Instale o MCP Auth SDK \{#install-mcp-auth-sdk} + +O MCP Auth está disponível para Python e TypeScript. Avise-nos se precisar de suporte para outra linguagem ou framework! + + + + +```bash +pip install mcpauth +``` + +Ou qualquer outro gerenciador de pacotes de sua preferência, como pipenv ou poetry. + + + + +```bash +npm install mcp-auth +``` + +Ou qualquer outro gerenciador de pacotes de sua preferência, como pnpm ou yarn. + + + + +## Inicialize o MCP Auth \{#init-mcp-auth} + +O primeiro passo é definir seu identificador de recurso e configurar o servidor de autorização que será confiável para autenticação. O MCP Auth agora opera no modo servidor de recursos, em conformidade com a especificação MCP atualizada que exige OAuth 2.0 Protected Resource Metadata (RFC 9728). + +Se seu provedor estiver em conformidade com: + +- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +Você pode usar a função integrada para buscar os metadados e inicializar a instância do MCP Auth: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType, ResourceServerConfig, ResourceServerMetadata +from mcpauth.utils import fetch_server_config + +# 1. Defina seu identificador de recurso e busque a configuração para seu servidor de autorização confiável. +resource_id = "https://api.example.com/notes" +auth_server_config = fetch_server_config("https://auth.logto.io/oidc", AuthServerType.OIDC) + +# 2. Inicialize o MCPAuth no modo servidor de recursos. +# `protected_resources` pode ser um único objeto ou uma lista para múltiplos recursos. +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +// 1. Defina seu identificador de recurso e busque a configuração para seu servidor de autorização confiável. +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +// 2. Inicialize o MCPAuth no modo servidor de recursos. +// `protectedResources` pode ser um único objeto ou um array para múltiplos recursos. +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +Para outras formas de configurar os metadados do servidor de autorização, incluindo URLs de metadados personalizados, transpilações de dados ou especificação manual de metadados, confira [Outras formas de configurar o MCP Auth](./configure-server/mcp-auth.mdx#other-ways). + +## Monte o endpoint de metadados do recurso protegido \{#mount-the-protected-resource-metadata-endpoint} + +Para estar em conformidade com a especificação MCP atualizada, o MCP Auth monta o endpoint OAuth 2.0 Protected Resource Metadata (RFC 9728) em seu servidor MCP. Este endpoint permite que os clientes descubram: + +- Quais servidores de autorização podem emitir tokens válidos para seus recursos protegidos +- Quais escopos são suportados para cada recurso +- Outros metadados necessários para validação adequada de tokens + +O caminho do endpoint é determinado automaticamente pelo componente de caminho do seu identificador de recurso: + +- **Sem caminho**: `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **Com caminho**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + +O servidor MCP agora **atua como um servidor de recursos** que valida tokens e fornece metadados sobre seus recursos protegidos, confiando inteiramente em servidores de autorização externos para autenticação e autorização. + +Você pode usar o método fornecido pelo SDK para montar este endpoint: + + + + +```python +from starlette.applications import Starlette + +# Monte o roteador para servir os Metadados do Recurso Protegido. +# Para o recurso "https://api.example.com" → endpoint: /.well-known/oauth-protected-resource +# Para o recurso "https://api.example.com/notes" → endpoint: /.well-known/oauth-protected-resource/notes +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// Monte o roteador para servir os Metadados do Recurso Protegido. +// Para o recurso "https://api.example.com" → endpoint: /.well-known/oauth-protected-resource +// Para o recurso "https://api.example.com/notes" → endpoint: /.well-known/oauth-protected-resource/notes +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + + +## Use o middleware Bearer auth \{#use-the-bearer-auth-middleware} + +Depois que a instância do MCP Auth for inicializada, você pode aplicar o middleware Bearer auth para proteger suas rotas MCP. O middleware agora exige a especificação de qual recurso o endpoint pertence, permitindo a validação adequada do token: + +:::note Validação do Público (Audience) +O parâmetro `audience` é **obrigatório** pela especificação OAuth 2.0 para validação segura de tokens. No entanto, atualmente é **opcional** para manter a compatibilidade com servidores de autorização que ainda não suportam identificadores de recurso. Por motivos de segurança, **sempre inclua o parâmetro audience** quando possível. Versões futuras tornarão a validação do público obrigatória para cumprir totalmente a especificação. +::: + + + + +```python +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount + +# Crie o middleware para proteger seu servidor MCP com a política específica do recurso. +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', + resource=resource_id, + audience=resource_id, # Habilite a validação do público para segurança + required_scopes=['read:notes'] +)) + +# Monte o roteador para servir os Metadados do Recurso Protegido e proteger o servidor MCP. +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # Proteja o servidor MCP com o middleware Bearer auth. + Mount("/", app=mcp.sse_app(), middleware=[bearer_auth]), + ], +) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// Monte o roteador para servir os Metadados do Recurso Protegido. +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Proteja um endpoint de API usando a política específica do recurso. +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, // Habilite a validação do público para segurança + requiredScopes: ['read:notes'], + }), + (req, res) => { + // Se o token for válido, `req.auth` será preenchido com suas reivindicações. + console.log('Informações de autenticação:', req.auth); + res.json({ notes: [] }); + }, +); + +app.listen(3000); +``` + + + + +Nos exemplos acima, especificamos o tipo de token `jwt` e o identificador do recurso. O middleware validará automaticamente o token JWT em relação aos servidores de autorização confiáveis configurados para esse recurso específico e preencherá as informações do usuário autenticado. + +:::info +Nunca ouviu falar de JWT (JSON Web Token) antes? Não se preocupe, você pode continuar lendo a documentação e explicaremos quando necessário. Você também pode conferir o [Auth Wiki](https://auth.wiki/jwt) para uma introdução rápida. +::: + +Para mais informações sobre a configuração do Bearer auth, confira [Configurar Bearer auth](./configure-server/bearer-auth.mdx). + +## Recupere as informações de autenticação na sua implementação MCP \{#retrieve-the-auth-info-in-your-mcp-implementation} + +Depois que o middleware Bearer auth for aplicado, você poderá acessar as informações do usuário (ou identidade) autenticado em sua implementação MCP: + + + + +O MCP Auth armazenará as informações do usuário autenticado em uma variável de contexto após a autenticação bem-sucedida, uma vez que o middleware Bearer auth for aplicado. Você pode acessá-la em seus handlers de ferramentas MCP assim: + +```python +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP() + +# Inicialize com MCP Auth conforme mostrado nos exemplos anteriores +# ... + +@mcp.tool() +def add(a: int, b: int): + """ + Uma ferramenta que soma dois números. + As informações do usuário autenticado estarão disponíveis no contexto. + """ + auth_info = mcp_auth.auth_info # Acesse as informações de autenticação no contexto atual + if auth_info: + print(f"Usuário autenticado: {auth_info.claims}") + return a + b +``` + + + + +O segundo argumento do handler da ferramenta conterá o objeto `authInfo`, que inclui as informações do usuário autenticado: + +```ts +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { z } from 'zod'; + +const server = new McpServer(/* ... */); + +// Inicialize com MCP Auth conforme mostrado nos exemplos anteriores +// ... + +server.tool('add', { a: z.number(), b: z.number() }, async ({ a, b }, { authInfo }) => { + // Agora você pode usar o objeto `authInfo` para acessar as informações autenticadas +}); +``` + + + + +## Próximos passos \{#next-steps} + +Continue lendo para aprender um exemplo de ponta a ponta de como integrar o MCP Auth ao seu servidor MCP e como lidar com o fluxo de autenticação em clientes MCP. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx b/i18n/pt-BR/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx new file mode 100644 index 0000000..cab3cad --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx @@ -0,0 +1,280 @@ +--- +sidebar_position: 2 +sidebar_label: Bearer auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# Configurar autenticação Bearer no servidor MCP + +Com a especificação MCP mais recente, seu servidor MCP atua como um **Resource Server (Servidor de Recursos)** que valida tokens de acesso para recursos protegidos. O MCP Auth oferece várias formas de configurar a autorização Bearer: + +- Modo [JWT (JSON Web Token)](https://auth.wiki/jwt): Um método de autorização integrado que verifica JWTs com afirmações de reivindicações. +- Modo personalizado: Permite que você implemente sua própria lógica de autorização. + +O middleware de autenticação Bearer agora exige a especificação de qual recurso o endpoint pertence, permitindo a validação adequada do token em relação aos servidores de autorização configurados. + +## Configurar autenticação Bearer com modo JWT \{#configure-bearer-auth-with-jwt-mode} + +Se seu provedor OAuth / OIDC emite JWTs para autorização, você pode usar o modo JWT integrado no MCP Auth. Ele verifica a assinatura do JWT, expiração e outras reivindicações que você especificar; em seguida, preenche as informações de autenticação no contexto da requisição para processamento posterior em sua implementação MCP. + +### Validação de escopo (Scope validation) \{#scope-validation} + +Aqui está um exemplo de validação básica de escopo: + + + + +```python +from mcpauth import MCPAuth +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP("MyMCPServer") +mcp_auth = MCPAuth( + # Initialize with your auth server config +) +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", # Especifique a qual recurso este endpoint pertence + audience="https://api.example.com", # Habilite a validação do público para segurança + required_scopes=["read", "write"] # [!code highlight] +) + +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + /* ... */ +}); +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // Especifique a qual recurso este endpoint pertence + audience: 'https://api.example.com', // Habilite a validação do público para segurança + requiredScopes: ['read', 'write'] // [!code highlight] +}); + +app.use('/mcp', bearerAuth, (req, res) => { + // Agora `req.auth` contém as informações de autenticação + console.log(req.auth); +}); +``` + + + + +No exemplo acima, especificamos que o JWT exige os escopos `read` e `write`. Se o JWT não contiver **nenhum** desses escopos, a requisição será rejeitada com um erro 403 Forbidden. + +### Validação de público (Audience validation) (RFC 8707) \{#audience-validation-rfc-8707} + +Para validação segura do token, você deve sempre incluir a validação de público especificando o parâmetro `audience`. Isso valida a reivindicação `aud` (público) no JWT para garantir que o token foi emitido especificamente para o recurso do seu servidor MCP. + +:::note Audience Validation +O parâmetro `audience` é **obrigatório** pela especificação OAuth 2.0 para validação segura do token. No entanto, atualmente é **opcional** para manter a compatibilidade com servidores de autorização que ainda não suportam identificadores de recurso. Por motivos de segurança, **sempre inclua o parâmetro audience** quando possível. Versões futuras tornarão a validação de público obrigatória para cumprir totalmente a especificação. +::: + +O valor do público geralmente deve corresponder ao seu identificador de recurso: + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", # Especifique a qual recurso este endpoint pertence + audience="https://api.example.com", # Habilite a validação do público para segurança [!code highlight] + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // Especifique a qual recurso este endpoint pertence + audience: 'https://api.example.com', // Habilite a validação do público para segurança [!code highlight] + requiredScopes: ['read', 'write'], +}); +``` + + + + +No exemplo acima, o MCP Auth validará **tanto** a reivindicação `aud` no JWT quanto os escopos necessários. + +### Forneça opções personalizadas para a verificação do JWT \{#provide-custom-options-to-the-jwt-verification} + +Você também pode fornecer opções personalizadas para a biblioteca de verificação JWT subjacente: + + + + +No SDK Python, usamos [PyJWT](https://pyjwt.readthedocs.io/en/stable/) para verificação de JWT. Você pode usar as seguintes opções: + +- `leeway`: Permite uma certa margem ao verificar o tempo de expiração do JWT (em segundos). O padrão é 60 segundos. + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", + audience="https://api.example.com", + required_scopes=["read", "write"], + leeway=10, # Reduza a diferença de relógio permitindo 10 segundos de margem [!code highlight] +) +``` + + + + +No SDK Node.js, usamos a biblioteca [jose](https://github.com/panva/jose) para verificação de JWT. Você pode fornecer as seguintes opções: + +- `jwtVerify`: Opções para o processo de verificação do JWT (função `jwtVerify` do `jose`). +- `remoteJwtSet`: Opções para buscar o conjunto JWT remoto (função `createRemoteJWKSet` do `jose`). + +```ts {5-10} +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', + requiredScopes: ['read', 'write'], + jwtVerify: { + clockTolerance: 60, // Permite uma diferença de relógio de 60 segundos + }, + remoteJwtSet: { + timeoutDuration: 10 * 1000, // Timeout de 10 segundos para busca do JWT remoto + }, +}); +``` + + + + +## Configurar autenticação Bearer com verificação personalizada \{#configure-bearer-auth-with-custom-verification} + +Se seu provedor OAuth / OIDC não emite JWTs, ou se você deseja implementar sua própria lógica de autorização, o MCP Auth permite criar uma função de verificação personalizada: + +:::info +Como o middleware de autenticação Bearer verificará o emissor (`iss`), público (`aud`) e escopos necessários (`scope`) com o resultado da verificação fornecido, não há necessidade de implementar essas verificações em sua função de verificação personalizada. Você pode focar em verificar a validade do token (por exemplo, assinatura, expiração, etc.) e retornar o objeto de informações de autenticação. +::: + + + + +```python +from mcpauth.exceptions import MCPAuthJwtVerificationException, MCPAuthJwtVerificationExceptionCode +from mcpauth.types import AuthInfo + +async def custom_verification(token: str) -> AuthInfo: + # Implemente sua lógica personalizada de verificação aqui + info = await verify_token(token) + if not info: + raise MCPAuthJwtVerificationException( + MCPAuthJwtVerificationExceptionCode.JWT_VERIFICATION_FAILED + ) + return info # Retorne o objeto de informações de autenticação + +bearer_auth = mcp_auth.bearer_auth_middleware( + custom_verification, + resource="https://api.example.com", + audience="https://api.example.com", # Habilite a validação do público para segurança + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth( + async (token) => { + // Implemente sua lógica personalizada de verificação aqui + const info = await verifyToken(token); + if (!info) { + throw new MCPAuthJwtVerificationError('jwt_verification_failed'); + } + return info; // Retorne o objeto de informações de autenticação + }, + { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // Habilite a validação do público para segurança + requiredScopes: ['read', 'write'] + } +); +``` + + + + +## Aplicar autenticação Bearer em seu servidor MCP \{#apply-bearer-auth-in-your-mcp-server} + +Para proteger seu servidor MCP com autenticação Bearer, você precisa aplicar o middleware de autenticação Bearer à sua instância do servidor MCP. + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", + audience="https://api.example.com", # Habilite a validação do público para segurança + required_scopes=["read", "write"] +) +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```js +const app = express(); +app.use(mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // Habilite a validação do público para segurança + requiredScopes: ['read', 'write'] +})); +``` + + + + +Isso garantirá que todas as requisições recebidas sejam autenticadas e autorizadas de acordo com as configurações Bearer auth, e as informações de autenticação estarão disponíveis no contexto da requisição. + +Você pode então acessar as informações em sua implementação do servidor MCP: + + + + +```python +@mcp.tool() +async def whoami() -> dict: + # `mcp_auth.auth_info` é o objeto de contexto para a requisição atual + auth_info = mcp_auth.auth_info + print(f"Usuário autenticado: {auth_info.subject}") + return {"subject": auth_info.subject} +``` + + + + +```js +// `authInfo` será carregado a partir do objeto `req.auth` +server.tool('whoami', ({ authInfo }) => { + console.log(`Usuário autenticado: ${authInfo.subject}`); + return { subject: authInfo.subject }; +}); +``` + + + diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx b/i18n/pt-BR/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx new file mode 100644 index 0000000..1e8c65c --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx @@ -0,0 +1,290 @@ +--- +sidebar_position: 1 +sidebar_label: MCP Auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# Configurar MCP Auth no servidor MCP + +Com a última [Especificação MCP (2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18), seu servidor MCP atua como um **Servidor de Recursos** que valida tokens de acesso emitidos por servidores de autorização externos. + +Para configurar o MCP Auth, você precisa de dois passos principais: +1. **Configurar os metadados do servidor de autorização** - Defina quais servidores de autorização podem emitir tokens válidos para seu servidor MCP e oriente os clientes MCP sobre onde obter tokens de acesso +2. **Configurar os metadados do recurso protegido** - Defina seu servidor MCP como um recurso protegido com escopos suportados + +## Passo 1: Configurar os metadados do servidor de autorização \{#configure-authorization-server-metadata} + +### Busca automática de metadados \{#automatic-metadata-fetching} + +A maneira mais fácil de configurar os metadados do servidor de autorização é usando as funções integradas que buscam os metadados a partir de URLs bem conhecidas. Se seu provedor estiver em conformidade com um dos seguintes padrões: + +- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +Você pode usar o `fetchServerConfig` para recuperar automaticamente os metadados fornecendo a URL do `issuer`: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +# Buscar metadados do servidor de autorização +auth_server_config = fetch_server_config( + "https://auth.logto.io/oidc", + AuthServerType.OIDC # ou AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +// Buscar metadados do servidor de autorização +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); // ou 'oauth' +``` + + + + +Se o seu issuer incluir um caminho, o comportamento difere um pouco entre OAuth 2.0 e OpenID Connect: + +- **OAuth 2.0**: A URL bem conhecida é anexada ao **domínio** do issuer. Por exemplo, se seu issuer for `https://my-project.logto.app/oauth`, a URL bem conhecida será `https://auth.logto.io/.well-known/oauth-authorization-server/oauth`. +- **OpenID Connect**: A URL bem conhecida é anexada diretamente ao **issuer**. Por exemplo, se seu issuer for `https://my-project.logto.app/oidc`, a URL bem conhecida será `https://auth.logto.io/oidc/.well-known/openid-configuration`. + +### Outras formas de configurar os metadados do servidor de autorização \{#other-ways} + +#### Transpilação de dados personalizada \{#custom-data-transpilation} + +Em alguns casos, os metadados retornados pelo provedor podem não estar no formato esperado. Se você tiver certeza de que o provedor está em conformidade, pode usar a opção `transpile_data` para modificar os metadados antes de serem utilizados: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +auth_server_config = fetch_server_config( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfig('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +Isso permite modificar o objeto de metadados antes de ser utilizado pelo MCP Auth. Por exemplo, você pode adicionar ou remover campos, alterar seus valores ou convertê-los para um formato diferente. + +#### Buscar metadados de uma URL específica \{#fetch-metadata-from-a-specific-url} + +Se seu provedor possui uma URL de metadados específica em vez das padrões, você pode usá-la de forma semelhante: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC # ou AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfigByWellKnownUrl } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { type: 'oidc' }); // ou 'oauth' +``` + + + + +#### Buscar metadados de uma URL específica com transpilação de dados personalizada \{#fetch-metadata-from-a-specific-url-with-custom-data-transpilation} + +Em alguns casos, a resposta do provedor pode estar malformada ou não estar em conformidade com o formato de metadados esperado. Se você tiver certeza de que o provedor está em conformidade, pode transpilar os metadados via opção de configuração: + + + + +```python +from mcpauth.config import AuthServerType, fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +#### Fornecer metadados manualmente \{#manually-provide-metadata} + +Se seu provedor não suporta busca de metadados, você pode fornecer manualmente o objeto de metadados: + + + + +```python +from mcpauth.config import AuthServerConfig, AuthServerType, AuthorizationServerMetadata + +auth_server_config = AuthServerConfig( + type=AuthServerType.OIDC, # ou AuthServerType.OAUTH + metadata=AuthorizationServerMetadata( + issuer='', + authorization_endpoint='', + # ... outros campos de metadados + ), +) +``` + + + + +```ts +const authServerConfig = { + metadata: { + issuer: '', + // Os campos de metadados devem estar em camelCase + authorizationEndpoint: '', + // ... outros campos de metadados + }, + type: 'oidc', // ou 'oauth' +}; +``` + + + + +## Passo 2: Configurar os metadados do recurso protegido \{#configure-protected-resource-metadata} + +Após configurar os metadados do servidor de autorização, você precisa inicializar o MCPAuth como um Servidor de Recursos definindo os metadados dos seus recursos protegidos. + +Este passo segue a especificação [RFC 9728 (OAuth 2.0 Protected Resource Metadata)](https://datatracker.ietf.org/doc/html/rfc9728) para descrever seu servidor MCP como um recurso protegido: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import ResourceServerConfig, ResourceServerMetadata + +# Defina seu identificador de recurso +resource_id = "https://api.example.com/notes" + +# Inicialize o MCPAuth no modo servidor de recursos +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], # Usando a configuração do Passo 1 + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth } from 'mcp-auth'; + +// Defina seu identificador de recurso +const resourceIdentifier = 'https://api.example.com/notes'; + +// Inicialize o MCPAuth no modo servidor de recursos +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], // Usando a configuração do Passo 1 + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +Para múltiplos recursos, você pode fornecer um array de recursos protegidos, cada um com sua própria configuração de metadados. + +A configuração mostrada acima cobre a configuração básica. Para parâmetros de metadados mais avançados, consulte [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata). + +## Passo 3: Montar o endpoint de metadados do recurso protegido \{#mount-the-protected-resource-metadata-endpoint} + +Monte o roteador para servir o endpoint de metadados do recurso protegido. O caminho do endpoint é determinado automaticamente pelo componente de caminho do seu identificador de recurso: + +- **Sem caminho**: `https://api.example.com` → `/.well-known/oauth-protected-resource` +- **Com caminho**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + + + + +```python +from starlette.applications import Starlette +from mcpauth import MCPAuth + +mcp_auth = MCPAuth({/* ... */}) + +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +const mcpAuth = new MCPAuth({/* ... */}); + +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/README.md new file mode 100644 index 0000000..164f971 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/README.md @@ -0,0 +1,59 @@ +--- +sidebar_label: Node.js SDK +--- + +# Referência do MCP Auth Node.js SDK + +## Classes {#classes} + +- [MCPAuth](/references/js/classes/MCPAuth.md) +- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) +- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) +- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) +- [MCPAuthError](/references/js/classes/MCPAuthError.md) +- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) + +## Apelidos de Tipos (Type Aliases) {#type-aliases} + +- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) +- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) +- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) +- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) +- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) +- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) +- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) +- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) +- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) +- [AuthServerType](/references/js/type-aliases/AuthServerType.md) +- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) +- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) +- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) +- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) +- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) +- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) +- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) +- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) +- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) +- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) +- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) +- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) + +## Variáveis {#variables} + +- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) +- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) +- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) +- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) +- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) +- [defaultValues](/references/js/variables/defaultValues.md) +- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) +- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) +- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) +- [validateServerConfig](/references/js/variables/validateServerConfig.md) + +## Funções {#functions} + +- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) +- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) +- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) +- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md new file mode 100644 index 0000000..c9bfb0f --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md @@ -0,0 +1,301 @@ +--- +sidebar_label: MCPAuth +--- + +# Classe: MCPAuth + +A classe principal da biblioteca mcp-auth. Atua como uma fábrica e registro para criar +políticas de autenticação para seus recursos protegidos. + +Ela é inicializada com as configurações do seu servidor e fornece um método `bearerAuth` +para gerar middleware Express para autenticação baseada em token. + +## Exemplo {#example} + +### Uso no modo `resource server` {#usage-in-resource-server-mode} + +Esta é a abordagem recomendada para novas aplicações. + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); + +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +const mcpAuth = new MCPAuth({ + // `protectedResources` pode ser um único objeto de configuração ou um array deles. + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); + +// Monta o router para lidar com o Metadata de Recurso Protegido +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Protege um endpoint de API para o recurso configurado +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, // Especifique a qual recurso este endpoint pertence + audience: resourceIdentifier, // Opcionalmente, valide a reivindicação 'aud' + requiredScopes: ['read:notes'], + }), + (req, res) => { + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); +``` + +### Uso legado no modo `authorization server` (Obsoleto) {#legacy-usage-in-authorization-server-mode-deprecated} + +Esta abordagem é suportada para compatibilidade retroativa. + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + server: await fetchServerConfig( + 'https://auth.logto.io/oidc', + { type: 'oidc' } + ), +}); + +// Monta o router para lidar com o Metadata legado do Authorization Server +app.use(mcpAuth.delegatedRouter()); + +// Protege um endpoint usando a política padrão +app.get( + '/mcp', + mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), + (req, res) => { + console.log('Auth info:', req.auth); + // Lide com a requisição MCP aqui + }, +); +``` + +## Construtores {#constructors} + +### Construtor {#constructor} + +```ts +new MCPAuth(config: MCPAuthConfig): MCPAuth; +``` + +Cria uma instância de MCPAuth. +Valida toda a configuração antecipadamente para falhar rapidamente em caso de erros. + +#### Parâmetros {#parameters} + +##### config {#config} + +[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) + +A configuração de autenticação. + +#### Retorna {#returns} + +`MCPAuth` + +## Propriedades {#properties} + +### config {#config} + +```ts +readonly config: MCPAuthConfig; +``` + +A configuração de autenticação. + +## Métodos {#methods} + +### bearerAuth() {#bearerauth} + +#### Assinatura de chamada {#call-signature} + +```ts +bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; +``` + +Cria um handler de autenticação Bearer (middleware Express) que verifica o token de acesso no +cabeçalho `Authorization` da requisição. + +##### Parâmetros {#parameters} + +###### verifyAccessToken {#verifyaccesstoken} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +Uma função que verifica o token de acesso. Deve aceitar o +token de acesso como uma string e retornar uma promise (ou um valor) que resolve para o +resultado da verificação. + +**Veja também** + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para a definição do tipo da função +`verifyAccessToken`. + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> + +Configuração opcional para o handler de autenticação Bearer. + +**Veja também** + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para as opções de configuração disponíveis (excluindo +`verifyAccessToken` e `issuer`). + +##### Retorna {#returns} + +`RequestHandler` + +Uma função middleware Express que verifica o token de acesso e adiciona o +resultado da verificação ao objeto da requisição (`req.auth`). + +##### Veja também {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) para detalhes da implementação e os tipos estendidos do +objeto `req.auth` (`AuthInfo`). + +#### Assinatura de chamada {#call-signature} + +```ts +bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; +``` + +Cria um handler de autenticação Bearer (middleware Express) que verifica o token de acesso no +cabeçalho `Authorization` da requisição usando um modo de verificação predefinido. + +No modo `'jwt'`, o handler criará uma função de verificação JWT usando o JWK Set +do JWKS URI do servidor de autorização. + +##### Parâmetros {#parameters} + +###### mode {#mode} + +`"jwt"` + +O modo de verificação para o token de acesso. Atualmente, apenas 'jwt' é suportado. + +**Veja também** + +[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) para os modos disponíveis. + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` + +Configuração opcional para o handler de autenticação Bearer, incluindo opções de verificação JWT e +opções remotas de JWK set. + +**Veja também** + + - VerifyJwtConfig para as opções de configuração disponíveis para verificação JWT. + - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para as opções de configuração disponíveis (excluindo +`verifyAccessToken` e `issuer`). + +##### Retorna {#returns} + +`RequestHandler` + +Uma função middleware Express que verifica o token de acesso e adiciona o +resultado da verificação ao objeto da requisição (`req.auth`). + +##### Veja também {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) para detalhes da implementação e os tipos estendidos do +objeto `req.auth` (`AuthInfo`). + +##### Lança exceção {#throws} + +se o JWKS URI não for fornecido nos metadados do servidor ao +usar o modo `'jwt'`. + +*** + +### ~~delegatedRouter()~~ {#delegatedrouter} + +```ts +delegatedRouter(): Router; +``` + +Cria um router delegado para servir o endpoint legado de Metadata do OAuth 2.0 Authorization Server +(`/.well-known/oauth-authorization-server`) com os metadados fornecidos para a instância. + +#### Retorna {#returns} + +`Router` + +Um router que serve o endpoint de Metadata do OAuth 2.0 Authorization Server com os +metadados fornecidos para a instância. + +#### Obsoleto {#deprecated} + +Use [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) em vez disso. + +#### Exemplo {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth: MCPAuth; // Suponha que está inicializado +app.use(mcpAuth.delegatedRouter()); +``` + +#### Lança exceção {#throws} + +Se chamado no modo `resource server`. + +*** + +### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} + +```ts +protectedResourceMetadataRouter(): Router; +``` + +Cria um router que serve o endpoint de Metadata de Recurso Protegido OAuth 2.0 +para todos os recursos configurados. + +Este router cria automaticamente os endpoints `.well-known` corretos para cada +identificador de recurso fornecido na sua configuração. + +#### Retorna {#returns} + +`Router` + +Um router que serve o endpoint de Metadata de Recurso Protegido OAuth 2.0. + +#### Lança exceção {#throws} + +Se chamado no modo `authorization server`. + +#### Exemplo {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +// Supondo que mcpAuth está inicializado com uma ou mais configs `protectedResources` +const mcpAuth: MCPAuth; +const app = express(); + +// Isso servirá metadata em `/.well-known/oauth-protected-resource/...` +// com base nos seus identificadores de recurso. +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md new file mode 100644 index 0000000..c85af2b --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthAuthServerError +--- + +# Classe: MCPAuthAuthServerError + +Erro lançado quando há um problema com o servidor de autorização remoto. + +## Estende {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Construtores {#constructors} + +### Construtor {#constructor} + +```ts +new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; +``` + +#### Parâmetros {#parameters} + +##### code {#code} + +[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### Retorna {#returns} + +`MCPAuthAuthServerError` + +#### Sobrescreve {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propriedades {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: AuthServerErrorCode; +``` + +O código do erro no formato snake_case. + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthAuthServerError'; +``` + +#### Sobrescreve {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +A propriedade `Error.stackTraceLimit` especifica o número de frames de pilha +coletados por um stack trace (seja gerado por `new Error().stack` ou +`Error.captureStackTrace(obj)`). + +O valor padrão é `10`, mas pode ser definido para qualquer número válido do JavaScript. Alterações +afetarão qualquer stack trace capturado _após_ a alteração do valor. + +Se definido para um valor não numérico ou negativo, os stack traces não +capturarão nenhum frame. + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Métodos {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Converte o erro para um formato JSON amigável para resposta HTTP. + +#### Parâmetros {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Se deve incluir a causa do erro na resposta JSON. +O padrão é `false`. + +#### Retorna {#returns} + +`Record`\<`string`, `unknown`\> + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Cria uma propriedade `.stack` em `targetObject`, que ao ser acessada retorna +uma string representando a localização no código em que +`Error.captureStackTrace()` foi chamado. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Semelhante a `new Error().stack` +``` + +A primeira linha do trace será prefixada com +`${myObject.name}: ${myObject.message}`. + +O argumento opcional `constructorOpt` aceita uma função. Se fornecido, todos os frames +acima de `constructorOpt`, incluindo `constructorOpt`, serão omitidos do +stack trace gerado. + +O argumento `constructorOpt` é útil para ocultar detalhes de implementação +da geração do erro para o usuário. Por exemplo: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Cria um erro sem stack trace para evitar calcular o stack trace duas vezes. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Captura o stack trace acima da função b + Error.captureStackTrace(error, b); // Nem a função c, nem b são incluídas no stack trace + throw error; +} + +a(); +``` + +#### Parâmetros {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Retorna {#returns} + +`void` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parâmetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Retorna {#returns} + +`any` + +#### Veja também {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md new file mode 100644 index 0000000..d7f4fcd --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthBearerAuthError +--- + +# Classe: MCPAuthBearerAuthError + +Erro lançado quando há um problema ao autenticar com tokens Bearer. + +## Estende {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Construtores {#constructors} + +### Construtor {#constructor} + +```ts +new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; +``` + +#### Parâmetros {#parameters} + +##### code {#code} + +[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) + +##### cause? {#cause} + +[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) + +#### Retorna {#returns} + +`MCPAuthBearerAuthError` + +#### Sobrescreve {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propriedades {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: MCPAuthBearerAuthErrorDetails; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: BearerAuthErrorCode; +``` + +O código de erro no formato snake_case. + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthBearerAuthError'; +``` + +#### Sobrescreve {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +A propriedade `Error.stackTraceLimit` especifica o número de frames de pilha +coletados por um stack trace (seja gerado por `new Error().stack` ou +`Error.captureStackTrace(obj)`). + +O valor padrão é `10`, mas pode ser definido para qualquer número válido em JavaScript. Alterações +afetarão qualquer stack trace capturado _após_ a alteração do valor. + +Se definido para um valor não numérico, ou para um número negativo, os stack traces +não capturarão nenhum frame. + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Métodos {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Converte o erro para um formato JSON amigável para resposta HTTP. + +#### Parâmetros {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Se deve incluir a causa do erro na resposta JSON. +O padrão é `false`. + +#### Retorna {#returns} + +`Record`\<`string`, `unknown`\> + +#### Sobrescreve {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Cria uma propriedade `.stack` em `targetObject`, que ao ser acessada retorna +uma string representando a localização no código em que +`Error.captureStackTrace()` foi chamado. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Semelhante a `new Error().stack` +``` + +A primeira linha do trace será prefixada com +`${myObject.name}: ${myObject.message}`. + +O argumento opcional `constructorOpt` aceita uma função. Se fornecido, todos os frames +acima de `constructorOpt`, incluindo `constructorOpt`, serão omitidos do +stack trace gerado. + +O argumento `constructorOpt` é útil para ocultar detalhes de implementação +da geração do erro para o usuário. Por exemplo: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Cria um erro sem stack trace para evitar calcular o stack trace duas vezes. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Captura o stack trace acima da função b + Error.captureStackTrace(error, b); // Nem a função c, nem b são incluídas no stack trace + throw error; +} + +a(); +``` + +#### Parâmetros {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Retorna {#returns} + +`void` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parâmetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Retorna {#returns} + +`any` + +#### Veja também {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md new file mode 100644 index 0000000..97a7fef --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md @@ -0,0 +1,252 @@ +--- +sidebar_label: MCPAuthConfigError +--- + +# Classe: MCPAuthConfigError + +Erro lançado quando há um problema de configuração com o mcp-auth. + +## Estende {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Construtores {#constructors} + +### Construtor {#constructor} + +```ts +new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; +``` + +#### Parâmetros {#parameters} + +##### code {#code} + +`string` + +O código do erro no formato snake_case. + +##### message {#message} + +`string` + +Uma descrição legível do erro. + +#### Retorna {#returns} + +`MCPAuthConfigError` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propriedades {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +O código do erro no formato snake_case. + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthConfigError'; +``` + +#### Sobrescreve {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +A propriedade `Error.stackTraceLimit` especifica o número de frames de pilha +coletados por um stack trace (seja gerado por `new Error().stack` ou +`Error.captureStackTrace(obj)`). + +O valor padrão é `10`, mas pode ser definido para qualquer número válido em JavaScript. Alterações +afetarão qualquer stack trace capturado _após_ a alteração do valor. + +Se definido para um valor não numérico, ou para um número negativo, os stack traces +não capturarão nenhum frame. + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Métodos {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Converte o erro para um formato JSON amigável para resposta HTTP. + +#### Parâmetros {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Se deve incluir a causa do erro na resposta JSON. +O padrão é `false`. + +#### Retorna {#returns} + +`Record`\<`string`, `unknown`\> + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Cria uma propriedade `.stack` em `targetObject`, que ao ser acessada retorna +uma string representando a localização no código em que +`Error.captureStackTrace()` foi chamada. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Semelhante a `new Error().stack` +``` + +A primeira linha do trace será prefixada com +`${myObject.name}: ${myObject.message}`. + +O argumento opcional `constructorOpt` aceita uma função. Se fornecido, todos os frames +acima de `constructorOpt`, incluindo `constructorOpt`, serão omitidos do +stack trace gerado. + +O argumento `constructorOpt` é útil para ocultar detalhes de implementação +da geração do erro para o usuário. Por exemplo: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Cria um erro sem stack trace para evitar calcular o stack trace duas vezes. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Captura o stack trace acima da função b + Error.captureStackTrace(error, b); // Nem a função c, nem b são incluídas no stack trace + throw error; +} + +a(); +``` + +#### Parâmetros {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Retorna {#returns} + +`void` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parâmetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Retorna {#returns} + +`any` + +#### Veja também {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md new file mode 100644 index 0000000..e868d80 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md @@ -0,0 +1,268 @@ +--- +sidebar_label: MCPAuthError +--- + +# Classe: MCPAuthError + +Classe base para todos os erros do mcp-auth. + +Ela fornece uma maneira padronizada de lidar com erros relacionados à autenticação (Authentication) e autorização (Authorization) MCP. + +## Estende {#extends} + +- `Error` + +## Estendida por {#extended-by} + +- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) +- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) +- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) +- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) + +## Construtores {#constructors} + +### Construtor {#constructor} + +```ts +new MCPAuthError(code: string, message: string): MCPAuthError; +``` + +#### Parâmetros {#parameters} + +##### code {#code} + +`string` + +O código do erro no formato snake_case. + +##### message {#message} + +`string` + +Uma descrição legível do erro. + +#### Retorna {#returns} + +`MCPAuthError` + +#### Sobrescreve {#overrides} + +```ts +Error.constructor +``` + +## Propriedades {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### Herdado de {#inherited-from} + +```ts +Error.cause +``` + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +O código do erro no formato snake_case. + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Herdado de {#inherited-from} + +```ts +Error.message +``` + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthError'; +``` + +#### Sobrescreve {#overrides} + +```ts +Error.name +``` + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Herdado de {#inherited-from} + +```ts +Error.stack +``` + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +A propriedade `Error.stackTraceLimit` especifica o número de frames de pilha +coletados por um stack trace (seja gerado por `new Error().stack` ou +`Error.captureStackTrace(obj)`). + +O valor padrão é `10`, mas pode ser definido para qualquer número válido do JavaScript. Alterações +afetarão qualquer stack trace capturado _após_ a alteração do valor. + +Se definido para um valor não numérico, ou para um número negativo, os stack traces +não capturarão nenhum frame. + +#### Herdado de {#inherited-from} + +```ts +Error.stackTraceLimit +``` + +## Métodos {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Converte o erro para um formato JSON amigável para resposta HTTP. + +#### Parâmetros {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Se deve incluir a causa do erro na resposta JSON. +O padrão é `false`. + +#### Retorna {#returns} + +`Record`\<`string`, `unknown`\> + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Cria uma propriedade `.stack` em `targetObject`, que ao ser acessada retorna +uma string representando a localização no código em que +`Error.captureStackTrace()` foi chamada. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Semelhante a `new Error().stack` +``` + +A primeira linha do trace será prefixada com +`${myObject.name}: ${myObject.message}`. + +O argumento opcional `constructorOpt` aceita uma função. Se fornecido, todos os frames +acima de `constructorOpt`, incluindo `constructorOpt`, serão omitidos do stack trace gerado. + +O argumento `constructorOpt` é útil para ocultar detalhes de implementação +da geração do erro para o usuário. Por exemplo: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Cria um erro sem stack trace para evitar calcular o stack trace duas vezes. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Captura o stack trace acima da função b + Error.captureStackTrace(error, b); // Nem a função c, nem b são incluídas no stack trace + throw error; +} + +a(); +``` + +#### Parâmetros {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Retorna {#returns} + +`void` + +#### Herdado de {#inherited-from} + +```ts +Error.captureStackTrace +``` + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parâmetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Retorna {#returns} + +`any` + +#### Veja {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Herdado de {#inherited-from} + +```ts +Error.prepareStackTrace +``` \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md new file mode 100644 index 0000000..47b2783 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md @@ -0,0 +1,248 @@ +--- +sidebar_label: MCPAuthTokenVerificationError +--- + +# Classe: MCPAuthTokenVerificationError + +Erro lançado quando há um problema ao verificar tokens. + +## Estende {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## Construtores {#constructors} + +### Construtor {#constructor} + +```ts +new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; +``` + +#### Parâmetros {#parameters} + +##### code {#code} + +[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### Retorna {#returns} + +`MCPAuthTokenVerificationError` + +#### Sobrescreve {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## Propriedades {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: MCPAuthTokenVerificationErrorCode; +``` + +O código do erro no formato snake_case. + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthTokenVerificationError'; +``` + +#### Sobrescreve {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +A propriedade `Error.stackTraceLimit` especifica o número de frames de pilha +coletados por um stack trace (seja gerado por `new Error().stack` ou +`Error.captureStackTrace(obj)`). + +O valor padrão é `10`, mas pode ser definido para qualquer número válido do JavaScript. Alterações +afetarão qualquer stack trace capturado _após_ a alteração do valor. + +Se definido para um valor não numérico, ou para um número negativo, os stack traces +não capturarão nenhum frame. + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## Métodos {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +Converte o erro para um formato JSON amigável para resposta HTTP. + +#### Parâmetros {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +Se deve incluir a causa do erro na resposta JSON. +O padrão é `false`. + +#### Retorna {#returns} + +`Record`\<`string`, `unknown`\> + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +Cria uma propriedade `.stack` em `targetObject`, que ao ser acessada retorna +uma string representando a localização no código em que +`Error.captureStackTrace()` foi chamado. + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // Semelhante a `new Error().stack` +``` + +A primeira linha do trace será prefixada com +`${myObject.name}: ${myObject.message}`. + +O argumento opcional `constructorOpt` aceita uma função. Se fornecido, todos os frames +acima de `constructorOpt`, incluindo `constructorOpt`, serão omitidos do +stack trace gerado. + +O argumento `constructorOpt` é útil para ocultar detalhes de implementação +da geração do erro para o usuário. Por exemplo: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // Cria um erro sem stack trace para evitar calcular o stack trace duas vezes. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // Captura o stack trace acima da função b + Error.captureStackTrace(error, b); // Nem a função c, nem b são incluídas no stack trace + throw error; +} + +a(); +``` + +#### Parâmetros {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### Retorna {#returns} + +`void` + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### Parâmetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Retorna {#returns} + +`any` + +#### Veja também {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Herdado de {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md new file mode 100644 index 0000000..da4553d --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md @@ -0,0 +1,43 @@ +--- +sidebar_label: createVerifyJwt +--- + +# Função: createVerifyJwt() + +```ts +function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; +``` + +Cria uma função para verificar tokens de acesso JWT (Access tokens) usando a função de recuperação de chave fornecida e opções. + +## Parâmetros {#parameters} + +### getKey {#getkey} + +`JWTVerifyGetKey` + +A função para recuperar a chave usada para verificar o JWT. + +**Veja também** + +JWTVerifyGetKey para a definição do tipo da função de recuperação de chave. + +### options? {#options} + +`JWTVerifyOptions` + +Opções opcionais de verificação do JWT. + +**Veja também** + +JWTVerifyOptions para a definição do tipo das opções. + +## Retorno {#returns} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +Uma função que verifica tokens de acesso JWT (Access tokens) e retorna um objeto AuthInfo se o token for válido. Ela exige que o JWT contenha os campos `iss`, `client_id` e `sub` em seu payload, e pode opcionalmente conter os campos `scope` ou `scopes`. A função utiliza a biblioteca `jose` internamente para realizar a verificação do JWT. + +## Veja também {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para a definição do tipo da função retornada. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md new file mode 100644 index 0000000..d11b77d --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md @@ -0,0 +1,62 @@ +--- +sidebar_label: fetchServerConfig +--- + +# Função: fetchServerConfig() + +```ts +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +``` + +Busca a configuração do servidor de acordo com o emissor (Issuer) e o tipo de servidor de autorização (Authorization). + +Esta função determina automaticamente a URL well-known com base no tipo de servidor, já que servidores OAuth e +OpenID Connect possuem convenções diferentes para seus endpoints de metadados. + +## Parâmetros {#parameters} + +### issuer {#issuer} + +`string` + +A URL do emissor (Issuer) do servidor de autorização. + +### config {#config} + +`ServerMetadataConfig` + +O objeto de configuração contendo o tipo de servidor e uma função de transpilação opcional. + +## Retorno {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +Uma promise que resolve para a configuração do servidor. + +## Veja também {#see} + + - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) para a implementação subjacente. + - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) para a especificação de Metadados do Servidor de Autorização OAuth 2.0. + - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) para a especificação de Descoberta do OpenID Connect. + +## Exemplo {#example} + +```ts +import { fetchServerConfig } from 'mcp-auth'; +// Buscando configuração do servidor OAuth +// Isso buscará os metadados de `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` +const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); + +// Buscando configuração do servidor OpenID Connect +// Isso buscará os metadados de `https://auth.logto.io/oidc/.well-known/openid-configuration` +const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); +``` + +## Lança exceção {#throws} + +se a operação de busca falhar. + +## Lança exceção {#throws} + +se os metadados do servidor forem inválidos ou não corresponderem à +especificação MCP. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md new file mode 100644 index 0000000..53f429c --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md @@ -0,0 +1,41 @@ +--- +sidebar_label: fetchServerConfigByWellKnownUrl +--- + +# Função: fetchServerConfigByWellKnownUrl() + +```ts +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +``` + +Busca a configuração do servidor a partir da well-known URL fornecida e a valida conforme a especificação MCP. + +Se os metadados do servidor não estiverem em conformidade com o esquema esperado, mas você tiver certeza de que são compatíveis, é possível definir uma função `transpileData` para transformar os metadados no formato esperado. + +## Parâmetros {#parameters} + +### wellKnownUrl {#wellknownurl} + +A well-known URL de onde buscar a configuração do servidor. Pode ser uma string ou um objeto URL. + +`string` | `URL` + +### config {#config} + +`ServerMetadataConfig` + +O objeto de configuração contendo o tipo do servidor e, opcionalmente, a função de transpile. + +## Retorna {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +Uma promise que resolve para a configuração do servidor. + +## Lança exceção {#throws} + +se a operação de busca falhar. + +## Lança exceção {#throws} + +se os metadados do servidor forem inválidos ou não corresponderem à especificação MCP. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md new file mode 100644 index 0000000..3c9d1fa --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md @@ -0,0 +1,41 @@ +--- +sidebar_label: handleBearerAuth +--- + +# Função: handleBearerAuth() + +```ts +function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; +``` + +Cria uma função middleware para lidar com autenticação Bearer em uma aplicação Express. + +Este middleware extrai o token Bearer do cabeçalho `Authorization`, verifica-o usando a função +`verifyAccessToken` fornecida e checa o emissor (Issuer), público (Audience) e escopos (Scopes) necessários. + +- Se o token for válido, adiciona as informações de autenticação à propriedade `request.auth`; +caso contrário, responde com uma mensagem de erro apropriada. +- Se a verificação do token de acesso (Access token) falhar, responde com um erro 401 Não autorizado. +- Se o token não possuir os escopos (Scopes) necessários, responde com um erro 403 Proibido. +- Se ocorrerem erros inesperados durante o processo de autenticação (Authentication), o middleware irá relançá-los. + +**Nota:** O objeto `request.auth` conterá campos estendidos em comparação com a interface padrão +AuthInfo definida no módulo `@modelcontextprotocol/sdk`. Veja a interface estendida neste arquivo para mais detalhes. + +## Parâmetros {#parameters} + +### param0 {#param0} + +[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) + +Configuração para o manipulador de autenticação Bearer. + +## Retorno {#returns} + +`RequestHandler` + +Uma função middleware para Express que lida com autenticação Bearer. + +## Veja também {#see} + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para as opções de configuração. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md new file mode 100644 index 0000000..0651175 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md @@ -0,0 +1,49 @@ +--- +sidebar_label: AuthServerConfig +--- + +# Alias de Tipo: AuthServerConfig + +```ts +type AuthServerConfig = { + metadata: CamelCaseAuthorizationServerMetadata; + type: AuthServerType; +}; +``` + +Configuração para o servidor remoto de autorização integrado com o servidor MCP. + +## Propriedades {#properties} + +### metadata {#metadata} + +```ts +metadata: CamelCaseAuthorizationServerMetadata; +``` + +Os metadados do servidor de autorização (Authorization Server), que devem estar em conformidade com a especificação MCP +(baseada nos Metadados do Servidor de Autorização OAuth 2.0). + +Esses metadados normalmente são obtidos a partir do endpoint well-known do servidor (Metadados do Servidor de Autorização OAuth 2.0 ou OpenID Connect Discovery); também podem ser fornecidos +diretamente na configuração caso o servidor não suporte tais endpoints. + +**Nota:** Os metadados devem estar no formato camelCase conforme preferido pela biblioteca mcp-auth. + +#### Veja também {#see} + + - [Metadados do Servidor de Autorização OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8414) + - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +*** + +### type {#type} + +```ts +type: AuthServerType; +``` + +O tipo do servidor de autorização (Authorization Server). + +#### Veja também {#see} + +[AuthServerType](/references/js/type-aliases/AuthServerType.md) para os valores possíveis. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md new file mode 100644 index 0000000..bce4d15 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md @@ -0,0 +1,45 @@ +--- +sidebar_label: AuthServerConfigError +--- + +# Alias de Tipo: AuthServerConfigError + +```ts +type AuthServerConfigError = { + cause?: Error; + code: AuthServerConfigErrorCode; + description: string; +}; +``` + +Representa um erro que ocorre durante a validação dos metadados do servidor de autorização (authorization server). + +## Propriedades {#properties} + +### cause? {#cause} + +```ts +optional cause: Error; +``` + +Uma causa opcional do erro, normalmente uma instância de `Error` que fornece mais contexto. + +*** + +### code {#code} + +```ts +code: AuthServerConfigErrorCode; +``` + +O código que representa o erro de validação específico. + +*** + +### description {#description} + +```ts +description: string; +``` + +Uma descrição legível do erro. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md new file mode 100644 index 0000000..d6e374d --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: AuthServerConfigErrorCode +--- + +# Alias de Tipo: AuthServerConfigErrorCode + +```ts +type AuthServerConfigErrorCode = + | "invalid_server_metadata" + | "code_response_type_not_supported" + | "authorization_code_grant_not_supported" + | "pkce_not_supported" + | "s256_code_challenge_method_not_supported"; +``` + +Os códigos para erros que podem ocorrer ao validar os metadados do servidor de autorização. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md new file mode 100644 index 0000000..102c7ce --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md @@ -0,0 +1,34 @@ +--- +sidebar_label: AuthServerConfigWarning +--- + +# Alias de Tipo: AuthServerConfigWarning + +```ts +type AuthServerConfigWarning = { + code: AuthServerConfigWarningCode; + description: string; +}; +``` + +Representa um aviso que ocorre durante a validação dos metadados do servidor de autorização (authorization server). + +## Propriedades {#properties} + +### code {#code} + +```ts +code: AuthServerConfigWarningCode; +``` + +O código que representa o aviso específico de validação. + +*** + +### description {#description} + +```ts +description: string; +``` + +Uma descrição legível por humanos do aviso. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md new file mode 100644 index 0000000..3e2035f --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerConfigWarningCode +--- + +# Alias de Tipo: AuthServerConfigWarningCode + +```ts +type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; +``` + +Os códigos para avisos que podem ocorrer ao validar os metadados do servidor de autorização. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md new file mode 100644 index 0000000..5c2a3fd --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md @@ -0,0 +1,12 @@ +--- +sidebar_label: AuthServerErrorCode +--- + +# Alias de Tipo: AuthServerErrorCode + +```ts +type AuthServerErrorCode = + | "invalid_server_metadata" + | "invalid_server_config" + | "missing_jwks_uri"; +``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md new file mode 100644 index 0000000..5719fd8 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md @@ -0,0 +1,31 @@ +--- +sidebar_label: AuthServerModeConfig +--- + +# Alias de Tipo: ~~AuthServerModeConfig~~ + +```ts +type AuthServerModeConfig = { + server: AuthServerConfig; +}; +``` + +Configuração para o modo legado de servidor MCP como servidor de autorização (authorization server). + +## Obsoleto {#deprecated} + +Use a configuração `ResourceServerModeConfig` em vez disso. + +## Propriedades {#properties} + +### ~~server~~ {#server} + +```ts +server: AuthServerConfig; +``` + +A configuração do único servidor de autorização (authorization server). + +#### Obsoleto {#deprecated} + +Use a configuração `protectedResources` em vez disso. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md new file mode 100644 index 0000000..a5cb4c5 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md @@ -0,0 +1,17 @@ +--- +sidebar_label: AuthServerSuccessCode +--- + +# Alias de Tipo: AuthServerSuccessCode + +```ts +type AuthServerSuccessCode = + | "server_metadata_valid" + | "dynamic_registration_supported" + | "pkce_supported" + | "s256_code_challenge_method_supported" + | "authorization_code_grant_supported" + | "code_response_type_supported"; +``` + +Os códigos para validação bem-sucedida dos metadados do servidor de autorização. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md new file mode 100644 index 0000000..1252cf4 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerType +--- + +# Alias de Tipo: AuthServerType + +```ts +type AuthServerType = "oauth" | "oidc"; +``` + +O tipo do servidor de autorização (authorization server). Esta informação deve ser fornecida pela configuração do servidor e indica se o servidor é um servidor de autorização OAuth 2.0 ou OpenID Connect (OIDC). \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md new file mode 100644 index 0000000..95c6719 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md @@ -0,0 +1,238 @@ +--- +sidebar_label: AuthorizationServerMetadata +--- + +# Alias de Tipo: AuthorizationServerMetadata + +```ts +type AuthorizationServerMetadata = { + authorization_endpoint: string; + code_challenge_methods_supported?: string[]; + grant_types_supported?: string[]; + introspection_endpoint?: string; + introspection_endpoint_auth_methods_supported?: string[]; + introspection_endpoint_auth_signing_alg_values_supported?: string[]; + issuer: string; + jwks_uri?: string; + op_policy_uri?: string; + op_tos_uri?: string; + registration_endpoint?: string; + response_modes_supported?: string[]; + response_types_supported: string[]; + revocation_endpoint?: string; + revocation_endpoint_auth_methods_supported?: string[]; + revocation_endpoint_auth_signing_alg_values_supported?: string[]; + scopes_supported?: string[]; + service_documentation?: string; + token_endpoint: string; + token_endpoint_auth_methods_supported?: string[]; + token_endpoint_auth_signing_alg_values_supported?: string[]; + ui_locales_supported?: string[]; + userinfo_endpoint?: string; +}; +``` + +Esquema para os metadados do servidor de autorização OAuth 2.0 conforme definido na RFC 8414. + +## Declaração do tipo {#type-declaration} + +### authorization\_endpoint {#authorization-endpoint} + +```ts +authorization_endpoint: string; +``` + +URL do endpoint de autorização do servidor de autorização [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. +Isto é OBRIGATÓRIO, a menos que nenhum tipo de concessão seja suportado que utilize o endpoint de autorização. + +#### Veja {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.1 + +### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} + +```ts +optional code_challenge_methods_supported: string[]; +``` + +Array JSON contendo uma lista de métodos de desafio de código Proof Key for Code Exchange (PKCE) +[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] suportados por este servidor de autorização. + +### grant\_types\_supported? {#grant-types-supported} + +```ts +optional grant_types_supported: string[]; +``` + +Array JSON contendo uma lista dos valores de tipo de concessão OAuth 2.0 que este servidor de autorização +suporta. Os valores do array usados são os mesmos usados com o parâmetro `grant_types` +definido pelo "OAuth 2.0 Dynamic Client Registration Protocol" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. +Se omitido, o valor padrão é `["authorization_code", "implicit"]`. + +### introspection\_endpoint? {#introspection-endpoint} + +```ts +optional introspection_endpoint: string; +``` + +URL do endpoint de introspecção OAuth 2.0 do servidor de autorização +[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. + +### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} + +```ts +optional introspection_endpoint_auth_methods_supported: string[]; +``` + +### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} + +```ts +optional introspection_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +O identificador do emissor (Issuer) do servidor de autorização, que é uma URL que utiliza o esquema `https` e +não possui componentes de consulta ou fragmento. + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +URL do documento JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] +do servidor de autorização. O documento referenciado contém a(s) chave(s) de assinatura que o cliente usa para validar +assinaturas do servidor de autorização. Esta URL DEVE usar o esquema `https`. + +### op\_policy\_uri? {#op-policy-uri} + +```ts +optional op_policy_uri: string; +``` + +### op\_tos\_uri? {#op-tos-uri} + +```ts +optional op_tos_uri: string; +``` + +### registration\_endpoint? {#registration-endpoint} + +```ts +optional registration_endpoint: string; +``` + +URL do endpoint de Registro Dinâmico de Cliente OAuth 2.0 do servidor de autorização +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. + +### response\_modes\_supported? {#response-modes-supported} + +```ts +optional response_modes_supported: string[]; +``` + +Array JSON contendo uma lista dos valores de `response_mode` do OAuth 2.0 que este +servidor de autorização suporta, conforme especificado em "OAuth 2.0 Multiple Response +Type Encoding Practices" +[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]. + +Se omitido, o padrão é `["query", "fragment"]`. O valor de response mode `"form_post"` também é +definido em "OAuth 2.0 Form Post Response Mode" +[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]. + +### response\_types\_supported {#response-types-supported} + +```ts +response_types_supported: string[]; +``` + +Array JSON contendo uma lista dos valores de `response_type` do OAuth 2.0 que este servidor de autorização +suporta. Os valores do array usados são os mesmos usados com o parâmetro `response_types` +definido pelo "OAuth 2.0 Dynamic Client Registration Protocol" +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. + +### revocation\_endpoint? {#revocation-endpoint} + +```ts +optional revocation_endpoint: string; +``` + +URL do endpoint de revogação OAuth 2.0 do servidor de autorização +[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. + +### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} + +```ts +optional revocation_endpoint_auth_methods_supported: string[]; +``` + +### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} + +```ts +optional revocation_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +Array JSON contendo uma lista dos valores de `scope` do OAuth 2.0 que este servidor de autorização +suporta. +[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] + +### service\_documentation? {#service-documentation} + +```ts +optional service_documentation: string; +``` + +### token\_endpoint {#token-endpoint} + +```ts +token_endpoint: string; +``` + +URL do endpoint de token do servidor de autorização [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. +Isto é OBRIGATÓRIO, a menos que apenas o tipo de concessão implícita seja suportado. + +#### Veja {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.2 + +### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} + +```ts +optional token_endpoint_auth_methods_supported: string[]; +``` + +### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} + +```ts +optional token_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### ui\_locales\_supported? {#ui-locales-supported} + +```ts +optional ui_locales_supported: string[]; +``` + +### userinfo\_endpoint? {#userinfo-endpoint} + +```ts +optional userinfo_endpoint: string; +``` + +URL do [userinfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) do OpenID Connect. +Este endpoint é usado para recuperar informações sobre o usuário autenticado. + +## Veja também {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md new file mode 100644 index 0000000..7aa9fe1 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md @@ -0,0 +1,117 @@ +--- +sidebar_label: BearerAuthConfig +--- + +# Alias de Tipo: BearerAuthConfig + +```ts +type BearerAuthConfig = { + audience?: string; + issuer: | string + | ValidateIssuerFunction; + requiredScopes?: string[]; + resource?: string; + showErrorDetails?: boolean; + verifyAccessToken: VerifyAccessTokenFunction; +}; +``` + +## Propriedades {#properties} + +### audience? {#audience} + +```ts +optional audience: string; +``` + +O público (Audience) esperado do token de acesso (`aud` claim). Normalmente, este é o servidor de recursos +(API) para o qual o token se destina. Se não for fornecido, a verificação do público será ignorada. + +**Nota:** Se o seu servidor de autorização não suporta Indicadores de Recurso (Resource Indicators) (RFC 8707), +você pode omitir este campo, pois o público pode não ser relevante. + +#### Veja {#see} + +https://datatracker.ietf.org/doc/html/rfc8707 + +*** + +### issuer {#issuer} + +```ts +issuer: + | string + | ValidateIssuerFunction; +``` + +Uma string representando um emissor (Issuer) válido, ou uma função para validar o emissor do token de acesso. + +Se uma string for fornecida, ela será usada como o valor esperado do emissor para comparação direta. + +Se uma função for fornecida, ela deve validar o emissor de acordo com as regras em +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md). + +#### Veja {#see} + +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) para mais detalhes sobre a função de validação. + +*** + +### requiredScopes? {#requiredscopes} + +```ts +optional requiredScopes: string[]; +``` + +Um array de escopos (Scopes) obrigatórios que o token de acesso deve possuir. Se o token não contiver +todos esses escopos, um erro será lançado. + +**Nota:** O handler verificará a reivindicação `scope` no token, que pode ser uma string separada por espaços +ou um array de strings, dependendo da implementação do servidor de autorização. Se a reivindicação `scope` não estiver presente, o handler verificará a reivindicação `scopes` +se disponível. + +*** + +### resource? {#resource} + +```ts +optional resource: string; +``` + +O identificador do recurso protegido. Quando fornecido, o handler usará os +servidores de autorização configurados para este recurso para validar o token recebido. +É obrigatório ao usar o handler com uma configuração `protectedResources`. + +*** + +### showErrorDetails? {#showerrordetails} + +```ts +optional showErrorDetails: boolean; +``` + +Indica se deve mostrar informações detalhadas de erro na resposta. Isso é útil para depuração +durante o desenvolvimento, mas deve ser desabilitado em produção para evitar vazamento de informações sensíveis. + +#### Padrão {#default} + +```ts +false +``` + +*** + +### verifyAccessToken {#verifyaccesstoken} + +```ts +verifyAccessToken: VerifyAccessTokenFunction; +``` + +Tipo de função para verificar um token de acesso (Access token). + +Esta função deve lançar um [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) se o token for inválido, +ou retornar um objeto AuthInfo se o token for válido. + +#### Veja {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para mais detalhes. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md new file mode 100644 index 0000000..45363f7 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: BearerAuthErrorCode +--- + +# Alias de Tipo: BearerAuthErrorCode + +```ts +type BearerAuthErrorCode = + | "missing_auth_header" + | "invalid_auth_header_format" + | "missing_bearer_token" + | "invalid_issuer" + | "invalid_audience" + | "missing_required_scopes" + | "invalid_token"; +``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md new file mode 100644 index 0000000..7b7d02e --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md @@ -0,0 +1,179 @@ +--- +sidebar_label: CamelCaseAuthorizationServerMetadata +--- + +# Alias de Tipo: CamelCaseAuthorizationServerMetadata + +```ts +type CamelCaseAuthorizationServerMetadata = { + authorizationEndpoint: string; + codeChallengeMethodsSupported?: string[]; + grantTypesSupported?: string[]; + introspectionEndpoint?: string; + introspectionEndpointAuthMethodsSupported?: string[]; + introspectionEndpointAuthSigningAlgValuesSupported?: string[]; + issuer: string; + jwksUri?: string; + opPolicyUri?: string; + opTosUri?: string; + registrationEndpoint?: string; + responseModesSupported?: string[]; + responseTypesSupported: string[]; + revocationEndpoint?: string; + revocationEndpointAuthMethodsSupported?: string[]; + revocationEndpointAuthSigningAlgValuesSupported?: string[]; + scopesSupported?: string[]; + serviceDocumentation?: string; + tokenEndpoint: string; + tokenEndpointAuthMethodsSupported?: string[]; + tokenEndpointAuthSigningAlgValuesSupported?: string[]; + uiLocalesSupported?: string[]; + userinfoEndpoint?: string; +}; +``` + +A versão em camelCase do tipo de Metadados do Servidor de Autorização OAuth 2.0 (OAuth 2.0 Authorization Server Metadata type). + +## Declaração do tipo {#type-declaration} + +### authorizationEndpoint {#authorizationendpoint} + +```ts +authorizationEndpoint: string; +``` + +### codeChallengeMethodsSupported? {#codechallengemethodssupported} + +```ts +optional codeChallengeMethodsSupported: string[]; +``` + +### grantTypesSupported? {#granttypessupported} + +```ts +optional grantTypesSupported: string[]; +``` + +### introspectionEndpoint? {#introspectionendpoint} + +```ts +optional introspectionEndpoint: string; +``` + +### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} + +```ts +optional introspectionEndpointAuthMethodsSupported: string[]; +``` + +### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} + +```ts +optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### opPolicyUri? {#oppolicyuri} + +```ts +optional opPolicyUri: string; +``` + +### opTosUri? {#optosuri} + +```ts +optional opTosUri: string; +``` + +### registrationEndpoint? {#registrationendpoint} + +```ts +optional registrationEndpoint: string; +``` + +### responseModesSupported? {#responsemodessupported} + +```ts +optional responseModesSupported: string[]; +``` + +### responseTypesSupported {#responsetypessupported} + +```ts +responseTypesSupported: string[]; +``` + +### revocationEndpoint? {#revocationendpoint} + +```ts +optional revocationEndpoint: string; +``` + +### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} + +```ts +optional revocationEndpointAuthMethodsSupported: string[]; +``` + +### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} + +```ts +optional revocationEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### serviceDocumentation? {#servicedocumentation} + +```ts +optional serviceDocumentation: string; +``` + +### tokenEndpoint {#tokenendpoint} + +```ts +tokenEndpoint: string; +``` + +### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} + +```ts +optional tokenEndpointAuthMethodsSupported: string[]; +``` + +### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} + +```ts +optional tokenEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### uiLocalesSupported? {#uilocalessupported} + +```ts +optional uiLocalesSupported: string[]; +``` + +### userinfoEndpoint? {#userinfoendpoint} + +```ts +optional userinfoEndpoint: string; +``` + +## Veja também {#see} + +[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) para o tipo original e informações dos campos. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md new file mode 100644 index 0000000..1de9b37 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md @@ -0,0 +1,123 @@ +--- +sidebar_label: CamelCaseProtectedResourceMetadata +--- + +# Alias de Tipo: CamelCaseProtectedResourceMetadata + +```ts +type CamelCaseProtectedResourceMetadata = { + authorizationDetailsTypesSupported?: string[]; + authorizationServers?: string[]; + bearerMethodsSupported?: string[]; + dpopBoundAccessTokensRequired?: boolean; + dpopSigningAlgValuesSupported?: string[]; + jwksUri?: string; + resource: string; + resourceDocumentation?: string; + resourceName?: string; + resourcePolicyUri?: string; + resourceSigningAlgValuesSupported?: string[]; + resourceTosUri?: string; + scopesSupported?: string[]; + signedMetadata?: string; + tlsClientCertificateBoundAccessTokens?: boolean; +}; +``` + +A versão camelCase do tipo de Metadados de Recurso Protegido do OAuth 2.0 (OAuth 2.0 Protected Resource Metadata). + +## Declaração do tipo {#type-declaration} + +### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} + +```ts +optional authorizationDetailsTypesSupported: string[]; +``` + +### authorizationServers? {#authorizationservers} + +```ts +optional authorizationServers: string[]; +``` + +### bearerMethodsSupported? {#bearermethodssupported} + +```ts +optional bearerMethodsSupported: string[]; +``` + +### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} + +```ts +optional dpopBoundAccessTokensRequired: boolean; +``` + +### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} + +```ts +optional dpopSigningAlgValuesSupported: string[]; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### resource {#resource} + +```ts +resource: string; +``` + +### resourceDocumentation? {#resourcedocumentation} + +```ts +optional resourceDocumentation: string; +``` + +### resourceName? {#resourcename} + +```ts +optional resourceName: string; +``` + +### resourcePolicyUri? {#resourcepolicyuri} + +```ts +optional resourcePolicyUri: string; +``` + +### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} + +```ts +optional resourceSigningAlgValuesSupported: string[]; +``` + +### resourceTosUri? {#resourcetosuri} + +```ts +optional resourceTosUri: string; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### signedMetadata? {#signedmetadata} + +```ts +optional signedMetadata: string; +``` + +### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} + +```ts +optional tlsClientCertificateBoundAccessTokens: boolean; +``` + +## Veja também {#see} + +[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) para o tipo original e informações dos campos. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md new file mode 100644 index 0000000..b2ebc3e --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md @@ -0,0 +1,55 @@ +--- +sidebar_label: MCPAuthBearerAuthErrorDetails +--- + +# Alias de Tipo: MCPAuthBearerAuthErrorDetails + +```ts +type MCPAuthBearerAuthErrorDetails = { + actual?: unknown; + cause?: unknown; + expected?: unknown; + missingScopes?: string[]; + uri?: URL; +}; +``` + +## Propriedades {#properties} + +### actual? {#actual} + +```ts +optional actual: unknown; +``` + +*** + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +*** + +### expected? {#expected} + +```ts +optional expected: unknown; +``` + +*** + +### missingScopes? {#missingscopes} + +```ts +optional missingScopes: string[]; +``` + +*** + +### uri? {#uri} + +```ts +optional uri: URL; +``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md new file mode 100644 index 0000000..6ff49a8 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md @@ -0,0 +1,13 @@ +--- +sidebar_label: MCPAuthConfig +--- + +# Alias de Tipo: MCPAuthConfig + +```ts +type MCPAuthConfig = + | AuthServerModeConfig + | ResourceServerModeConfig; +``` + +Configuração para a classe [MCPAuth](/references/js/classes/MCPAuth.md), suportando tanto um único `authorization server` legado quanto a configuração de `resource server`. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md new file mode 100644 index 0000000..2df9187 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md @@ -0,0 +1,9 @@ +--- +sidebar_label: MCPAuthTokenVerificationErrorCode +--- + +# Alias de Tipo: MCPAuthTokenVerificationErrorCode (Type Alias: MCPAuthTokenVerificationErrorCode) + +```ts +type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; +``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md new file mode 100644 index 0000000..0168f0b --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md @@ -0,0 +1,156 @@ +--- +sidebar_label: ProtectedResourceMetadata +--- + +# Alias de Tipo: ProtectedResourceMetadata + +```ts +type ProtectedResourceMetadata = { + authorization_details_types_supported?: string[]; + authorization_servers?: string[]; + bearer_methods_supported?: string[]; + dpop_bound_access_tokens_required?: boolean; + dpop_signing_alg_values_supported?: string[]; + jwks_uri?: string; + resource: string; + resource_documentation?: string; + resource_name?: string; + resource_policy_uri?: string; + resource_signing_alg_values_supported?: string[]; + resource_tos_uri?: string; + scopes_supported?: string[]; + signed_metadata?: string; + tls_client_certificate_bound_access_tokens?: boolean; +}; +``` + +Esquema para Metadados de Recurso Protegido do OAuth 2.0. + +## Declaração do tipo {#type-declaration} + +### authorization\_details\_types\_supported? {#authorization-details-types-supported} + +```ts +optional authorization_details_types_supported: string[]; +``` + +Valores de tipo de detalhes de autorização suportados ao usar o parâmetro de solicitação authorization_details. + +### authorization\_servers? {#authorization-servers} + +```ts +optional authorization_servers: string[]; +``` + +Lista de identificadores de emissor do servidor de autorização OAuth que podem ser usados com este recurso protegido. + +### bearer\_methods\_supported? {#bearer-methods-supported} + +```ts +optional bearer_methods_supported: string[]; +``` + +Métodos suportados para envio de tokens bearer do OAuth 2.0. Valores: ["header", "body", "query"]. + +### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} + +```ts +optional dpop_bound_access_tokens_required: boolean; +``` + +Se o recurso protegido sempre exige tokens de acesso vinculados ao DPoP. + +### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} + +```ts +optional dpop_signing_alg_values_supported: string[]; +``` + +Algoritmos JWS suportados para validação de provas JWT DPoP. + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +URL do documento JSON Web Key (JWK) Set do recurso protegido. Este documento contém as chaves públicas +que podem ser usadas para verificar assinaturas digitais de respostas ou dados retornados por este recurso protegido. +Isso difere do jwks_uri do servidor de autorização, que é usado para validação de tokens. Quando o recurso protegido +assina suas respostas, os clientes podem buscar essas chaves públicas para verificar a autenticidade e integridade +dos dados recebidos. + +### resource {#resource} + +```ts +resource: string; +``` + +O identificador de recurso do recurso protegido. + +### resource\_documentation? {#resource-documentation} + +```ts +optional resource_documentation: string; +``` + +URL contendo a documentação para desenvolvedores sobre o uso do recurso protegido. + +### resource\_name? {#resource-name} + +```ts +optional resource_name: string; +``` + +Nome legível por humanos do recurso protegido para exibição aos usuários finais. + +### resource\_policy\_uri? {#resource-policy-uri} + +```ts +optional resource_policy_uri: string; +``` + +URL contendo informações sobre os requisitos de uso de dados do recurso protegido. + +### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} + +```ts +optional resource_signing_alg_values_supported: string[]; +``` + +Algoritmos de assinatura JWS suportados pelo recurso protegido para assinar respostas do recurso. + +### resource\_tos\_uri? {#resource-tos-uri} + +```ts +optional resource_tos_uri: string; +``` + +URL contendo os termos de serviço do recurso protegido. + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +Lista de valores de escopo usados em solicitações de autorização para acessar este recurso protegido. + +### signed\_metadata? {#signed-metadata} + +```ts +optional signed_metadata: string; +``` + +Um JWT assinado contendo parâmetros de metadados como reivindicações. O JWT deve ser assinado usando JWS e incluir +uma reivindicação 'iss'. Este campo fornece uma maneira de verificar criptograficamente a autenticidade dos próprios metadados. +A assinatura pode ser verificada usando as chaves públicas disponíveis no endpoint `jwks_uri`. +Quando presente, os valores neste metadado assinado têm precedência sobre os valores JSON simples correspondentes neste documento de metadados. Isso ajuda a evitar adulteração dos metadados do recurso. + +### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} + +```ts +optional tls_client_certificate_bound_access_tokens: boolean; +``` + +Se o recurso protegido suporta tokens de acesso vinculados a certificado de cliente mutual-TLS. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md new file mode 100644 index 0000000..3299106 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md @@ -0,0 +1,23 @@ +--- +sidebar_label: ResourceServerModeConfig +--- + +# Alias de Tipo: ResourceServerModeConfig + +```ts +type ResourceServerModeConfig = { + protectedResources: ResourceServerConfig | ResourceServerConfig[]; +}; +``` + +Configuração para o servidor MCP no modo de servidor de recursos. + +## Propriedades {#properties} + +### protectedResources {#protectedresources} + +```ts +protectedResources: ResourceServerConfig | ResourceServerConfig[]; +``` + +Uma única configuração de servidor de recursos ou um array delas. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md new file mode 100644 index 0000000..2cc6468 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md @@ -0,0 +1,30 @@ +--- +sidebar_label: ValidateIssuerFunction +--- + +# Alias de Tipo: ValidateIssuerFunction() + +```ts +type ValidateIssuerFunction = (tokenIssuer: string) => void; +``` + +Tipo de função para validar o emissor (Issuer) do token de acesso (Access token). + +Esta função deve lançar um [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) com o código 'invalid_issuer' se o emissor não for válido. O emissor deve ser validado em relação a: + +1. Os servidores de autorização configurados nos metadados do servidor de autenticação do MCP-Auth +2. Os servidores de autorização listados nos metadados do recurso protegido + +## Parâmetros {#parameters} + +### tokenIssuer {#tokenissuer} + +`string` + +## Retorna {#returns} + +`void` + +## Lança {#throws} + +Quando o emissor não é reconhecido ou é inválido. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md new file mode 100644 index 0000000..d1ab25d --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md @@ -0,0 +1,39 @@ +--- +sidebar_label: VerifyAccessTokenFunction +--- + +# Alias de Tipo: VerifyAccessTokenFunction() + +```ts +type VerifyAccessTokenFunction = (token: string) => MaybePromise; +``` + +Tipo de função para verificar um token de acesso (Access token). + +Esta função deve lançar um [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) se o token for inválido, +ou retornar um objeto AuthInfo se o token for válido. + +Por exemplo, se você tiver uma função de verificação de JWT, ela deve pelo menos verificar a +assinatura do token, validar sua expiração e extrair as reivindicações (Claims) necessárias para retornar um objeto `AuthInfo`. + +**Nota:** Não há necessidade de verificar os seguintes campos no token, pois eles serão verificados +pelo handler: + +- `iss` (emissor / Issuer) +- `aud` (público / Audience) +- `scope` (escopos / Scopes) + +## Parâmetros {#parameters} + +### token {#token} + +`string` + +A string do token de acesso (Access token) a ser verificada. + +## Retorno {#returns} + +`MaybePromise`\<`AuthInfo`\> + +Uma promessa que resolve para um objeto AuthInfo ou um valor síncrono se o +token for válido. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md new file mode 100644 index 0000000..f20ba05 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: VerifyAccessTokenMode +--- + +# Alias de Tipo: VerifyAccessTokenMode + +```ts +type VerifyAccessTokenMode = "jwt"; +``` + +Os modos de verificação integrados suportados por `bearerAuth`. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md new file mode 100644 index 0000000..940ff45 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: authServerErrorDescription +--- + +# Variável: authServerErrorDescription + +```ts +const authServerErrorDescription: Readonly>; +``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md new file mode 100644 index 0000000..6f1c6c7 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: authorizationServerMetadataSchema +--- + +# Variável: authorizationServerMetadataSchema + +```ts +const authorizationServerMetadataSchema: ZodObject; +``` + +Schema Zod para Metadados do Servidor de Autorização OAuth 2.0 conforme definido na RFC 8414. + +## Veja também {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md new file mode 100644 index 0000000..0f6a202 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: bearerAuthErrorDescription +--- + +# Variável: bearerAuthErrorDescription + +```ts +const bearerAuthErrorDescription: Readonly>; +``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md new file mode 100644 index 0000000..f998119 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseAuthorizationServerMetadataSchema +--- + +# Variável: camelCaseAuthorizationServerMetadataSchema + +```ts +const camelCaseAuthorizationServerMetadataSchema: ZodObject; +``` + +A versão em camelCase do esquema Zod de Metadados do Servidor de Autorização (Authorization Server Metadata) do OAuth 2.0. + +## Veja também {#see} + +[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) para o esquema original e informações dos campos. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md new file mode 100644 index 0000000..a6e0617 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseProtectedResourceMetadataSchema +--- + +# Variável: camelCaseProtectedResourceMetadataSchema + +```ts +const camelCaseProtectedResourceMetadataSchema: ZodObject; +``` + +A versão em camelCase do esquema Zod de Metadados de Recurso Protegido do OAuth 2.0. + +## Veja também {#see} + +[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) para o esquema original e informações dos campos. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md new file mode 100644 index 0000000..d0e76b1 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md @@ -0,0 +1,9 @@ +--- +sidebar_label: defaultValues +--- + +# Variável: defaultValues + +```ts +const defaultValues: Readonly>; +``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md new file mode 100644 index 0000000..0b3fee6 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md @@ -0,0 +1,11 @@ +--- +sidebar_label: protectedResourceMetadataSchema +--- + +# Variável: protectedResourceMetadataSchema + +```ts +const protectedResourceMetadataSchema: ZodObject; +``` + +Schema Zod para Metadados de Recurso Protegido do OAuth 2.0 (OAuth 2.0 Protected Resource Metadata). \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md new file mode 100644 index 0000000..13265ff --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md @@ -0,0 +1,12 @@ +--- +sidebar_label: serverMetadataPaths +--- + +# Variável: serverMetadataPaths + +```ts +const serverMetadataPaths: Readonly<{ + oauth: "/.well-known/oauth-authorization-server"; + oidc: "/.well-known/openid-configuration"; +}>; +``` \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md new file mode 100644 index 0000000..755437b --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: tokenVerificationErrorDescription +--- + +# Variável: tokenVerificationErrorDescription + +```ts +const tokenVerificationErrorDescription: Readonly>; +``` \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md new file mode 100644 index 0000000..29e1bcb --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md @@ -0,0 +1,9 @@ +--- +sidebar_label: validateServerConfig +--- + +# Variável: validateServerConfig + +```ts +const validateServerConfig: ValidateServerConfig; +``` \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx b/i18n/pt-BR/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx new file mode 100644 index 0000000..00f677a --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx @@ -0,0 +1,73 @@ +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + + + + +```python +mcp = FastMCP("MyMCPServer") +resource_identifier = "https://api.example.com" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_identifier, + authorization_servers=[fetch_server_config('', AuthServerType.OIDC)], + scopes_supported=["read", "write"], + ) + ) +) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + Mount('/', app=mcp.sse_app(), middleware=[Middleware( + mcp_auth.bearer_auth_middleware("jwt", + resource=resource_identifier, + audience=resource_identifier, + required_scopes=["read", "write"] + ) + )]) + ] +) + +@mcp.tool() +def whoami(): + return mcp_auth.auth_info.claims +``` + + + + +```ts +const server = new McpServer(/* ... */); +const resourceIdentifier = 'https://api.example.com'; + +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceIdentifier, + authorizationServers: [await fetchServerConfig('', { type: 'oidc' })], + scopesSupported: ['read', 'write'], + } + } +}); + +const app = express(); + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +app.use(mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, + requiredScopes: ['read', 'write'] +})); + +server.tool('whoami', ({ authInfo }) => { + return authInfo.claims; +}); +``` + + + diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx b/i18n/pt-BR/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx new file mode 100644 index 0000000..94b9e94 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx @@ -0,0 +1,1396 @@ +--- +sidebar_position: 2 +sidebar_label: 'Tutorial: Construa um gerenciador de tarefas' +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + +# Tutorial: Construa um gerenciador de tarefas + +Neste tutorial, vamos construir um servidor MCP de gerenciador de tarefas com autenticação e autorização de usuário. Seguindo a especificação MCP mais recente, nosso servidor MCP atuará como um **Servidor de Recursos (Resource Server)** OAuth 2.0 que valida tokens de acesso e aplica permissões baseadas em escopo. + +Após concluir este tutorial, você terá: + +- ✅ Uma compreensão básica de como configurar controle de acesso baseado em papel (RBAC) em seu servidor MCP. +- ✅ Um servidor MCP que atua como um Servidor de Recursos, consumindo tokens de acesso emitidos por um Servidor de Autorização. +- ✅ Uma implementação funcional de aplicação de permissões baseadas em escopo para operações de tarefas. + +## Visão geral \{#overview} + +O tutorial envolverá os seguintes componentes: + +- **Cliente MCP (MCP Inspector)**: Uma ferramenta visual de testes para servidores MCP que atua como um cliente OAuth 2.0/OIDC. Ele inicia o fluxo de autorização com o servidor de autorização e obtém tokens de acesso para autenticar requisições ao servidor MCP. +- **Servidor de Autorização**: Um provedor OAuth 2.1 ou OpenID Connect que gerencia identidades de usuários, autentica usuários e emite tokens de acesso com escopos apropriados para clientes autorizados. +- **Servidor MCP (Servidor de Recursos)**: De acordo com a especificação MCP mais recente, o servidor MCP atua como um Servidor de Recursos no framework OAuth 2.0. Ele valida tokens de acesso emitidos pelo servidor de autorização e aplica permissões baseadas em escopo para operações de tarefas. + +Esta arquitetura segue o fluxo padrão do OAuth 2.0 onde: +- O **MCP Inspector** solicita recursos protegidos em nome do usuário +- O **Servidor de Autorização** autentica o usuário e emite tokens de acesso +- O **Servidor MCP** valida tokens e serve recursos protegidos com base nas permissões concedidas + +Aqui está um diagrama de alto nível da interação entre esses componentes: + +```mermaid +sequenceDiagram + autonumber + participant Client as MCP Inspector
(Cliente OAuth) + participant RS as Servidor MCP
(Servidor de Recursos) + participant AS as Servidor de Autorização + + Client->>RS: Requisição MCP (sem token) + RS-->>Client: 401 Não autorizado (WWW-Authenticate) + Note over Client: Extrair URL resource_metadata
do cabeçalho WWW-Authenticate + + Client->>RS: GET /.well-known/oauth-protected-resource (resource_metadata) + RS-->>Client: Metadados do recurso protegido
(inclui URL do servidor de autorização) + + Client->>AS: GET /.well-known/oauth-authorization-server + AS-->>Client: Metadados do servidor de autorização + Client->>AS: Autorização OAuth (login & consentimento) + AS-->>Client: Token de acesso + + Client->>RS: Requisição MCP (Authorization: Bearer ) + RS->>RS: Validar se o token de acesso é válido e autorizado + RS-->>Client: Resposta MCP +``` + +## Entenda seu servidor de autorização \{#understand-your-authorization-server} + +### Tokens de acesso com escopos \{#access-tokens-with-scopes} + +Para implementar [controle de acesso baseado em papel (RBAC)](https://auth.wiki/rbac) em seu servidor MCP, seu servidor de autorização precisa suportar a emissão de tokens de acesso com escopos. Escopos representam as permissões que um usuário recebeu. + + + + +[Logto](https://logto.io) oferece suporte a RBAC por meio de seus recursos de API (conforme [RFC 8707: Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707)) e funcionalidades de papéis. Veja como configurar: + +1. Faça login no [Logto Console](https://cloud.logto.io) (ou em seu Logto Console auto-hospedado) + +2. Crie recurso de API e escopos: + + - Vá para "Recursos de API" + - Crie um novo recurso de API chamado "Todo Manager" + - Adicione os seguintes escopos: + - `create:todos`: "Criar novos itens de tarefa" + - `read:todos`: "Ler todos os itens de tarefa" + - `delete:todos`: "Excluir qualquer item de tarefa" + +3. Crie papéis (recomendado para facilitar o gerenciamento): + + - Vá para "Papéis" + - Crie um papel "Admin" e atribua todos os escopos (`create:todos`, `read:todos`, `delete:todos`) + - Crie um papel "User" e atribua apenas o escopo `create:todos` + +4. Atribua permissões: + - Vá para "Usuários" + - Selecione um usuário + - Você pode: + - Atribuir papéis na aba "Papéis" (recomendado) + - Ou atribuir escopos diretamente na aba "Permissões" + +Os escopos serão incluídos na reivindicação `scope` do token de acesso JWT como uma string separada por espaços. + + + + +Provedores OAuth 2.0 / OIDC normalmente suportam controle de acesso baseado em escopo. Ao implementar RBAC: + +1. Defina os escopos necessários em seu servidor de autorização +2. Configure seu cliente para solicitar esses escopos durante o fluxo de autorização +3. Certifique-se de que seu servidor de autorização inclua os escopos concedidos no token de acesso +4. Os escopos geralmente são incluídos na reivindicação `scope` do token de acesso JWT + +Consulte a documentação do seu provedor para detalhes específicos sobre: + +- Como definir e gerenciar escopos +- Como os escopos são incluídos no token de acesso +- Quaisquer recursos adicionais de RBAC, como gerenciamento de papéis + + + + +### Validando tokens e verificando permissões \{#validating-tokens-and-checking-permissions} + +De acordo com a especificação MCP mais recente, o servidor MCP atua como um **Servidor de Recursos (Resource Server)** no framework OAuth 2.0. Como Servidor de Recursos, o servidor MCP tem as seguintes responsabilidades: + +1. **Validação de Token**: Verificar a autenticidade e integridade dos tokens de acesso recebidos dos clientes MCP +2. **Aplicação de Escopo**: Extrair e validar os escopos do token de acesso para determinar quais operações o cliente está autorizado a executar +3. **Proteção de Recursos**: Servir apenas recursos protegidos (executar ferramentas) quando o cliente apresentar tokens válidos com permissões suficientes + +Quando seu servidor MCP recebe uma requisição, ele executa o seguinte processo de validação: + +1. Extrai o token de acesso do cabeçalho `Authorization` (formato Bearer token) +2. Valida a assinatura e expiração do token de acesso +3. Extrai os escopos e informações do usuário do token validado +4. Verifica se o token possui os escopos necessários para a operação solicitada + +Por exemplo, se um usuário quiser criar um novo item de tarefa, seu token de acesso deve incluir o escopo `create:todos`. Veja como funciona o fluxo de validação do Servidor de Recursos: + +```mermaid +sequenceDiagram + participant Client as Cliente MCP + participant Server as Servidor MCP
(Servidor de Recursos) + participant Auth as Servidor de Autorização + + Client->>Server: Requisição com token de acesso
(Authorization: Bearer ) + + alt Validação JWT (Preferencial) + Server->>Auth: Buscar JWKS (se não estiver em cache) + Auth-->>Server: Retornar JWKS + Server->>Server: Validar assinatura e reivindicações do JWT localmente + else Introspecção de Token (Alternativa) + Server->>Auth: POST /introspect
(token=access_token) + Auth-->>Server: Retornar informações do token
(active, scope, user_id, etc.) + end + + Server->>Server: Extrair escopos e contexto do usuário
do token validado + + alt Possui escopos necessários + Server->>Server: Executar operação solicitada + Server->>Client: Retornar resultado da operação + else Faltam escopos necessários + Server->>Client: Retornar 403 Proibido
(erro insufficient_scope) + end +``` + +### Registro Dinâmico de Cliente \{#dynamic-client-registration} + +O Registro Dinâmico de Cliente não é necessário para este tutorial, mas pode ser útil se você quiser automatizar o processo de registro do cliente MCP com seu servidor de autorização. Veja [O Registro Dinâmico de Cliente é necessário?](/provider-list#is-dcr-required) para mais detalhes. + +## Entenda o RBAC no gerenciador de tarefas \{#understand-rbac-in-todo-manager} + +Para fins de demonstração, implementaremos um sistema simples de controle de acesso baseado em papel (RBAC) em nosso servidor MCP de gerenciador de tarefas. Isso mostrará os princípios básicos do RBAC mantendo a implementação direta. + +:::note +Embora este tutorial demonstre o gerenciamento de escopos baseado em RBAC, é importante observar que nem todos os provedores de autenticação implementam o gerenciamento de escopos por meio de papéis. Alguns provedores podem ter suas próprias implementações e mecanismos exclusivos para gerenciar controle de acesso e permissões. +::: + +### Ferramentas e escopos \{#tools-and-scopes} + +Nosso servidor MCP de gerenciador de tarefas fornece três ferramentas principais: + +- `create-todo`: Criar um novo item de tarefa +- `get-todos`: Listar todas as tarefas +- `delete-todo`: Excluir uma tarefa pelo ID + +Para controlar o acesso a essas ferramentas, definimos os seguintes escopos: + +- `create:todos`: Permite criar novos itens de tarefa +- `delete:todos`: Permite excluir itens de tarefa existentes +- `read:todos`: Permite consultar e recuperar a lista de todos os itens de tarefa + +### Papéis e permissões \{#roles-and-permissions} + +Definiremos dois papéis com diferentes níveis de acesso: + +| Papel | create:todos | read:todos | delete:todos | +| ----- | ------------ | ---------- | ------------ | +| Admin | ✅ | ✅ | ✅ | +| User | ✅ | | | + +- **User**: Um usuário comum que pode criar tarefas e visualizar ou excluir apenas suas próprias tarefas +- **Admin**: Um administrador que pode criar, visualizar e excluir todas as tarefas, independentemente da propriedade + +### Propriedade do recurso \{#resource-ownership} + +Embora a tabela de permissões acima mostre os escopos explícitos atribuídos a cada papel, há um princípio importante de propriedade de recurso a considerar: + +- **Usuários** não possuem os escopos `read:todos` ou `delete:todos`, mas ainda podem: + - Ler seus próprios itens de tarefa + - Excluir seus próprios itens de tarefa +- **Admins** possuem permissões totais (`read:todos` e `delete:todos`), permitindo que: + - Visualizem todas as tarefas do sistema + - Excluam qualquer tarefa, independentemente da propriedade + +Isso demonstra um padrão comum em sistemas RBAC onde a propriedade do recurso concede permissões implícitas aos usuários para seus próprios recursos, enquanto papéis administrativos recebem permissões explícitas para todos os recursos. + +:::tip Saiba mais +Para se aprofundar nos conceitos e melhores práticas de RBAC, confira [Dominando RBAC: Um Exemplo Abrangente do Mundo Real](https://blog.logto.io/mastering-rbac). +::: + +## Configure a autorização em seu provedor \{#configure-authorization-in-your-provider} + +Para implementar o sistema de controle de acesso que descrevemos anteriormente, você precisará configurar seu servidor de autorização para suportar os escopos necessários. Veja como fazer isso com diferentes provedores: + + + + +[Logto](https://logto.io) oferece suporte a RBAC por meio de recursos de API e funcionalidades de papéis. Veja como configurar: + +1. Faça login no [Logto Console](https://cloud.logto.io) (ou em seu Logto Console auto-hospedado) + +2. Crie recurso de API e escopos: + + - Vá para "Recursos de API" + - Crie um novo recurso de API chamado "Todo Manager" usando `http://localhost:3001` como indicador de recurso. + - **Importante**: O indicador de recurso deve corresponder à URL do seu servidor MCP. Para este tutorial, usamos `http://localhost:3001` já que nosso servidor MCP roda na porta 3001. Em produção, use a URL real do seu servidor MCP (por exemplo, `https://seu-servidor-mcp.exemplo.com`). + - Crie os seguintes escopos: + - `create:todos`: "Criar novos itens de tarefa" + - `read:todos`: "Ler todos os itens de tarefa" + - `delete:todos`: "Excluir qualquer item de tarefa" + +3. Crie papéis (recomendado para facilitar o gerenciamento): + + - Vá para "Papéis" + - Crie um papel "Admin" e atribua todos os escopos (`create:todos`, `read:todos`, `delete:todos`) + - Crie um papel "User" e atribua apenas o escopo `create:todos` + - Na página de detalhes do papel "User", vá para a aba "Geral" e defina o papel "User" como o "Papel padrão". + +4. Gerencie papéis e permissões dos usuários: + - Para novos usuários: + - Eles receberão automaticamente o papel "User" já que o definimos como papel padrão + - Para usuários existentes: + - Vá para "Gerenciamento de usuários" + - Selecione um usuário + - Atribua papéis para o usuário na aba "Papéis" + +:::tip Gerenciamento de Papéis Programático +Você também pode usar a [Management API](https://docs.logto.io/integrate-logto/interact-with-management-api) do Logto para gerenciar papéis de usuários programaticamente. Isso é especialmente útil para gerenciamento automatizado de usuários ou ao construir painéis administrativos. +::: + +Ao solicitar um token de acesso, o Logto incluirá os escopos na reivindicação `scope` do token com base nas permissões do papel do usuário. + + + + +Para provedores OAuth 2.0 ou OpenID Connect, você precisará configurar os escopos que representam diferentes permissões. Os passos exatos dependerão do seu provedor, mas geralmente: + +1. Defina escopos: + + - Configure seu servidor de autorização para suportar: + - `create:todos` + - `read:todos` + - `delete:todos` + +2. Configure o cliente: + + - Registre ou atualize seu cliente para solicitar esses escopos + - Certifique-se de que os escopos estejam incluídos no token de acesso + +3. Atribua permissões: + - Use a interface do seu provedor para conceder escopos apropriados aos usuários + - Alguns provedores podem suportar gerenciamento baseado em papéis, enquanto outros podem usar atribuições diretas de escopos + - Consulte a documentação do seu provedor para a abordagem recomendada + +:::tip +A maioria dos provedores incluirá os escopos concedidos na reivindicação `scope` do token de acesso. O formato geralmente é uma string de escopos separados por espaço. +::: + + + + +Após configurar seu servidor de autorização, os usuários receberão tokens de acesso contendo seus escopos concedidos. O servidor MCP usará esses escopos para determinar: + +- Se um usuário pode criar novas tarefas (`create:todos`) +- Se um usuário pode visualizar todas as tarefas (`read:todos`) ou apenas as suas próprias +- Se um usuário pode excluir qualquer tarefa (`delete:todos`) ou apenas as suas próprias + +## Configure o servidor MCP \{#set-up-the-mcp-server} + +Usaremos os [SDKs oficiais MCP](https://github.com/modelcontextprotocol) para criar nosso servidor MCP de gerenciador de tarefas. + +### Crie um novo projeto \{#create-a-new-project} + + + + +Configure um novo projeto Python: + +```bash +mkdir mcp-todo-server +cd mcp-todo-server + +# Inicialize um novo projeto Python +uv init + +# Crie um novo ambiente virtual usando uv +uv venv + +# Ative o ambiente virtual (opcional ao usar 'uv run') +source .venv/bin/activate +``` + +:::note +Este projeto usa `uv` para gerenciamento de pacotes, mas você pode usar outros gerenciadores como `pip`, `poetry` ou `conda` se preferir. +::: + + + + +Configure um novo projeto Node.js: + +```bash +mkdir mcp-server +cd mcp-server +npm init -y # Ou use `pnpm init` +npm pkg set type="module" +npm pkg set main="todo-manager.ts" +npm pkg set scripts.start="node --experimental-strip-types todo-manager.ts" +``` + +:::note +Estamos usando TypeScript em nossos exemplos, pois o Node.js v22.6.0+ suporta execução nativa de TypeScript usando a flag `--experimental-strip-types`. Se você estiver usando JavaScript, o código será semelhante - apenas certifique-se de usar Node.js v22.6.0 ou superior. Veja a documentação do Node.js para detalhes. +::: + + + + +### Instale o MCP SDK e dependências \{#install-the-mcp-sdk-and-dependencies} + + + + +Instale as dependências necessárias: + +```bash +uv add "mcp[cli]" uvicorn starlette +``` + + + + +```bash +npm install @modelcontextprotocol/sdk express zod +``` + +Ou qualquer outro gerenciador de pacotes de sua preferência, como `pnpm` ou `yarn`. + + + + +### Crie o servidor MCP \{#create-the-mcp-server} + +Primeiro, vamos criar um servidor MCP básico com as definições das ferramentas: + + + + +Crie um arquivo chamado `server.py` e adicione o seguinte código: + +```python +# server.py + +import contextlib +from typing import Any +from mcp.server.fastmcp import FastMCP +from starlette.applications import Starlette +from starlette.routing import Mount + +# Inicialize o servidor FastMCP +mcp = FastMCP(name="Todo Manager", stateless_http=True, streamable_http_path='/') + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """Cria uma nova tarefa. Requer escopo 'create:todos'.""" + return {"error": "Not implemented"} + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """Lista tarefas. Usuários com escopo 'read:todos' podem ver todas as tarefas.""" + return {"error": "Not implemented"} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """Exclui uma tarefa pelo id. Usuários podem excluir suas próprias tarefas.""" + return {"error": "Not implemented"} + +@contextlib.asynccontextmanager +async def lifespan(app: Starlette): + async with contextlib.AsyncExitStack() as stack: + await stack.enter_async_context(mcp.session_manager.run()) + yield + +# Crie o app +app = Starlette( + routes=[ + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + +Execute o servidor com: + +```bash +# Inicie o servidor Todo Manager usando uvicorn +uvicorn server:app --host 127.0.0.1 --port 3001 + +# Ou usando uv: +# uv run uvicorn server:app --host 127.0.0.1 --port 3001 +``` + + + + +Crie um arquivo chamado `todo-manager.ts` e adicione o seguinte código: + +```ts +// todo-manager.ts + +import { z } from 'zod'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import express, { type Request, type Response } from 'express'; + +// Crie um servidor MCP +const server = new McpServer({ + name: 'Todo Manager', + version: '0.0.0', +}); + +server.tool('create-todo', 'Criar uma nova tarefa', { content: z.string() }, async ({ content }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('get-todos', 'Listar todas as tarefas', async () => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('delete-todo', 'Excluir uma tarefa pelo id', { id: z.string() }, async ({ id }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +// Abaixo está o código boilerplate da documentação do MCP SDK +const PORT = 3001; +const app = express(); + +app.post('/', async (request: Request, response: Response) => { + // Em modo stateless, crie uma nova instância de transporte e servidor para cada requisição + // para garantir isolamento completo. Uma única instância causaria colisão de IDs de requisição + // quando múltiplos clientes conectam simultaneamente. + + try { + const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + }); + response.on('close', async () => { + console.log('Request closed'); + await transport.close(); + await server.close(); + }); + await server.connect(transport); + await transport.handleRequest(request, response, request.body); + } catch (error) { + console.error('Error handling MCP request:', error); + if (!response.headersSent) { + response.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32_603, + message: 'Internal server error', + }, + id: null, + }); + } + } +}); + +// Notificações SSE não suportadas em modo stateless +app.get('/', async (request: Request, response: Response) => { + console.log('Received GET MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +// Encerramento de sessão não necessário em modo stateless +app.delete('/', async (request: Request, response: Response) => { + console.log('Received DELETE MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +app.listen(PORT); +``` + +Execute o servidor com: + +```bash +npm start +``` + + + + +## Inspecione o servidor MCP \{#inspect-the-mcp-server} + +### Clone e execute o MCP inspector \{#clone-and-run-mcp-inspector} + +Agora que temos o servidor MCP rodando, podemos usar o MCP inspector para ver se as ferramentas estão disponíveis. + +O MCP inspector oficial v0.16.2 possui alguns bugs que afetam a funcionalidade de autenticação. Para resolver esses problemas, criamos uma [versão corrigida do MCP inspector](https://github.com/mcp-auth/inspector/tree/patch/0.16.2-fixes) que inclui correções necessárias para fluxos de autenticação OAuth/OIDC. Também enviamos pull requests para o repositório oficial para contribuir com essas correções. + +Para executar o MCP inspector, use o seguinte comando (Node.js é necessário): + +```bash +git clone https://github.com/mcp-auth/inspector.git -b patch/0.16.2-fixes +cd inspector +npm install +npm run dev +``` + +O MCP inspector abrirá automaticamente em seu navegador padrão, ou você pode acessá-lo manualmente clicando no link exibido no terminal (certifique-se de clicar no link que inclui o parâmetro `MCP_PROXY_AUTH_TOKEN`, como `http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=458ae4a4...acab1907`). + +### Conecte o MCP inspector ao servidor MCP \{#connect-mcp-inspector-to-the-mcp-server} + +Antes de prosseguir, verifique a seguinte configuração no MCP inspector: + +- **Tipo de Transporte**: Defina como `Streamable HTTP`. +- **URL**: Defina para a URL do seu servidor MCP. No nosso caso, deve ser `http://localhost:3001`. + +Agora você pode clicar no botão "Connect" para ver se o MCP inspector consegue conectar ao servidor MCP. Se tudo estiver certo, você verá o status "Connected" no MCP inspector. + +### Checkpoint: Execute as ferramentas do gerenciador de tarefas \{#checkpoint-run-todo-manager-tools} + +1. No menu superior do MCP inspector, clique na aba "Tools". +2. Clique no botão "List Tools". +3. Você deve ver as ferramentas `create-todo`, `get-todos` e `delete-todo` listadas na página. Clique para abrir os detalhes da ferramenta. +4. Você deve ver o botão "Run Tool" no lado direito. Clique nele e insira os parâmetros necessários para executar a ferramenta. +5. Você verá o resultado da ferramenta com a resposta JSON `{"error": "Not implemented"}`. + +![Primeira execução do MCP inspector](/docs-assets/images/tutorials/todo-manager/inspector-first-run.png) + +## Integre com seu servidor de autorização \{#integrate-with-your-authorization-server} + +Para concluir esta seção, há várias considerações a serem feitas: + +
+**A URL do emissor do seu servidor de autorização** + +Geralmente é a URL base do seu servidor de autorização, como `https://auth.exemplo.com`. Alguns provedores podem ter um caminho como `https://exemplo.logto.app/oidc`, então verifique a documentação do seu provedor. + +
+ +
+**Como recuperar os metadados do servidor de autorização** + +- Se seu servidor de autorização estiver em conformidade com o [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) ou [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html), você pode usar as utilidades integradas do MCP Auth para buscar os metadados automaticamente. +- Se seu servidor de autorização não estiver em conformidade com esses padrões, você precisará especificar manualmente a URL dos metadados ou endpoints na configuração do servidor MCP. Consulte a documentação do seu provedor para os endpoints específicos. + +
+ +
+**Como registrar o MCP inspector como cliente em seu servidor de autorização** + +- Se seu servidor de autorização suporta [Registro Dinâmico de Cliente](https://datatracker.ietf.org/doc/html/rfc7591), você pode pular esta etapa, pois o MCP inspector se registrará automaticamente como cliente. +- Se seu servidor de autorização não suporta Registro Dinâmico de Cliente, você precisará registrar manualmente o MCP inspector como cliente em seu servidor de autorização. + +
+ +
+**Entenda os parâmetros de requisição de token** + +Ao solicitar tokens de acesso de diferentes servidores de autorização, você encontrará várias abordagens para especificar o recurso alvo e permissões. Aqui estão os principais padrões: + +- **Baseado em indicador de recurso**: + + - Usa o parâmetro `resource` para especificar a API alvo (veja [RFC 8707: Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707)) + - Comum em implementações modernas de OAuth 2.0 + - Exemplo de requisição: + ```json + { + "resource": "http://localhost:3001", + "scope": "create:todos read:todos" + } + ``` + - O servidor emite tokens vinculados especificamente ao recurso solicitado + +- **Baseado em audiência**: + + - Usa o parâmetro `audience` para especificar o destinatário pretendido do token + - Semelhante a indicadores de recurso, mas com semânticas diferentes + - Exemplo de requisição: + ```json + { + "audience": "todo-api", + "scope": "create:todos read:todos" + } + ``` + +- **Baseado apenas em escopo**: + - Depende apenas de escopos sem parâmetros de recurso/audiência + - Abordagem tradicional do OAuth 2.0 + - Exemplo de requisição: + ```json + { + "scope": "todo-api:create todo-api:read openid profile" + } + ``` + - Frequentemente usa escopos prefixados para namespacing de permissões + - Comum em implementações OAuth 2.0 mais simples + +:::tip Boas Práticas + +- Verifique a documentação do seu provedor para parâmetros suportados +- Alguns provedores suportam múltiplas abordagens simultaneamente +- Indicadores de recurso fornecem melhor segurança por restrição de audiência +- Considere usar indicadores de recurso quando disponíveis para melhor controle de acesso + ::: + +
+ +Embora cada provedor possa ter seus próprios requisitos específicos, os passos a seguir irão guiá-lo no processo de integração do MCP inspector e do servidor MCP com configurações específicas do provedor. + +### Registre o MCP inspector como cliente \{#register-mcp-inspector-as-a-client} + + + + +Integrar o gerenciador de tarefas com o [Logto](https://logto.io) é simples, pois é um provedor OpenID Connect que suporta indicadores de recurso e escopos, permitindo proteger sua API de tarefas com `http://localhost:3001` como indicador de recurso. + +Como o Logto ainda não suporta Registro Dinâmico de Cliente, você precisará registrar manualmente o MCP inspector como cliente em seu tenant Logto: + +1. Abra seu MCP inspector, vá para a configuração de Autenticação e clique em "OAuth2.0 Flow". Copie o valor **Redirect URI**, que deve ser algo como `http://localhost:6274/oauth/callback`. +2. Faça login no [Logto Console](https://cloud.logto.io) (ou em seu Logto Console auto-hospedado). +3. Navegue até a aba "Aplicações", clique em "Criar aplicação". No final da página, clique em "Criar app sem framework". +4. Preencha os detalhes da aplicação e clique em "Criar aplicação": + - **Selecione um tipo de aplicação**: Escolha "Aplicação de página única". + - **Nome da aplicação**: Insira um nome para sua aplicação, por exemplo, "MCP Inspector". +5. Na seção "Configurações / Redirect URIs", cole o valor **Redirect URI** copiado do MCP inspector. Depois clique em "Salvar alterações" na barra inferior. +6. No cartão superior, você verá o valor "App ID". Copie-o. +7. Volte ao MCP inspector e cole o valor "App ID" na configuração de Autenticação em "OAuth2.0 Flow" no campo "Client ID". +8. No campo "Scope", insira: `create:todos read:todos delete:todos`. Isso garantirá que o token de acesso retornado pelo Logto contenha os escopos necessários para acessar o gerenciador de tarefas. + + + + +:::note +Este é um guia genérico de integração com provedores OAuth 2.0 / OpenID Connect. Ambos seguem passos semelhantes, pois OIDC é construído sobre OAuth 2.0. Consulte a documentação do seu provedor para detalhes específicos. +::: + +Se seu provedor suporta Registro Dinâmico de Cliente, você pode ir diretamente para o passo 8 abaixo para configurar o MCP inspector; caso contrário, será necessário registrar manualmente o MCP inspector como cliente: + +1. Abra seu MCP inspector, vá para a configuração de Autenticação e clique em "OAuth2.0 Flow". Copie o valor **Redirect URI**, que deve ser algo como `http://localhost:6274/oauth/callback`. + +2. Faça login no console do seu provedor. + +3. Navegue até a seção "Aplicações" ou "Clientes" e crie uma nova aplicação ou cliente. + +4. Se seu provedor exigir um tipo de cliente, selecione "Aplicação de página única" ou "Cliente público". + +5. Após criar a aplicação, você precisará configurar o redirect URI. Cole o valor **Redirect URI** copiado do MCP inspector. + +6. Encontre o "Client ID" ou "Application ID" da nova aplicação criada e copie-o. + +7. Volte ao MCP inspector e cole o valor "Client ID" na configuração de Autenticação em "OAuth2.0 Flow" no campo "Client ID". + +8. No campo "Scope", insira os seguintes escopos para solicitar as permissões necessárias para operações de tarefas: + +```text +create:todos read:todos delete:todos +``` + + + + +### Configure o MCP Auth \{#set-up-mcp-auth} + +Primeiro, instale o SDK MCP Auth em seu projeto do servidor MCP. + + + + +```bash +uv add mcpauth==0.2.0b1 +``` + + + + +```bash +npm install mcp-auth@0.2.0-beta.1 +``` + + + + +Agora precisamos inicializar o MCP Auth em seu servidor MCP. Isso envolve dois passos principais: + +1. **Buscar metadados do servidor de autorização**: Usado para a verificação posterior do MCP Auth dos tokens de acesso emitidos pelo Servidor de Autorização, e para incluir o identificador do emissor do servidor de autenticação nos metadados do recurso +2. **Configurar metadados do recurso protegido**: Definir o identificador do recurso do seu servidor MCP e os escopos suportados + +#### Passo 1: Buscar metadados do servidor de autorização \{#step-1-fetch-authorization-server-metadata\} + +De acordo com a especificação OAuth / OIDC, podemos recuperar os metadados do servidor de autorização com base na URL do emissor do servidor de autorização. + + + + + +No Logto, você pode encontrar a URL do emissor na página de detalhes da aplicação dentro do Logto Console, na seção "Endpoints & Credentials / Issuer endpoint". Deve ser algo como `https://meu-projeto.logto.app/oidc`. + + + + + +Para provedores OAuth 2.0, você precisará: + +1. Verificar a documentação do seu provedor para a URL do servidor de autorização (geralmente chamada de issuer URL ou base URL) +2. Alguns provedores podem expor isso em `https://{seu-dominio}/.well-known/oauth-authorization-server` +3. Procurar no console de administração do seu provedor em configurações OAuth/API + + + + + +Agora, busque os metadados do servidor de autorização usando a função utilitária do MCP Auth para recuperar a configuração do servidor: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +issuer_url = "" # Substitua pela URL do emissor do seu servidor de autorização + +# Buscar configuração do servidor de autorização +auth_server_config = fetch_server_config(issuer_url, AuthServerType.OIDC) # ou AuthServerType.OAUTH +``` + + + +```js +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const issuerUrl = ''; // Substitua pela URL do emissor do seu servidor de autorização + +// Buscar configuração do servidor de autorização (OIDC Discovery) +const authServerConfig = await fetchServerConfig(issuerUrl, { type: 'oidc' }); // ou { type: 'oauth' } +``` + + + + +Se precisar de formas alternativas de buscar metadados do servidor de autorização ou quiser personalizar a configuração, consulte [outras formas de configurar metadados do servidor de autorização](/docs/configure-server/mcp-auth#other-ways). + +#### Passo 2: Configure os metadados do recurso protegido \{#step-2-configure-protected-resource-metadata} + +Em seguida, vamos configurar os Metadados do Recurso Protegido ao construir a instância MCP Auth. Posteriormente, o servidor MCP exporá os metadados do recurso configurados no MCP Auth. + + + + +```python +# server.py + +# outros imports... +from mcpauth.types import ResourceServerConfig, ResourceServerMetadata + +# Defina o identificador do recurso para este servidor MCP +resource_id = "http://localhost:3001" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + # Metadados do servidor de autorização buscados no passo anterior + authorization_servers=[auth_server_config], + # Escopos que este servidor MCP entende + scopes_supported=[ + "create:todos", + "read:todos", + "delete:todos" + ] + ) + ) +) +``` + + + +```js +// todo-manager.ts + +// Defina o identificador do recurso para este servidor MCP +const resourceId = 'http://localhost:3001'; + +// Configure o MCP Auth com os metadados do recurso protegido +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceId, + // Metadados do servidor de autorização buscados no passo anterior + authorizationServers: [authServerConfig], + // Escopos que este servidor MCP entende + scopesSupported: [ + "create:todos", + "read:todos", + "delete:todos" + ] + } + } +}); +``` + + + + +### Atualize o servidor MCP \{#update-mcp-server} + +Estamos quase lá! É hora de atualizar o servidor MCP para aplicar a rota e função middleware do MCP Auth, depois implementar o controle de acesso baseado em permissões para as ferramentas do gerenciador de tarefas com base nos escopos do usuário. + +Agora, aplique as rotas de metadados do recurso protegido para que clientes MCP possam recuperar os metadados esperados do recurso do servidor MCP. + + + +```python +# server.py + +# ..outros códigos + +app = Starlette( + routes=[ + # Configure rotas de Metadados do Recurso Protegido + # Isso expõe metadados sobre este servidor de recursos para clientes OAuth + *mcp_auth.resource_metadata_router().routes, + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +// Configure rotas de Metadados do Recurso Protegido +// Isso expõe metadados sobre este servidor de recursos para clientes OAuth +app.use(mcpAuth.protectedResourceMetadataRouter()); + +``` + + + +Em seguida, aplicaremos o middleware MCP Auth ao servidor MCP. Este middleware irá lidar com autenticação e autorização para requisições recebidas, garantindo que apenas usuários autorizados possam acessar as ferramentas do gerenciador de tarefas. + + + +```python +# server.py + +# outros imports... +from starlette.middleware import Middleware + +# outros códigos... + +# Crie o middleware +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', resource=resource_id, audience=resource_id)) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # Aplique o middleware MCP Auth + Mount("/", app=mcp.streamable_http_app(), middleware=[bearer_auth]), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// Aplique o middleware MCP Auth +app.use( + mcpAuth.bearerAuth('jwt', { + resource: resourceId, + audience: resourceId, + }) +); +``` + + + +Neste ponto, podemos atualizar as ferramentas do gerenciador de tarefas para aproveitar o middleware MCP Auth para autenticação e autorização. + +Vamos atualizar a implementação das ferramentas. + + + +```python +# server.py + +# outros imports... + +from typing import Any, List, Optional +from mcpauth.exceptions import MCPAuthBearerAuthException, BearerAuthExceptionCode +from mcpauth.types import AuthInfo, ResourceServerConfig, ResourceServerMetadata + +# Será mencionado na próxima seção +from service import TodoService + +def assert_user_id(auth_info: Optional[AuthInfo]) -> str: + """Garante que auth_info contenha um ID de usuário válido e o retorna.""" + if not auth_info or not auth_info.subject: + raise Exception("Invalid auth info") + return auth_info.subject + +def has_required_scopes(user_scopes: List[str], required_scopes: List[str]) -> bool: + """Verifica se o usuário possui todos os escopos necessários.""" + return all(scope in user_scopes for scope in required_scopes) + +# Crie a instância do TodoService +todo_service = TodoService() + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """Cria uma nova tarefa. Requer escopo 'create:todos'.""" + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # Apenas usuários com escopo 'create:todos' podem criar tarefas + user_scopes = auth_info.scopes if auth_info else [] + if not has_required_scopes(user_scopes, ["create:todos"]): + raise MCPAuthBearerAuthException(BearerAuthExceptionCode.MISSING_REQUIRED_SCOPES) + + created_todo = todo_service.create_todo(content=content, owner_id=user_id) + return created_todo + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """ + Lista tarefas. Usuários com escopo 'read:todos' podem ver todas as tarefas, + caso contrário, só podem ver suas próprias tarefas. + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # Se o usuário tem escopo 'read:todos', pode acessar todas as tarefas + # Se não, pode acessar apenas suas próprias tarefas + user_scopes = auth_info.scopes if auth_info else [] + todo_owner_id = None if has_required_scopes(user_scopes, ["read:todos"]) else user_id + + todos = todo_service.get_all_todos(todo_owner_id) + return {"todos": todos} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """ + Exclui uma tarefa pelo id. Usuários podem excluir suas próprias tarefas. + Usuários com escopo 'delete:todos' podem excluir qualquer tarefa. + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + todo = todo_service.get_todo_by_id(id) + + if not todo: + return {"error": "Failed to delete todo"} + + # Usuários só podem excluir suas próprias tarefas + # Usuários com escopo 'delete:todos' podem excluir qualquer tarefa + user_scopes = auth_info.scopes if auth_info else [] + if todo.owner_id != user_id and not has_required_scopes(user_scopes, ["delete:todos"]): + return {"error": "Failed to delete todo"} + + deleted_todo = todo_service.delete_todo(id) + + if deleted_todo: + return { + "message": f"Todo {id} deleted", + "details": deleted_todo + } + else: + return {"error": "Failed to delete todo"} +``` + + + +```js +// todo-manager.ts + +// outros imports... +import assert from 'node:assert'; +import { fetchServerConfig, MCPAuth, MCPAuthBearerAuthError } from 'mcp-auth'; +import { type AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js'; + +// Será mencionado na próxima seção +import { TodoService } from './todo-service.js'; + +const assertUserId = (authInfo?: AuthInfo) => { + const { subject } = authInfo ?? {}; + assert(subject, 'Invalid auth info'); + return subject; +}; + +const hasRequiredScopes = (userScopes: string[], requiredScopes: string[]): boolean => { + return requiredScopes.every((scope) => userScopes.includes(scope)); +}; + +const todoService = new TodoService(); + +server.tool( + 'create-todo', + 'Criar uma nova tarefa', + { content: z.string() }, + ({ content }: { content: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * Apenas usuários com escopo 'create:todos' podem criar tarefas + */ + if (!hasRequiredScopes(authInfo?.scopes ?? [], ['create:todos'])) { + throw new MCPAuthBearerAuthError('missing_required_scopes'); + } + + const createdTodo = todoService.createTodo({ content, ownerId: userId }); + + return { + content: [{ type: 'text', text: JSON.stringify(createdTodo) }], + }; + } +); + +server.tool('get-todos', 'Listar todas as tarefas', ({ authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * Se o usuário tem escopo 'read:todos', pode acessar todas as tarefas (todoOwnerId = undefined) + * Se não, pode acessar apenas suas próprias tarefas (todoOwnerId = userId) + */ + const todoOwnerId = hasRequiredScopes(authInfo?.scopes ?? [], ['read:todos']) + ? undefined + : userId; + + const todos = todoService.getAllTodos(todoOwnerId); + + return { + content: [{ type: 'text', text: JSON.stringify(todos) }], + }; +}); + +server.tool( + 'delete-todo', + 'Excluir uma tarefa pelo id', + { id: z.string() }, + ({ id }: { id: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + const todo = todoService.getTodoById(id); + + if (!todo) { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Failed to delete todo' }) }], + }; + } + + /** + * Usuários só podem excluir suas próprias tarefas + * Usuários com escopo 'delete:todos' podem excluir qualquer tarefa + */ + if (todo.ownerId !== userId && !hasRequiredScopes(authInfo?.scopes ?? [], ['delete:todos'])) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ error: 'Failed to delete todo' }), + }, + ], + }; + } + + const deletedTodo = todoService.deleteTodo(id); + + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + message: `Todo ${id} deleted`, + details: deletedTodo, + }), + }, + ], + }; + } +); +``` + + + +Agora, crie o "serviço de tarefas" usado no código acima para implementar a funcionalidade relacionada: + + + + +Crie o arquivo `service.py` para o serviço de tarefas: + +```python +""" +Um serviço simples de tarefas para fins de demonstração. +Usa uma lista em memória para armazenar tarefas. +""" + +from datetime import datetime +from typing import List, Optional, Dict, Any +import random +import string + +class Todo: + """Representa um item de tarefa.""" + + def __init__(self, id: str, content: str, owner_id: str, created_at: str): + self.id = id + self.content = content + self.owner_id = owner_id + self.created_at = created_at + + def to_dict(self) -> Dict[str, Any]: + """Converte a tarefa para dicionário para serialização JSON.""" + return { + "id": self.id, + "content": self.content, + "ownerId": self.owner_id, + "createdAt": self.created_at + } + + +class TodoService: + """Um serviço simples de tarefas para fins de demonstração.""" + + def __init__(self): + self._todos: List[Todo] = [] + + def get_all_todos(self, owner_id: Optional[str] = None) -> List[Dict[str, Any]]: + """ + Obtém todas as tarefas, opcionalmente filtradas por owner_id. + + Args: + owner_id: Se fornecido, retorna apenas tarefas deste usuário + + Returns: + Lista de dicionários de tarefas + """ + if owner_id: + filtered_todos = [todo for todo in self._todos if todo.owner_id == owner_id] + return [todo.to_dict() for todo in filtered_todos] + return [todo.to_dict() for todo in self._todos] + + def get_todo_by_id(self, todo_id: str) -> Optional[Todo]: + """ + Obtém uma tarefa pelo ID. + + Args: + todo_id: O ID da tarefa a ser recuperada + + Returns: + Objeto Todo se encontrado, None caso contrário + """ + for todo in self._todos: + if todo.id == todo_id: + return todo + return None + + def create_todo(self, content: str, owner_id: str) -> Dict[str, Any]: + """ + Cria uma nova tarefa. + + Args: + content: O conteúdo da tarefa + owner_id: O ID do usuário dono da tarefa + + Returns: + Representação em dicionário da tarefa criada + """ + todo = Todo( + id=self._generate_id(), + content=content, + owner_id=owner_id, + created_at=datetime.now().isoformat() + ) + self._todos.append(todo) + return todo.to_dict() + + def delete_todo(self, todo_id: str) -> Optional[Dict[str, Any]]: + """ + Exclui uma tarefa pelo ID. + + Args: + todo_id: O ID da tarefa a ser excluída + + Returns: + Representação em dicionário da tarefa excluída se encontrada, None caso contrário + """ + for i, todo in enumerate(self._todos): + if todo.id == todo_id: + deleted_todo = self._todos.pop(i) + return deleted_todo.to_dict() + return None + + def _generate_id(self) -> str: + """Gera um ID aleatório para uma tarefa.""" + return ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)) +``` + + + + +Crie o arquivo `todo-service.ts` para o serviço de tarefas: + +```ts +// todo-service.ts + +type Todo = { + id: string; + content: string; + ownerId: string; + createdAt: string; +}; + +/** + * Um serviço simples de tarefas para fins de demonstração. + * Usa um array em memória para armazenar tarefas + */ +export class TodoService { + private readonly todos: Todo[] = []; + + getAllTodos(ownerId?: string): Todo[] { + if (ownerId) { + return this.todos.filter((todo) => todo.ownerId === ownerId); + } + return this.todos; + } + + getTodoById(id: string): Todo | undefined { + return this.todos.find((todo) => todo.id === id); + } + + createTodo({ content, ownerId }: { content: string; ownerId: string }): Todo { + const todo: Todo = { + id: this.genId(), + content, + ownerId, + createdAt: new Date().toISOString(), + }; + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + this.todos.push(todo); + return todo; + } + + deleteTodo(id: string): Todo | undefined { + const index = this.todos.findIndex((todo) => todo.id === id); + + if (index === -1) { + return undefined; + } + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + const [deleted] = this.todos.splice(index, 1); + return deleted; + } + + private genId(): string { + return Math.random().toString(36).slice(2, 10); + } +} +``` + + + + +🎉 Parabéns! Implementamos com sucesso um servidor MCP completo com autenticação e autorização! + +Você também pode conferir nosso código de exemplo como referência: + + + + +:::info +Confira o [repositório MCP Auth Python SDK](https://github.com/mcp-auth/python/tree/master/samples/current/todo-manager) para o código completo do servidor MCP (versão OIDC). +::: + + + + +:::info +Confira o [repositório MCP Auth Node.js SDK](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) para o código completo do servidor MCP (versão OIDC). +::: + + + + +## Checkpoint: Execute as ferramentas `todo-manager` \{#checkpoint-run-the-todo-manager-tools} + +Reinicie seu servidor MCP e abra o MCP inspector no navegador. Ao clicar no botão "Connect", você deve ser redirecionado para a página de login do seu servidor de autorização. + +Depois de fazer login e retornar ao MCP inspector, repita as ações do checkpoint anterior para executar as ferramentas do gerenciador de tarefas. Desta vez, você poderá usar essas ferramentas com sua identidade de usuário autenticada. O comportamento das ferramentas dependerá dos papéis e permissões atribuídos ao seu usuário: + +- Se você estiver logado como **User** (com apenas o escopo `create:todos`): + + - Pode criar novas tarefas usando a ferramenta `create-todo` + - Só pode visualizar e excluir suas próprias tarefas + - Não poderá ver ou excluir tarefas de outros usuários + +- Se estiver logado como **Admin** (com todos os escopos: `create:todos`, `read:todos`, `delete:todos`): + - Pode criar novas tarefas + - Pode visualizar todas as tarefas do sistema usando a ferramenta `get-todos` + - Pode excluir qualquer tarefa usando a ferramenta `delete-todo`, independentemente de quem a criou + +Você pode testar esses diferentes níveis de permissão: + +1. Saindo da sessão atual (clique no botão "Disconnect" no MCP inspector) +2. Fazendo login com outra conta de usuário que tenha papéis/permissões diferentes +3. Testando novamente as ferramentas para observar como o comportamento muda de acordo com as permissões do usuário + +Isso demonstra como o controle de acesso baseado em papel (RBAC) funciona na prática, onde diferentes usuários têm diferentes níveis de acesso à funcionalidade do sistema. + +![Resultado da ferramenta do gerenciador de tarefas no MCP inspector](/docs-assets/images/tutorials/todo-manager/result.png) + + + + +:::info +Confira o [repositório MCP Auth Python SDK](https://github.com/mcp-auth/python) para o código completo do servidor MCP (versão OIDC). +::: + + + + +:::info +Confira o [repositório MCP Auth Node.js SDK](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) para o código completo do servidor MCP (versão OIDC). +::: + + + + +## Notas finais \{#closing-notes} + +🎊 Parabéns! Você concluiu com sucesso o tutorial. Vamos recapitular o que fizemos: + +- Configuração de um servidor MCP básico com ferramentas de gerenciamento de tarefas (`create-todo`, `get-todos`, `delete-todo`) +- Implementação de controle de acesso baseado em papel (RBAC) com diferentes níveis de permissão para usuários e administradores +- Integração do servidor MCP com um servidor de autorização usando MCP Auth +- Configuração do MCP Inspector para autenticar usuários e usar tokens de acesso com escopos para chamar ferramentas + +Não deixe de conferir outros tutoriais e a documentação para aproveitar ao máximo o MCP Auth. \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/README.mdx b/i18n/zh-CN/docusaurus-plugin-content-docs/current/README.mdx new file mode 100644 index 0000000..48a12dd --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/README.mdx @@ -0,0 +1,297 @@ +--- +sidebar_position: 1 +sidebar_label: 入门 +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# 入门 + +:::info MCP 授权 (Authorization) 规范支持 +此版本支持 [MCP 授权 (Authorization) 规范(2025-06-18 版本)](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization)。 +::: + + +## 选择兼容的 OAuth 2.1 或 OpenID Connect 提供商 \{#choose-a-compatible-oauth-2-1-or-openid-connect-provider} + +MCP 规范对授权 (Authorization) 有[特定要求](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#standards-compliance)。授权 (Authorization) 机制基于既定规范,实施其部分精选功能,以确保安全性和互操作性,同时保持简洁: + +- OAuth 2.1 IETF DRAFT ([draft-ietf-oauth-v2-1-13](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13)) +- OAuth 2.0 授权服务器元数据 ([RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)) +- OAuth 2.0 动态客户端注册协议 ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) +- OAuth 2.0 受保护资源元数据 ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)) + +这些规范协同工作,为 MCP 实现提供安全且标准化的授权 (Authorization) 框架。 + +你可以查看 [MCP 兼容提供商列表](/provider-list),了解你的提供商是否受支持。 + +## 安装 MCP Auth SDK \{#install-mcp-auth-sdk} + +MCP Auth 支持 Python 和 TypeScript。如果你需要其他语言或框架的支持,请告知我们! + + + + +```bash +pip install mcpauth +``` + +或者你喜欢的其他包管理器,如 pipenv 或 poetry。 + + + + +```bash +npm install mcp-auth +``` + +或者你喜欢的其他包管理器,如 pnpm 或 yarn。 + + + + +## 初始化 MCP Auth \{#init-mcp-auth} + +第一步是定义你的资源标识符,并配置将被信任用于认证 (Authentication) 的授权服务器。MCP Auth 现在以资源服务器模式运行,符合最新 MCP 规范对 OAuth 2.0 受保护资源元数据(RFC 9728)的要求。 + +如果你的提供商符合: + +- [OAuth 2.0 授权服务器元数据](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +你可以使用内置函数获取元数据并初始化 MCP Auth 实例: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType, ResourceServerConfig, ResourceServerMetadata +from mcpauth.utils import fetch_server_config + +# 1. 定义你的资源标识符,并获取其信任的授权服务器配置。 +resource_id = "https://api.example.com/notes" +auth_server_config = fetch_server_config("https://auth.logto.io/oidc", AuthServerType.OIDC) + +# 2. 以资源服务器模式初始化 MCPAuth。 +# `protected_resources` 可以是单个对象,也可以是多个资源的列表。 +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +// 1. 定义你的资源标识符,并获取其信任的授权服务器配置。 +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +// 2. 以资源服务器模式初始化 MCPAuth。 +// `protectedResources` 可以是单个对象,也可以是多个资源的数组。 +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +如需通过自定义元数据 URL、数据转译或手动指定元数据等其他方式配置授权服务器元数据,请查看 [配置 MCP Auth 的其他方式](./configure-server/mcp-auth.mdx#other-ways)。 + +## 挂载受保护资源元数据端点 \{#mount-the-protected-resource-metadata-endpoint} + +为符合最新 MCP 规范,MCP Auth 会将 OAuth 2.0 受保护资源元数据端点(RFC 9728)挂载到你的 MCP 服务器。此端点允许客户端发现: + +- 哪些授权服务器可以为你的受保护资源签发有效令牌 +- 每个资源支持哪些权限 (Scopes) +- 令牌正确验证所需的其他元数据 + +端点路径会根据你的资源标识符的路径部分自动确定: + +- **无路径**:`https://api.example.com` → `/.well-known/oauth-protected-resource` +- **有路径**:`https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + +MCP 服务器现在**作为资源服务器**,负责验证令牌并提供其受保护资源的元数据,同时完全依赖外部授权服务器进行认证 (Authentication) 和授权 (Authorization)。 + +你可以使用 SDK 提供的方法挂载此端点: + + + + +```python +from starlette.applications import Starlette + +# 挂载路由以提供受保护资源元数据。 +# 资源 "https://api.example.com" → 端点: /.well-known/oauth-protected-resource +# 资源 "https://api.example.com/notes" → 端点: /.well-known/oauth-protected-resource/notes +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// 挂载路由以提供受保护资源元数据。 +// 资源 "https://api.example.com" → 端点: /.well-known/oauth-protected-resource +// 资源 "https://api.example.com/notes" → 端点: /.well-known/oauth-protected-resource/notes +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + + +## 使用 Bearer 认证 (Authentication) 中间件 \{#use-the-bearer-auth-middleware} + +初始化 MCP Auth 实例后,你可以应用 Bearer 认证 (Authentication) 中间件来保护你的 MCP 路由。该中间件现在需要指定端点所属的资源,以实现正确的令牌验证: + +:::note 受众 (Audience) 验证 +OAuth 2.0 规范要求 `audience` 参数用于安全的令牌验证。但目前为兼容尚未支持资源标识符的授权服务器,该参数**为可选**。出于安全考虑,**请尽可能始终包含 audience 参数**。未来版本将强制要求受众 (Audience) 验证,以完全符合规范。 +::: + + + + +```python +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount + +# 创建中间件,以资源特定策略保护你的 MCP 服务器。 +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', + resource=resource_id, + audience=resource_id, # 启用受众 (Audience) 验证以增强安全性 + required_scopes=['read:notes'] +)) + +# 挂载路由以提供受保护资源元数据,并保护 MCP 服务器。 +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # 使用 Bearer 认证 (Authentication) 中间件保护 MCP 服务器。 + Mount("/", app=mcp.sse_app(), middleware=[bearer_auth]), + ], +) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// 挂载路由以提供受保护资源元数据。 +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// 使用资源特定策略保护 API 端点。 +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, // 启用受众 (Audience) 验证以增强安全性 + requiredScopes: ['read:notes'], + }), + (req, res) => { + // 如果令牌有效,`req.auth` 会包含其声明 (Claims)。 + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); + +app.listen(3000); +``` + + + + +在上述示例中,我们指定了 `jwt` 令牌类型和资源标识符。中间件会自动针对为该资源配置的信任授权服务器验证 JWT 令牌,并填充认证 (Authentication) 用户的信息。 + +:::info +还不了解 JWT (JSON Web Token)?别担心,你可以继续阅读文档,我们会在需要时进行讲解。你也可以查看 [Auth Wiki](https://auth.wiki/jwt) 进行快速了解。 +::: + +关于 Bearer 认证 (Authentication) 配置的更多信息,请查看 [配置 Bearer 认证 (Authentication)](./configure-server/bearer-auth.mdx)。 + +## 在 MCP 实现中获取认证 (Authentication) 信息 \{#retrieve-the-auth-info-in-your-mcp-implementation} + +应用 Bearer 认证 (Authentication) 中间件后,你可以在 MCP 实现中访问认证 (Authentication) 用户(或身份)的信息: + + + + +Bearer 认证 (Authentication) 中间件应用后,MCP Auth 会在上下文变量中存储认证 (Authentication) 用户信息。你可以在 MCP 工具处理器中这样访问: + +```python +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP() + +# 按前述示例初始化 MCP Auth +# ... + +@mcp.tool() +def add(a: int, b: int): + """ + 一个将两个数字相加的工具。 + 认证 (Authentication) 用户信息将在上下文中可用。 + """ + auth_info = mcp_auth.auth_info # 在当前上下文中访问认证 (Authentication) 信息 + if auth_info: + print(f"Authenticated user: {auth_info.claims}") + return a + b +``` + + + + +工具处理器的第二个参数将包含 `authInfo` 对象,其中包括认证 (Authentication) 用户的信息: + +```ts +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { z } from 'zod'; + +const server = new McpServer(/* ... */); + +// 按前述示例初始化 MCP Auth +// ... + +server.tool('add', { a: z.number(), b: z.number() }, async ({ a, b }, { authInfo }) => { + // 现在你可以使用 `authInfo` 对象访问认证 (Authentication) 信息 +}); +``` + + + + +## 下一步 \{#next-steps} + +继续阅读,了解如何将 MCP Auth 与 MCP 服务器集成的端到端示例,以及如何在 MCP 客户端中处理认证 (Authentication) 流程。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx b/i18n/zh-CN/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx new file mode 100644 index 0000000..d4b6444 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx @@ -0,0 +1,280 @@ +--- +sidebar_position: 2 +sidebar_label: Bearer 认证 (Authentication) +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# 在 MCP 服务器中配置 Bearer 认证 (Authentication) + +根据最新的 MCP 规范,你的 MCP 服务器作为**资源服务器**,用于验证受保护资源的访问令牌 (Access token)。MCP Auth 提供了多种方式来配置 Bearer 授权 (Authorization): + +- [JWT (JSON Web Token)](https://auth.wiki/jwt) 模式:内置的授权 (Authorization) 方法,通过声明 (Claim) 断言验证 JWT。 +- 自定义模式:允许你实现自己的授权 (Authorization) 逻辑。 + +Bearer 认证 (Authentication) 中间件现在需要指定端点属于哪个资源,以便针对配置的授权 (Authorization) 服务器进行正确的令牌 (Token) 验证。 + +## 使用 JWT 模式配置 Bearer 认证 (Authentication) \{#configure-bearer-auth-with-jwt-mode} + +如果你的 OAuth / OIDC 提供方为授权 (Authorization) 签发 JWT,你可以在 MCP Auth 中使用内置的 JWT 模式。它会验证 JWT 的签名、过期时间以及你指定的其他声明 (Claims);然后会将认证 (Authentication) 信息填充到请求上下文中,供你的 MCP 实现进一步处理。 + +### 权限 (Scope) 校验 \{#scope-validation} + +以下是基本权限 (Scope) 校验的示例: + + + + +```python +from mcpauth import MCPAuth +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP("MyMCPServer") +mcp_auth = MCPAuth( + # Initialize with your auth server config +) +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", # 指定该端点属于哪个资源 + audience="https://api.example.com", # 启用受众 (Audience) 校验以提升安全性 + required_scopes=["read", "write"] # [!code highlight] +) + +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + /* ... */ +}); +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // 指定该端点属于哪个资源 + audience: 'https://api.example.com', // 启用受众 (Audience) 校验以提升安全性 + requiredScopes: ['read', 'write'] // [!code highlight] +}); + +app.use('/mcp', bearerAuth, (req, res) => { + // 现在 `req.auth` 包含认证 (Authentication) 信息 + console.log(req.auth); +}); +``` + + + + +在上面的示例中,我们指定 JWT 需要包含 `read` 和 `write` 权限 (Scopes)。如果 JWT 未包含**任意**这些权限 (Scopes),请求将被拒绝并返回 403 Forbidden 错误。 + +### 受众 (Audience) 校验(RFC 8707)\{#audience-validation-rfc-8707} + +为了安全地验证令牌 (Token),你应始终通过指定 `audience` 参数来启用受众 (Audience) 校验。这会校验 JWT 中的 `aud`(受众 (Audience))声明 (Claim),确保令牌 (Token) 是专门为你的 MCP 服务器资源签发的。 + +:::note 受众 (Audience) 校验 +OAuth 2.0 规范要求安全令牌 (Token) 验证时**必须**提供 `audience` 参数。但目前为了兼容尚未支持资源指示器 (Resource indicator) 的授权 (Authorization) 服务器,该参数**为可选**。出于安全考虑,**请尽可能始终包含 audience 参数**。未来版本将强制要求受众 (Audience) 校验,以完全符合规范。 +::: + +受众 (Audience) 的值通常应与你的资源标识符一致: + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", # 指定该端点属于哪个资源 + audience="https://api.example.com", # 启用受众 (Audience) 校验以提升安全性 [!code highlight] + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // 指定该端点属于哪个资源 + audience: 'https://api.example.com', // 启用受众 (Audience) 校验以提升安全性 [!code highlight] + requiredScopes: ['read', 'write'], +}); +``` + + + + +在上述示例中,MCP Auth 会同时校验 JWT 的 `aud` 声明 (Claim) 和所需权限 (Scopes)。 + +### 为 JWT 验证提供自定义选项 \{#provide-custom-options-to-the-jwt-verification} + +你还可以为底层 JWT 验证库提供自定义选项: + + + + +在 Python SDK 中,我们使用 [PyJWT](https://pyjwt.readthedocs.io/en/stable/) 进行 JWT 验证。你可以使用以下选项: + +- `leeway`:在验证 JWT 过期时间时允许一定的宽限时间(秒),默认 60 秒。 + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", + audience="https://api.example.com", + required_scopes=["read", "write"], + leeway=10, # 允许 10 秒的时钟偏差 [!code highlight] +) +``` + + + + +在 Node.js SDK 中,我们使用 [jose](https://github.com/panva/jose) 库进行 JWT 验证。你可以提供以下选项: + +- `jwtVerify`:JWT 验证过程的选项(`jose` 的 `jwtVerify` 函数)。 +- `remoteJwtSet`:远程 JWT 集合获取的选项(`jose` 的 `createRemoteJWKSet` 函数)。 + +```ts {5-10} +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', + requiredScopes: ['read', 'write'], + jwtVerify: { + clockTolerance: 60, // 允许 60 秒的时钟偏差 + }, + remoteJwtSet: { + timeoutDuration: 10 * 1000, // 远程 JWT 集合获取超时时间 10 秒 + }, +}); +``` + + + + +## 使用自定义验证配置 Bearer 认证 (Authentication) \{#configure-bearer-auth-with-custom-verification} + +如果你的 OAuth / OIDC 提供方不签发 JWT,或者你想实现自己的授权 (Authorization) 逻辑,MCP Auth 允许你创建自定义验证函数: + +:::info +由于 Bearer 认证 (Authentication) 中间件会根据给定的验证结果自动校验发行者 (Issuer)(`iss`)、受众 (Audience)(`aud`)和所需权限 (Scopes)(`scope`),你无需在自定义验证函数中实现这些校验。你只需专注于验证令牌 (Token) 的有效性(如签名、过期等)并返回认证 (Authentication) 信息对象即可。 +::: + + + + +```python +from mcpauth.exceptions import MCPAuthJwtVerificationException, MCPAuthJwtVerificationExceptionCode +from mcpauth.types import AuthInfo + +async def custom_verification(token: str) -> AuthInfo: + # 在这里实现你的自定义验证逻辑 + info = await verify_token(token) + if not info: + raise MCPAuthJwtVerificationException( + MCPAuthJwtVerificationExceptionCode.JWT_VERIFICATION_FAILED + ) + return info # 返回认证 (Authentication) 信息对象 + +bearer_auth = mcp_auth.bearer_auth_middleware( + custom_verification, + resource="https://api.example.com", + audience="https://api.example.com", # 启用受众 (Audience) 校验以提升安全性 + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth( + async (token) => { + // 在这里实现你的自定义验证逻辑 + const info = await verifyToken(token); + if (!info) { + throw new MCPAuthJwtVerificationError('jwt_verification_failed'); + } + return info; // 返回认证 (Authentication) 信息对象 + }, + { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // 启用受众 (Audience) 校验以提升安全性 + requiredScopes: ['read', 'write'] + } +); +``` + + + + +## 在 MCP 服务器中应用 Bearer 认证 (Authentication) \{#apply-bearer-auth-in-your-mcp-server} + +要用 Bearer 认证 (Authentication) 保护你的 MCP 服务器,你需要将 Bearer 认证 (Authentication) 中间件应用到 MCP 服务器实例上。 + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", + audience="https://api.example.com", # 启用受众 (Audience) 校验以提升安全性 + required_scopes=["read", "write"] +) +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```js +const app = express(); +app.use(mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // 启用受众 (Audience) 校验以提升安全性 + requiredScopes: ['read', 'write'] +})); +``` + + + + +这样可以确保所有传入请求都根据配置的 Bearer 认证 (Authentication) 设置进行认证 (Authentication) 和授权 (Authorization),并且认证 (Authentication) 信息会在请求上下文中可用。 + +你可以在 MCP 服务器实现中访问这些信息: + + + + +```python +@mcp.tool() +async def whoami() -> dict: + # `mcp_auth.auth_info` 是当前请求的上下文对象 + auth_info = mcp_auth.auth_info + print(f"Authenticated user: {auth_info.subject}") + return {"subject": auth_info.subject} +``` + + + + +```js +// `authInfo` 会从 `req.auth` 对象中传递过来 +server.tool('whoami', ({ authInfo }) => { + console.log(`Authenticated user: ${authInfo.subject}`); + return { subject: authInfo.subject }; +}); +``` + + + diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx b/i18n/zh-CN/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx new file mode 100644 index 0000000..87cbd1a --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx @@ -0,0 +1,290 @@ +--- +sidebar_position: 1 +sidebar_label: MCP Auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# 在 MCP 服务器中配置 MCP Auth + +根据最新的 [MCP 规范 (2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18),你的 MCP 服务器作为一个**资源服务器 (Resource Server)**,用于验证由外部授权服务器颁发的访问令牌 (Access tokens)。 + +要配置 MCP Auth,你需要完成两个主要步骤: +1. **配置授权服务器元数据 (Authorization Server Metadata)** —— 定义哪些授权服务器可以为你的 MCP 服务器颁发有效令牌,并指导 MCP 客户端从哪里获取访问令牌 (Access tokens) +2. **配置受保护资源元数据 (Protected Resource Metadata)** —— 将你的 MCP 服务器定义为受保护资源,并声明支持的权限 (Scopes) + +## 步骤 1:配置授权服务器元数据 (Authorization Server Metadata) \{#configure-authorization-server-metadata} + +### 自动获取元数据 \{#automatic-metadata-fetching} + +配置授权服务器元数据 (Authorization Server Metadata) 最简单的方法是使用内置函数,从 well-known URL 自动获取元数据。如果你的提供方符合以下标准之一: + +- [OAuth 2.0 授权服务器元数据 (Authorization Server Metadata)](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect 发现 (Discovery)](https://openid.net/specs/openid-connect-discovery-1_0.html) + +你可以通过提供 `issuer` URL,使用 `fetchServerConfig` 自动获取元数据: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +# 获取授权服务器元数据 +auth_server_config = fetch_server_config( + "https://auth.logto.io/oidc", + AuthServerType.OIDC # 或 AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +// 获取授权服务器元数据 +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); // 或 'oauth' +``` + + + + +如果你的 issuer 包含路径,OAuth 2.0 和 OpenID Connect 的行为略有不同: + +- **OAuth 2.0**:well-known URL 会追加到 issuer 的**域名**。例如,如果你的 issuer 是 `https://my-project.logto.app/oauth`,well-known URL 将是 `https://auth.logto.io/.well-known/oauth-authorization-server/oauth`。 +- **OpenID Connect**:well-known URL 会直接追加到**issuer**。例如,如果你的 issuer 是 `https://my-project.logto.app/oidc`,well-known URL 将是 `https://auth.logto.io/oidc/.well-known/openid-configuration`。 + +### 其他配置授权服务器元数据的方法 \{#other-ways} + +#### 自定义数据转换 \{#custom-data-transpilation} + +在某些情况下,提供方返回的元数据可能不符合预期格式。如果你确定提供方是合规的,可以使用 `transpile_data` 选项在使用前修改元数据: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +auth_server_config = fetch_server_config( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfig('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +这样你可以在 MCP Auth 使用元数据对象前进行修改。例如,你可以添加或移除字段、修改其值,或转换为不同格式。 + +#### 从指定 URL 获取元数据 \{#fetch-metadata-from-a-specific-url} + +如果你的提供方有特定的元数据 URL(而不是标准 URL),你也可以类似地使用它: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC # 或 AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfigByWellKnownUrl } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { type: 'oidc' }); // 或 'oauth' +``` + + + + +#### 从指定 URL 获取元数据并自定义数据转换 \{#fetch-metadata-from-a-specific-url-with-custom-data-transpilation} + +在某些情况下,提供方响应可能格式不正确或不符合预期元数据格式。如果你确定提供方是合规的,可以通过配置选项转换元数据: + + + + +```python +from mcpauth.config import AuthServerType, fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +#### 手动提供元数据 \{#manually-provide-metadata} + +如果你的提供方不支持元数据获取,你可以手动提供元数据对象: + + + + +```python +from mcpauth.config import AuthServerConfig, AuthServerType, AuthorizationServerMetadata + +auth_server_config = AuthServerConfig( + type=AuthServerType.OIDC, # 或 AuthServerType.OAUTH + metadata=AuthorizationServerMetadata( + issuer='', + authorization_endpoint='', + # ... 其他元数据字段 + ), +) +``` + + + + +```ts +const authServerConfig = { + metadata: { + issuer: '', + // 元数据字段应为 camelCase + authorizationEndpoint: '', + // ... 其他元数据字段 + }, + type: 'oidc', // 或 'oauth' +}; +``` + + + + +## 步骤 2:配置受保护资源元数据 (Protected Resource Metadata) \{#configure-protected-resource-metadata} + +配置好授权服务器元数据 (Authorization Server Metadata) 后,你需要通过定义受保护资源元数据来将 MCPAuth 初始化为资源服务器 (Resource Server)。 + +此步骤遵循 [RFC 9728 (OAuth 2.0 受保护资源元数据)](https://datatracker.ietf.org/doc/html/rfc9728) 规范,将你的 MCP 服务器描述为受保护资源: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import ResourceServerConfig, ResourceServerMetadata + +# 定义你的资源标识符 +resource_id = "https://api.example.com/notes" + +# 以资源服务器模式初始化 MCPAuth +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], # 使用步骤 1 的配置 + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth } from 'mcp-auth'; + +// 定义你的资源标识符 +const resourceIdentifier = 'https://api.example.com/notes'; + +// 以资源服务器模式初始化 MCPAuth +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], // 使用步骤 1 的配置 + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +对于多个资源,你可以提供受保护资源的数组,每个资源都有自己的元数据配置。 + +上述配置涵盖了基础设置。更多高级元数据参数,请参见 [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata)。 + +## 步骤 3:挂载受保护资源元数据端点 \{#mount-the-protected-resource-metadata-endpoint} + +挂载路由以提供受保护资源元数据端点。端点路径会根据你的资源标识符的路径部分自动确定: + +- **无路径**:`https://api.example.com` → `/.well-known/oauth-protected-resource` +- **有路径**:`https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + + + + +```python +from starlette.applications import Starlette +from mcpauth import MCPAuth + +mcp_auth = MCPAuth({/* ... */}) + +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +const mcpAuth = new MCPAuth({/* ... */}); + +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/README.md new file mode 100644 index 0000000..2412dc6 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/README.md @@ -0,0 +1,59 @@ +--- +sidebar_label: Node.js SDK +--- + +# MCP Auth Node.js SDK 参考 + +## 类 {#classes} + +- [MCPAuth](/references/js/classes/MCPAuth.md) +- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) +- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) +- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) +- [MCPAuthError](/references/js/classes/MCPAuthError.md) +- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) + +## 类型别名 {#type-aliases} + +- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) +- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) +- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) +- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) +- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) +- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) +- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) +- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) +- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) +- [AuthServerType](/references/js/type-aliases/AuthServerType.md) +- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) +- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) +- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) +- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) +- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) +- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) +- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) +- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) +- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) +- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) +- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) +- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) + +## 变量 {#variables} + +- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) +- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) +- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) +- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) +- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) +- [defaultValues](/references/js/variables/defaultValues.md) +- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) +- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) +- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) +- [validateServerConfig](/references/js/variables/validateServerConfig.md) + +## 函数 {#functions} + +- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) +- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) +- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) +- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md new file mode 100644 index 0000000..42d7d58 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md @@ -0,0 +1,281 @@ +--- +sidebar_label: MCPAuth +--- + +# 类:MCPAuth + +mcp-auth 库的主类。它作为工厂和注册中心,用于为你的受保护资源创建认证 (Authentication) 策略。 + +它通过你的服务器配置进行初始化,并提供 `bearerAuth` 方法,用于生成基于令牌的 Express 中间件认证 (Authentication)。 + +## 示例 {#example} + +### 在 `resource server` 模式下的用法 {#usage-in-resource-server-mode} + +这是新应用推荐的方式。 + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); + +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +const mcpAuth = new MCPAuth({ + // `protectedResources` 可以是单个配置对象,也可以是对象数组。 + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); + +// 挂载路由以处理受保护资源元数据 +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// 为已配置资源保护 API 端点 +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, // 指定该端点属于哪个资源 + audience: resourceIdentifier, // 可选,校验 'aud' 声明 + requiredScopes: ['read:notes'], + }), + (req, res) => { + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); +``` + +### 传统 `authorization server` 模式用法(已弃用) {#legacy-usage-in-authorization-server-mode-deprecated} + +此方式为向后兼容而保留。 + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + server: await fetchServerConfig( + 'https://auth.logto.io/oidc', + { type: 'oidc' } + ), +}); + +// 挂载路由以处理传统授权 (Authorization) 服务器元数据 +app.use(mcpAuth.delegatedRouter()); + +// 使用默认策略保护端点 +app.get( + '/mcp', + mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), + (req, res) => { + console.log('Auth info:', req.auth); + // 在这里处理 MCP 请求 + }, +); +``` + +## 构造函数 {#constructors} + +### 构造函数 {#constructor} + +```ts +new MCPAuth(config: MCPAuthConfig): MCPAuth; +``` + +创建 MCPAuth 的实例。 +它会提前验证整个配置,以便在出错时快速失败。 + +#### 参数 {#parameters} + +##### config {#config} + +[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) + +认证 (Authentication) 配置。 + +#### 返回值 {#returns} + +`MCPAuth` + +## 属性 {#properties} + +### config {#config} + +```ts +readonly config: MCPAuthConfig; +``` + +认证 (Authentication) 配置。 + +## 方法 {#methods} + +### bearerAuth() {#bearerauth} + +#### 调用签名 {#call-signature} + +```ts +bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; +``` + +创建一个 Bearer 认证 (Authentication) 处理器(Express 中间件),用于验证请求中 `Authorization` 头部的访问令牌 (Access token)。 + +##### 参数 {#parameters} + +###### verifyAccessToken {#verifyaccesstoken} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +用于验证访问令牌 (Access token) 的函数。它应接受访问令牌 (Access token) 字符串,并返回一个 promise(或值),解析为验证结果。 + +**参见** + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以获取 `verifyAccessToken` 函数的类型定义。 + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> + +Bearer 认证 (Authentication) 处理器的可选配置。 + +**参见** + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以获取可用的配置选项(不包括 `verifyAccessToken` 和 `issuer`)。 + +##### 返回值 {#returns} + +`RequestHandler` + +一个 Express 中间件函数,用于验证访问令牌 (Access token) 并将验证结果添加到请求对象(`req.auth`)。 + +##### 参见 {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以了解实现细节及 `req.auth`(`AuthInfo`)对象的扩展类型。 + +#### 调用签名 {#call-signature} + +```ts +bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; +``` + +创建一个 Bearer 认证 (Authentication) 处理器(Express 中间件),使用预定义的验证模式验证请求中 `Authorization` 头部的访问令牌 (Access token)。 + +在 `'jwt'` 模式下,处理器将使用授权 (Authorization) 服务器的 JWKS URI 创建 JWT 验证函数。 + +##### 参数 {#parameters} + +###### mode {#mode} + +`"jwt"` + +访问令牌 (Access token) 的验证模式。目前仅支持 'jwt'。 + +**参见** + +[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) 以获取可用模式。 + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` + +Bearer 认证 (Authentication) 处理器的可选配置,包括 JWT 验证选项和远程 JWK set 选项。 + +**参见** + + - VerifyJwtConfig 以获取 JWT 验证的可用配置选项。 + - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以获取可用的配置选项(不包括 `verifyAccessToken` 和 `issuer`)。 + +##### 返回值 {#returns} + +`RequestHandler` + +一个 Express 中间件函数,用于验证访问令牌 (Access token) 并将验证结果添加到请求对象(`req.auth`)。 + +##### 参见 {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以了解实现细节及 `req.auth`(`AuthInfo`)对象的扩展类型。 + +##### 抛出 {#throws} + +当在 `'jwt'` 模式下,服务器元数据未提供 JWKS URI 时抛出。 + +*** + +### ~~delegatedRouter()~~ {#delegatedrouter} + +```ts +delegatedRouter(): Router; +``` + +创建一个用于服务传统 OAuth 2.0 授权 (Authorization) 服务器元数据端点(`/.well-known/oauth-authorization-server`)的委托路由器,使用实例中提供的元数据。 + +#### 返回值 {#returns} + +`Router` + +用于服务 OAuth 2.0 授权 (Authorization) 服务器元数据端点的路由器,使用实例中提供的元数据。 + +#### 已弃用 {#deprecated} + +请改用 [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter)。 + +#### 示例 {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth: MCPAuth; // 假设已初始化 +app.use(mcpAuth.delegatedRouter()); +``` + +#### 抛出 {#throws} + +如果在 `resource server` 模式下调用,则抛出。 + +*** + +### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} + +```ts +protectedResourceMetadataRouter(): Router; +``` + +创建一个路由器,用于为所有已配置资源服务 OAuth 2.0 受保护资源元数据端点。 + +该路由器会根据你配置中提供的每个资源标识符,自动创建正确的 `.well-known` 端点。 + +#### 返回值 {#returns} + +`Router` + +用于服务 OAuth 2.0 受保护资源元数据端点的路由器。 + +#### 抛出 {#throws} + +如果在 `authorization server` 模式下调用,则抛出。 + +#### 示例 {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +// 假设 mcpAuth 已通过一个或多个 `protectedResources` 配置初始化 +const mcpAuth: MCPAuth; +const app = express(); + +// 这将在 `/.well-known/oauth-protected-resource/...` 路径下 +// 根据你的资源标识符提供元数据。 +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md new file mode 100644 index 0000000..73c8302 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md @@ -0,0 +1,237 @@ +--- +sidebar_label: MCPAuthAuthServerError +--- + +# 类:MCPAuthAuthServerError + +当远程授权 (Authorization) 服务器出现问题时抛出的错误。 + +## 继承自 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 构造函数 {#constructors} + +### 构造函数 {#constructor} + +```ts +new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; +``` + +#### 参数 {#parameters} + +##### code {#code} + +[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### 返回 {#returns} + +`MCPAuthAuthServerError` + +#### 重写自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 属性 {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: AuthServerErrorCode; +``` + +错误代码,采用 snake_case 格式。 + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthAuthServerError'; +``` + +#### 重写自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 属性指定堆栈跟踪收集的堆栈帧数量(无论是由 `new Error().stack` 还是 `Error.captureStackTrace(obj)` 生成)。 + +默认值为 `10`,但可以设置为任何有效的 JavaScript 数字。更改后将影响之后捕获的所有堆栈跟踪。 + +如果设置为非数字值,或设置为负数,则堆栈跟踪将不会捕获任何帧。 + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 方法 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +将错误转换为适合 HTTP 响应的 JSON 格式。 + +#### 参数 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +是否在 JSON 响应中包含错误原因。默认为 `false`。 + +#### 返回 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +在 `targetObject` 上创建一个 `.stack` 属性,当访问时返回一个字符串,表示调用 `Error.captureStackTrace()` 时代码中的位置。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // 类似于 `new Error().stack` +``` + +跟踪的第一行将以 `${myObject.name}: ${myObject.message}` 为前缀。 + +可选的 `constructorOpt` 参数接受一个函数。如果提供,则所有高于 `constructorOpt` 的帧(包括 `constructorOpt`)都将从生成的堆栈跟踪中省略。 + +`constructorOpt` 参数用于隐藏错误生成的实现细节。例如: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 创建一个没有堆栈跟踪的错误,以避免重复计算堆栈跟踪。 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 捕获高于函数 b 的堆栈跟踪 + Error.captureStackTrace(error, b); // 堆栈跟踪中既不包含函数 c,也不包含 b + throw error; +} + +a(); +``` + +#### 参数 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 返回 {#returns} + +`void` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 参数 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 返回 {#returns} + +`any` + +#### 参见 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md new file mode 100644 index 0000000..e70b1da --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md @@ -0,0 +1,238 @@ +--- +sidebar_label: MCPAuthBearerAuthError +--- + +# 类:MCPAuthBearerAuthError + +当使用 Bearer 令牌进行认证 (Authentication) 时出现问题时抛出的错误。 + +## 继承自 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 构造函数 {#constructors} + +### 构造函数 {#constructor} + +```ts +new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; +``` + +#### 参数 {#parameters} + +##### code {#code} + +[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) + +##### cause? {#cause} + +[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) + +#### 返回 {#returns} + +`MCPAuthBearerAuthError` + +#### 重写自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 属性 {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: MCPAuthBearerAuthErrorDetails; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: BearerAuthErrorCode; +``` + +错误代码,采用 snake_case 格式。 + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthBearerAuthError'; +``` + +#### 重写自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 属性指定堆栈跟踪收集的堆栈帧数量(无论是由 `new Error().stack` 还是 `Error.captureStackTrace(obj)` 生成)。 + +默认值为 `10`,但可以设置为任何有效的 JavaScript 数字。更改后将影响之后捕获的任何堆栈跟踪。 + +如果设置为非数字值或负数,则堆栈跟踪不会捕获任何帧。 + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 方法 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +将错误转换为适合 HTTP 响应的 JSON 格式。 + +#### 参数 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +是否在 JSON 响应中包含错误原因。 +默认为 `false`。 + +#### 返回 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 重写自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +在 `targetObject` 上创建一个 `.stack` 属性,当访问时返回一个字符串,表示调用 `Error.captureStackTrace()` 时代码中的位置。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // 类似于 `new Error().stack` +``` + +跟踪的第一行将以 `${myObject.name}: ${myObject.message}` 为前缀。 + +可选的 `constructorOpt` 参数接受一个函数。如果提供,则在生成的堆栈跟踪中,将省略 `constructorOpt` 及其以上的所有帧。 + +`constructorOpt` 参数用于隐藏错误生成的实现细节。例如: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 创建一个没有堆栈跟踪的错误,以避免重复计算堆栈跟踪。 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 捕获 function b 以上的堆栈跟踪 + Error.captureStackTrace(error, b); // 堆栈跟踪中不包含 function c 和 b + throw error; +} + +a(); +``` + +#### 参数 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 返回 {#returns} + +`void` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 参数 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 返回 {#returns} + +`any` + +#### 参见 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md new file mode 100644 index 0000000..f258636 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md @@ -0,0 +1,241 @@ +--- +sidebar_label: MCPAuthConfigError +--- + +# 类:MCPAuthConfigError + +当 mcp-auth 配置出现问题时抛出的错误。 + +## 继承自 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 构造函数 {#constructors} + +### 构造函数 {#constructor} + +```ts +new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; +``` + +#### 参数 {#parameters} + +##### code {#code} + +`string` + +以 snake_case 格式表示的错误代码。 + +##### message {#message} + +`string` + +对错误的人类可读描述。 + +#### 返回 {#returns} + +`MCPAuthConfigError` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 属性 {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +以 snake_case 格式表示的错误代码。 + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthConfigError'; +``` + +#### 重写自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 属性指定堆栈跟踪收集的堆栈帧数量(无论是由 `new Error().stack` 还是 `Error.captureStackTrace(obj)` 生成)。 + +默认值为 `10`,但可以设置为任何有效的 JavaScript 数字。更改后将影响之后捕获的所有堆栈跟踪。 + +如果设置为非数字值或负数,则堆栈跟踪不会捕获任何帧。 + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 方法 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +将错误转换为适合 HTTP 响应的 JSON 格式。 + +#### 参数 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +是否在 JSON 响应中包含错误原因。默认为 `false`。 + +#### 返回 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +在 `targetObject` 上创建一个 `.stack` 属性,当访问时返回一个字符串,表示调用 `Error.captureStackTrace()` 时代码中的位置。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // 类似于 `new Error().stack` +``` + +跟踪的第一行将以 `${myObject.name}: ${myObject.message}` 为前缀。 + +可选的 `constructorOpt` 参数接受一个函数。如果提供,所有在 `constructorOpt` 之上的帧(包括 `constructorOpt`)都将从生成的堆栈跟踪中省略。 + +`constructorOpt` 参数用于隐藏错误生成的实现细节。例如: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 创建一个没有堆栈跟踪的错误,以避免重复计算堆栈跟踪。 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 捕获 function b 之上的堆栈跟踪 + Error.captureStackTrace(error, b); // 堆栈跟踪中不包含 function c 和 b + throw error; +} + +a(); +``` + +#### 参数 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 返回 {#returns} + +`void` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 参数 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 返回 {#returns} + +`any` + +#### 参考 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md new file mode 100644 index 0000000..ec40f17 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md @@ -0,0 +1,258 @@ +--- +sidebar_label: MCPAuthError +--- + +# 类:MCPAuthError + +所有 mcp-auth 错误的基类。 + +它为处理与 MCP 认证 (Authentication) 和授权 (Authorization) 相关的错误提供了标准化方式。 + +## 继承自 {#extends} + +- `Error` + +## 被以下类继承 {#extended-by} + +- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) +- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) +- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) +- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) + +## 构造函数 {#constructors} + +### 构造函数 {#constructor} + +```ts +new MCPAuthError(code: string, message: string): MCPAuthError; +``` + +#### 参数 {#parameters} + +##### code {#code} + +`string` + +错误代码,采用 snake_case 格式。 + +##### message {#message} + +`string` + +对错误的人类可读描述。 + +#### 返回 {#returns} + +`MCPAuthError` + +#### 重写自 {#overrides} + +```ts +Error.constructor +``` + +## 属性 {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### 继承自 {#inherited-from} + +```ts +Error.cause +``` + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +错误代码,采用 snake_case 格式。 + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 继承自 {#inherited-from} + +```ts +Error.message +``` + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthError'; +``` + +#### 重写自 {#overrides} + +```ts +Error.name +``` + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 继承自 {#inherited-from} + +```ts +Error.stack +``` + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 属性指定堆栈跟踪收集的堆栈帧数量(无论是由 `new Error().stack` 还是 `Error.captureStackTrace(obj)` 生成)。 + +默认值为 `10`,但可以设置为任何有效的 JavaScript 数字。更改后将影响之后捕获的所有堆栈跟踪。 + +如果设置为非数字值,或设置为负数,则堆栈跟踪不会捕获任何帧。 + +#### 继承自 {#inherited-from} + +```ts +Error.stackTraceLimit +``` + +## 方法 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +将错误转换为适合 HTTP 响应的 JSON 格式。 + +#### 参数 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +是否在 JSON 响应中包含错误原因。默认为 `false`。 + +#### 返回 {#returns} + +`Record`\<`string`, `unknown`\> + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +在 `targetObject` 上创建一个 `.stack` 属性,当访问时返回一个字符串,表示调用 `Error.captureStackTrace()` 时代码中的位置。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // 类似于 `new Error().stack` +``` + +跟踪的第一行将以 `${myObject.name}: ${myObject.message}` 为前缀。 + +可选的 `constructorOpt` 参数接受一个函数。如果提供,则生成的堆栈跟踪中将省略 `constructorOpt` 及其以上的所有帧。 + +`constructorOpt` 参数用于隐藏错误生成的实现细节。例如: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 创建一个没有堆栈跟踪的错误以避免重复计算堆栈。 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 捕获 b 以上的堆栈跟踪 + Error.captureStackTrace(error, b); // 堆栈跟踪中不包含 c 和 b + throw error; +} + +a(); +``` + +#### 参数 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 返回 {#returns} + +`void` + +#### 继承自 {#inherited-from} + +```ts +Error.captureStackTrace +``` + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 参数 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 返回 {#returns} + +`any` + +#### 参考 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 继承自 {#inherited-from} + +```ts +Error.prepareStackTrace +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md new file mode 100644 index 0000000..4897dea --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md @@ -0,0 +1,238 @@ +--- +sidebar_label: MCPAuthTokenVerificationError +--- + +# 类:MCPAuthTokenVerificationError + +在验证令牌时出现问题时抛出的错误。 + +## 继承自 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 构造函数 {#constructors} + +### 构造函数 {#constructor} + +```ts +new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; +``` + +#### 参数 {#parameters} + +##### code {#code} + +[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### 返回 {#returns} + +`MCPAuthTokenVerificationError` + +#### 重写自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 属性 {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: MCPAuthTokenVerificationErrorCode; +``` + +错误代码,采用 snake_case 格式。 + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthTokenVerificationError'; +``` + +#### 重写自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 属性指定堆栈跟踪收集的堆栈帧数量(无论是由 `new Error().stack` 还是 `Error.captureStackTrace(obj)` 生成)。 + +默认值为 `10`,但可以设置为任何有效的 JavaScript 数字。更改后将影响之后捕获的所有堆栈跟踪。 + +如果设置为非数字值,或设置为负数,则堆栈跟踪不会捕获任何帧。 + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 方法 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +将错误转换为适合 HTTP 响应的 JSON 格式。 + +#### 参数 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +是否在 JSON 响应中包含错误原因。 +默认为 `false`。 + +#### 返回 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +在 `targetObject` 上创建一个 `.stack` 属性,当访问时返回一个字符串,表示调用 `Error.captureStackTrace()` 时在代码中的位置。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // 类似于 `new Error().stack` +``` + +跟踪的第一行将以 `${myObject.name}: ${myObject.message}` 为前缀。 + +可选的 `constructorOpt` 参数接受一个函数。如果提供,则在生成的堆栈跟踪中,`constructorOpt` 及其以上的所有帧都将被省略。 + +`constructorOpt` 参数对于隐藏错误生成的实现细节很有用。例如: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 创建一个没有堆栈跟踪的错误,以避免重复计算堆栈跟踪。 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 捕获 b 函数以上的堆栈跟踪 + Error.captureStackTrace(error, b); // 堆栈跟踪中不包含 c 和 b 函数 + throw error; +} + +a(); +``` + +#### 参数 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 返回 {#returns} + +`void` + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 参数 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 返回 {#returns} + +`any` + +#### 参见 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 继承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md new file mode 100644 index 0000000..69a9a84 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md @@ -0,0 +1,43 @@ +--- +sidebar_label: createVerifyJwt +--- + +# 函数:createVerifyJwt() + +```ts +function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; +``` + +使用提供的密钥获取函数和选项,创建一个用于验证 JWT 访问令牌 (Access token) 的函数。 + +## 参数 {#parameters} + +### getKey {#getkey} + +`JWTVerifyGetKey` + +用于获取验证 JWT 所需密钥的函数。 + +**参见** + +JWTVerifyGetKey,了解密钥获取函数的类型定义。 + +### options? {#options} + +`JWTVerifyOptions` + +可选的 JWT 验证选项。 + +**参见** + +JWTVerifyOptions,了解选项的类型定义。 + +## 返回值 {#returns} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +一个用于验证 JWT 访问令牌 (Access token) 的函数,如果令牌有效,则返回一个 AuthInfo 对象。该函数要求 JWT 的 payload 中包含 `iss`、`client_id` 和 `sub` 字段,并且可以选择包含 `scope` 或 `scopes` 字段。该函数底层使用 `jose` 库进行 JWT 验证。 + +## 参见 {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md),了解返回函数的类型定义。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md new file mode 100644 index 0000000..5cf1460 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md @@ -0,0 +1,60 @@ +--- +sidebar_label: fetchServerConfig +--- + +# 函数:fetchServerConfig() + +```ts +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +``` + +根据发行者 (Issuer) 和授权 (Authorization) 服务器类型获取服务器配置。 + +此函数会根据服务器类型自动确定 well-known URL,因为 OAuth 和 OpenID Connect 服务器在其元数据端点上有不同的约定。 + +## 参数 {#parameters} + +### issuer {#issuer} + +`string` + +授权 (Authorization) 服务器的发行者 (Issuer) URL。 + +### config {#config} + +`ServerMetadataConfig` + +包含服务器类型和可选转译函数的配置对象。 + +## 返回值 {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +一个解析为服务器配置的 Promise。 + +## 参见 {#see} + + - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) 了解底层实现。 + - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) 查看 OAuth 2.0 授权 (Authorization) 服务器元数据规范。 + - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) 查看 OpenID Connect 发现规范。 + +## 示例 {#example} + +```ts +import { fetchServerConfig } from 'mcp-auth'; +// 获取 OAuth 服务器配置 +// 这将从 `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` 获取元数据 +const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); + +// 获取 OpenID Connect 服务器配置 +// 这将从 `https://auth.logto.io/oidc/.well-known/openid-configuration` 获取元数据 +const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); +``` + +## 抛出异常 {#throws} + +如果获取操作失败。 + +## 抛出异常 {#throws} + +如果服务器元数据无效或不符合 MCP 规范。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md new file mode 100644 index 0000000..6bdbc00 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md @@ -0,0 +1,41 @@ +--- +sidebar_label: fetchServerConfigByWellKnownUrl +--- + +# 函数:fetchServerConfigByWellKnownUrl() + +```ts +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +``` + +从提供的 well-known URL 获取服务器配置,并根据 MCP 规范进行校验。 + +如果服务器元数据不符合预期的 schema,但你确定它是兼容的,你可以定义一个 `transpileData` 函数,将元数据转换为预期格式。 + +## 参数 {#parameters} + +### wellKnownUrl {#wellknownurl} + +用于获取服务器配置的 well-known URL。可以是字符串或 URL 对象。 + +`string` | `URL` + +### config {#config} + +`ServerMetadataConfig` + +包含服务器类型和可选 transpile 函数的配置对象。 + +## 返回值 {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +一个解析为服务器配置的 Promise。 + +## 抛出异常 {#throws} + +如果获取操作失败,则抛出异常。 + +## 抛出异常 {#throws} + +如果服务器元数据无效或不符合 MCP 规范,则抛出异常。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md new file mode 100644 index 0000000..a2c3753 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md @@ -0,0 +1,39 @@ +--- +sidebar_label: handleBearerAuth +--- + +# 函数:handleBearerAuth() + +```ts +function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; +``` + +在 Express 应用中创建用于处理 Bearer 认证 (Authentication) 的中间件函数。 + +该中间件会从 `Authorization` 头中提取 Bearer 令牌,使用提供的 `verifyAccessToken` 函数进行验证,并检查发行者 (Issuer)、受众 (Audience) 和所需权限 (Scopes)。 + +- 如果令牌有效,会将认证 (Authentication) 信息添加到 `request.auth` 属性中; + 如果无效,则返回相应的错误信息。 +- 如果访问令牌 (Access token) 验证失败,则返回 401 未授权错误。 +- 如果令牌不包含所需的权限 (Scopes),则返回 403 禁止访问错误。 +- 如果在认证 (Authentication) 过程中发生意外错误,中间件会重新抛出这些错误。 + +**注意:** `request.auth` 对象将包含比 `@modelcontextprotocol/sdk` 模块中定义的标准 AuthInfo 接口更多的扩展字段。详情请参见本文件中的扩展接口。 + +## 参数 {#parameters} + +### param0 {#param0} + +[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) + +Bearer 认证 (Authentication) 处理器的配置。 + +## 返回值 {#returns} + +`RequestHandler` + +用于 Express 的 Bearer 认证 (Authentication) 中间件函数。 + +## 参见 {#see} + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以获取配置选项。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md new file mode 100644 index 0000000..61f9c4c --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md @@ -0,0 +1,48 @@ +--- +sidebar_label: AuthServerConfig +--- + +# 类型别名:AuthServerConfig + +```ts +type AuthServerConfig = { + metadata: CamelCaseAuthorizationServerMetadata; + type: AuthServerType; +}; +``` + +与 MCP 服务器集成的远程授权服务器 (Authorization Server) 的配置。 + +## 属性 {#properties} + +### metadata {#metadata} + +```ts +metadata: CamelCaseAuthorizationServerMetadata; +``` + +授权服务器 (Authorization Server) 的元数据,需符合 MCP 规范 +(基于 OAuth 2.0 授权服务器元数据 (Authorization Server Metadata))。 + +该元数据通常从服务器的 well-known 端点(OAuth 2.0 授权服务器元数据 (Authorization Server Metadata) 或 OpenID Connect Discovery)获取;如果服务器不支持这些端点,也可以直接在配置中提供。 + +**注意:** 元数据应采用 camelCase 格式,这是 mcp-auth 库推荐的格式。 + +#### 参见 {#see} + + - [OAuth 2.0 授权服务器元数据 (Authorization Server Metadata)](https://datatracker.ietf.org/doc/html/rfc8414) + - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +*** + +### type {#type} + +```ts +type: AuthServerType; +``` + +授权服务器 (Authorization Server) 的类型。 + +#### 参见 {#see} + +[AuthServerType](/references/js/type-aliases/AuthServerType.md) 以获取可能的取值。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md new file mode 100644 index 0000000..f442d8f --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md @@ -0,0 +1,45 @@ +--- +sidebar_label: AuthServerConfigError +--- + +# 类型别名:AuthServerConfigError + +```ts +type AuthServerConfigError = { + cause?: Error; + code: AuthServerConfigErrorCode; + description: string; +}; +``` + +表示在验证授权服务器元数据时发生的错误。 + +## 属性 {#properties} + +### cause? {#cause} + +```ts +optional cause: Error; +``` + +错误的可选原因,通常是一个 `Error` 实例,用于提供更多上下文信息。 + +*** + +### code {#code} + +```ts +code: AuthServerConfigErrorCode; +``` + +表示具体验证错误的代码。 + +*** + +### description {#description} + +```ts +description: string; +``` + +对错误的人类可读描述。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md new file mode 100644 index 0000000..a5b9d02 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: AuthServerConfigErrorCode +--- + +# 类型别名:AuthServerConfigErrorCode + +```ts +type AuthServerConfigErrorCode = + | "invalid_server_metadata" + | "code_response_type_not_supported" + | "authorization_code_grant_not_supported" + | "pkce_not_supported" + | "s256_code_challenge_method_not_supported"; +``` + +在验证授权服务器元数据时可能出现的错误代码。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md new file mode 100644 index 0000000..a73ff3c --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md @@ -0,0 +1,34 @@ +--- +sidebar_label: AuthServerConfigWarning +--- + +# 类型别名:AuthServerConfigWarning + +```ts +type AuthServerConfigWarning = { + code: AuthServerConfigWarningCode; + description: string; +}; +``` + +表示在验证授权服务器元数据期间发生的警告。 + +## 属性 {#properties} + +### code {#code} + +```ts +code: AuthServerConfigWarningCode; +``` + +表示特定验证警告的代码。 + +*** + +### description {#description} + +```ts +description: string; +``` + +对警告的人类可读描述。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md new file mode 100644 index 0000000..2f51a52 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerConfigWarningCode +--- + +# 类型别名:AuthServerConfigWarningCode + +```ts +type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; +``` + +在验证授权服务器元数据时可能出现的警告代码。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md new file mode 100644 index 0000000..f285c5a --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md @@ -0,0 +1,12 @@ +--- +sidebar_label: AuthServerErrorCode +--- + +# 类型别名:AuthServerErrorCode + +```ts +type AuthServerErrorCode = + | "invalid_server_metadata" + | "invalid_server_config" + | "missing_jwks_uri"; +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md new file mode 100644 index 0000000..aa8fd5c --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md @@ -0,0 +1,31 @@ +--- +sidebar_label: AuthServerModeConfig +--- + +# 类型别名:~~AuthServerModeConfig~~ + +```ts +type AuthServerModeConfig = { + server: AuthServerConfig; +}; +``` + +用于传统 MCP 服务器作为授权服务器模式的配置。 + +## 已废弃 {#deprecated} + +请改用 `ResourceServerModeConfig` 配置。 + +## 属性 {#properties} + +### ~~server~~ {#server} + +```ts +server: AuthServerConfig; +``` + +单一授权服务器配置。 + +#### 已废弃 {#deprecated} + +请改用 `protectedResources` 配置。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md new file mode 100644 index 0000000..18fcf46 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md @@ -0,0 +1,17 @@ +--- +sidebar_label: AuthServerSuccessCode +--- + +# 类型别名:AuthServerSuccessCode + +```ts +type AuthServerSuccessCode = + | "server_metadata_valid" + | "dynamic_registration_supported" + | "pkce_supported" + | "s256_code_challenge_method_supported" + | "authorization_code_grant_supported" + | "code_response_type_supported"; +``` + +用于授权服务器元数据验证成功的代码。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md new file mode 100644 index 0000000..0e4748a --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerType +--- + +# 类型别名:AuthServerType + +```ts +type AuthServerType = "oauth" | "oidc"; +``` + +授权 (Authorization) 服务器的类型。此信息应由服务器配置提供,并指示该服务器是 OAuth 2.0 还是 OpenID Connect (OIDC) 授权 (Authorization) 服务器。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md new file mode 100644 index 0000000..3d7b45f --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md @@ -0,0 +1,223 @@ +--- +sidebar_label: AuthorizationServerMetadata +--- + +# 类型别名:AuthorizationServerMetadata + +```ts +type AuthorizationServerMetadata = { + authorization_endpoint: string; + code_challenge_methods_supported?: string[]; + grant_types_supported?: string[]; + introspection_endpoint?: string; + introspection_endpoint_auth_methods_supported?: string[]; + introspection_endpoint_auth_signing_alg_values_supported?: string[]; + issuer: string; + jwks_uri?: string; + op_policy_uri?: string; + op_tos_uri?: string; + registration_endpoint?: string; + response_modes_supported?: string[]; + response_types_supported: string[]; + revocation_endpoint?: string; + revocation_endpoint_auth_methods_supported?: string[]; + revocation_endpoint_auth_signing_alg_values_supported?: string[]; + scopes_supported?: string[]; + service_documentation?: string; + token_endpoint: string; + token_endpoint_auth_methods_supported?: string[]; + token_endpoint_auth_signing_alg_values_supported?: string[]; + ui_locales_supported?: string[]; + userinfo_endpoint?: string; +}; +``` + +OAuth 2.0 授权服务器元数据(Authorization Server Metadata)的模式,定义见 RFC 8414。 + +## 类型声明 {#type-declaration} + +### authorization\_endpoint {#authorization-endpoint} + +```ts +authorization_endpoint: string; +``` + +授权服务器的授权端点(authorization endpoint)的 URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 +除非不支持任何使用授权端点的授权类型,否则这是必需的。 + +#### 参考 {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.1 + +### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} + +```ts +optional code_challenge_methods_supported: string[]; +``` + +包含此授权服务器支持的 Proof Key for Code Exchange (PKCE) [[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] code challenge 方法列表的 JSON 数组。 + +### grant\_types\_supported? {#grant-types-supported} + +```ts +optional grant_types_supported: string[]; +``` + +包含此授权服务器支持的 OAuth 2.0 授权类型(grant type)值列表的 JSON 数组。数组中的值与 "OAuth 2.0 动态客户端注册协议" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] 中 `grant_types` 参数使用的值相同。 +如果省略,默认值为 `["authorization_code", "implicit"]`。 + +### introspection\_endpoint? {#introspection-endpoint} + +```ts +optional introspection_endpoint: string; +``` + +授权服务器的 OAuth 2.0 introspection 端点的 URL [[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]。 + +### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} + +```ts +optional introspection_endpoint_auth_methods_supported: string[]; +``` + +### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} + +```ts +optional introspection_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +授权服务器的发行者 (Issuer) 标识符,是一个使用 `https` 协议且没有查询或片段组件的 URL。 + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +授权服务器的 JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] 文档的 URL。被引用的文档包含客户端用于验证授权服务器签名的密钥。此 URL 必须使用 `https` 协议。 + +### op\_policy\_uri? {#op-policy-uri} + +```ts +optional op_policy_uri: string; +``` + +### op\_tos\_uri? {#op-tos-uri} + +```ts +optional op_tos_uri: string; +``` + +### registration\_endpoint? {#registration-endpoint} + +```ts +optional registration_endpoint: string; +``` + +授权服务器的 OAuth 2.0 动态客户端注册端点的 URL [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]。 + +### response\_modes\_supported? {#response-modes-supported} + +```ts +optional response_modes_supported: string[]; +``` + +包含此授权服务器支持的 OAuth 2.0 `response_mode` 值列表的 JSON 数组,详见 "OAuth 2.0 多响应类型编码实践" +[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]。 + +如果省略,默认值为 `["query", "fragment"]`。响应模式值 `"form_post"` 也在 "OAuth 2.0 表单提交响应模式" +[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)] 中定义。 + +### response\_types\_supported {#response-types-supported} + +```ts +response_types_supported: string[]; +``` + +包含此授权服务器支持的 OAuth 2.0 `response_type` 值列表的 JSON 数组。数组中的值与 "OAuth 2.0 动态客户端注册协议" +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] 中 `response_types` 参数使用的值相同。 + +### revocation\_endpoint? {#revocation-endpoint} + +```ts +optional revocation_endpoint: string; +``` + +授权服务器的 OAuth 2.0 撤销端点(revocation endpoint)的 URL [[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]。 + +### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} + +```ts +optional revocation_endpoint_auth_methods_supported: string[]; +``` + +### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} + +```ts +optional revocation_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +包含此授权服务器支持的 OAuth 2.0 `scope` 值列表的 JSON 数组。 +[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] + +### service\_documentation? {#service-documentation} + +```ts +optional service_documentation: string; +``` + +### token\_endpoint {#token-endpoint} + +```ts +token_endpoint: string; +``` + +授权服务器的令牌端点(token endpoint)的 URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 +除非只支持 implicit 授权类型,否则这是必需的。 + +#### 参考 {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.2 + +### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} + +```ts +optional token_endpoint_auth_methods_supported: string[]; +``` + +### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} + +```ts +optional token_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### ui\_locales\_supported? {#ui-locales-supported} + +```ts +optional ui_locales_supported: string[]; +``` + +### userinfo\_endpoint? {#userinfo-endpoint} + +```ts +optional userinfo_endpoint: string; +``` + +OpenID Connect [userinfo 端点](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) 的 URL。 +该端点用于获取已认证用户的信息。 + +## 参考 {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md new file mode 100644 index 0000000..f0308cd --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md @@ -0,0 +1,107 @@ +--- +sidebar_label: BearerAuthConfig +--- + +# 类型别名:BearerAuthConfig + +```ts +type BearerAuthConfig = { + audience?: string; + issuer: | string + | ValidateIssuerFunction; + requiredScopes?: string[]; + resource?: string; + showErrorDetails?: boolean; + verifyAccessToken: VerifyAccessTokenFunction; +}; +``` + +## 属性 {#properties} + +### audience? {#audience} + +```ts +optional audience: string; +``` + +访问令牌 (Access token) 的预期受众 (Audience)(`aud` 声明 (Claim))。这通常是令牌所针对的资源服务器(API)。如果未提供,将跳过受众 (Audience) 检查。 + +**注意:** 如果你的授权服务器 (Authorization server) 不支持资源指示器 (Resource Indicators)(RFC 8707),你可以省略此字段,因为受众 (Audience) 可能并不相关。 + +#### 参见 {#see} + +https://datatracker.ietf.org/doc/html/rfc8707 + +*** + +### issuer {#issuer} + +```ts +issuer: + | string + | ValidateIssuerFunction; +``` + +表示有效发行者 (Issuer) 的字符串,或用于验证访问令牌 (Access token) 发行者 (Issuer) 的函数。 + +如果提供字符串,则将其用作预期的发行者 (Issuer) 值进行直接比较。 + +如果提供函数,则应根据 [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 中的规则验证发行者 (Issuer)。 + +#### 参见 {#see} + +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 了解有关验证函数的更多细节。 + +*** + +### requiredScopes? {#requiredscopes} + +```ts +optional requiredScopes: string[]; +``` + +访问令牌 (Access token) 必须包含的权限 (Scopes) 数组。如果令牌未包含所有这些权限 (Scopes),将抛出错误。 + +**注意:** 处理器将检查令牌中的 `scope` 声明 (Claim),该声明 (Claim) 可能是以空格分隔的字符串或字符串数组,具体取决于授权服务器 (Authorization server) 的实现。如果未包含 `scope` 声明 (Claim),处理器将检查 `scopes` 声明 (Claim)(如果可用)。 + +*** + +### resource? {#resource} + +```ts +optional resource: string; +``` + +受保护资源的标识符。当提供该字段时,处理器将使用为此资源配置的授权服务器 (Authorization server) 验证收到的令牌。在使用带有 `protectedResources` 配置的处理器时是必需的。 + +*** + +### showErrorDetails? {#showerrordetails} + +```ts +optional showErrorDetails: boolean; +``` + +是否在响应中显示详细的错误信息。这对于开发期间调试很有用,但在生产环境中应禁用,以避免泄露敏感信息。 + +#### 默认值 {#default} + +```ts +false +``` + +*** + +### verifyAccessToken {#verifyaccesstoken} + +```ts +verifyAccessToken: VerifyAccessTokenFunction; +``` + +用于验证访问令牌 (Access token) 的函数类型。 + +如果令牌无效,此函数应抛出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md);如果令牌有效,则返回 AuthInfo 对象。 + +#### 参见 {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 了解更多细节。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md new file mode 100644 index 0000000..becf5bb --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: BearerAuthErrorCode +--- + +# 类型别名:BearerAuthErrorCode + +```ts +type BearerAuthErrorCode = + | "missing_auth_header" + | "invalid_auth_header_format" + | "missing_bearer_token" + | "invalid_issuer" + | "invalid_audience" + | "missing_required_scopes" + | "invalid_token"; +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md new file mode 100644 index 0000000..21dee17 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md @@ -0,0 +1,179 @@ +--- +sidebar_label: CamelCaseAuthorizationServerMetadata +--- + +# 类型别名:CamelCaseAuthorizationServerMetadata + +```ts +type CamelCaseAuthorizationServerMetadata = { + authorizationEndpoint: string; + codeChallengeMethodsSupported?: string[]; + grantTypesSupported?: string[]; + introspectionEndpoint?: string; + introspectionEndpointAuthMethodsSupported?: string[]; + introspectionEndpointAuthSigningAlgValuesSupported?: string[]; + issuer: string; + jwksUri?: string; + opPolicyUri?: string; + opTosUri?: string; + registrationEndpoint?: string; + responseModesSupported?: string[]; + responseTypesSupported: string[]; + revocationEndpoint?: string; + revocationEndpointAuthMethodsSupported?: string[]; + revocationEndpointAuthSigningAlgValuesSupported?: string[]; + scopesSupported?: string[]; + serviceDocumentation?: string; + tokenEndpoint: string; + tokenEndpointAuthMethodsSupported?: string[]; + tokenEndpointAuthSigningAlgValuesSupported?: string[]; + uiLocalesSupported?: string[]; + userinfoEndpoint?: string; +}; +``` + +OAuth 2.0 授权服务器元数据类型的 camelCase 版本。 + +## 类型声明 {#type-declaration} + +### authorizationEndpoint {#authorizationendpoint} + +```ts +authorizationEndpoint: string; +``` + +### codeChallengeMethodsSupported? {#codechallengemethodssupported} + +```ts +optional codeChallengeMethodsSupported: string[]; +``` + +### grantTypesSupported? {#granttypessupported} + +```ts +optional grantTypesSupported: string[]; +``` + +### introspectionEndpoint? {#introspectionendpoint} + +```ts +optional introspectionEndpoint: string; +``` + +### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} + +```ts +optional introspectionEndpointAuthMethodsSupported: string[]; +``` + +### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} + +```ts +optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### opPolicyUri? {#oppolicyuri} + +```ts +optional opPolicyUri: string; +``` + +### opTosUri? {#optosuri} + +```ts +optional opTosUri: string; +``` + +### registrationEndpoint? {#registrationendpoint} + +```ts +optional registrationEndpoint: string; +``` + +### responseModesSupported? {#responsemodessupported} + +```ts +optional responseModesSupported: string[]; +``` + +### responseTypesSupported {#responsetypessupported} + +```ts +responseTypesSupported: string[]; +``` + +### revocationEndpoint? {#revocationendpoint} + +```ts +optional revocationEndpoint: string; +``` + +### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} + +```ts +optional revocationEndpointAuthMethodsSupported: string[]; +``` + +### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} + +```ts +optional revocationEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### serviceDocumentation? {#servicedocumentation} + +```ts +optional serviceDocumentation: string; +``` + +### tokenEndpoint {#tokenendpoint} + +```ts +tokenEndpoint: string; +``` + +### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} + +```ts +optional tokenEndpointAuthMethodsSupported: string[]; +``` + +### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} + +```ts +optional tokenEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### uiLocalesSupported? {#uilocalessupported} + +```ts +optional uiLocalesSupported: string[]; +``` + +### userinfoEndpoint? {#userinfoendpoint} + +```ts +optional userinfoEndpoint: string; +``` + +## 参见 {#see} + +[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) 以获取原始类型和字段信息。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md new file mode 100644 index 0000000..dfcb8ea --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md @@ -0,0 +1,123 @@ +--- +sidebar_label: CamelCaseProtectedResourceMetadata +--- + +# 类型别名:CamelCaseProtectedResourceMetadata + +```ts +type CamelCaseProtectedResourceMetadata = { + authorizationDetailsTypesSupported?: string[]; + authorizationServers?: string[]; + bearerMethodsSupported?: string[]; + dpopBoundAccessTokensRequired?: boolean; + dpopSigningAlgValuesSupported?: string[]; + jwksUri?: string; + resource: string; + resourceDocumentation?: string; + resourceName?: string; + resourcePolicyUri?: string; + resourceSigningAlgValuesSupported?: string[]; + resourceTosUri?: string; + scopesSupported?: string[]; + signedMetadata?: string; + tlsClientCertificateBoundAccessTokens?: boolean; +}; +``` + +OAuth 2.0 Protected Resource Metadata 类型的 camelCase 版本。 + +## 类型声明 {#type-declaration} + +### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} + +```ts +optional authorizationDetailsTypesSupported: string[]; +``` + +### authorizationServers? {#authorizationservers} + +```ts +optional authorizationServers: string[]; +``` + +### bearerMethodsSupported? {#bearermethodssupported} + +```ts +optional bearerMethodsSupported: string[]; +``` + +### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} + +```ts +optional dpopBoundAccessTokensRequired: boolean; +``` + +### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} + +```ts +optional dpopSigningAlgValuesSupported: string[]; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### resource {#resource} + +```ts +resource: string; +``` + +### resourceDocumentation? {#resourcedocumentation} + +```ts +optional resourceDocumentation: string; +``` + +### resourceName? {#resourcename} + +```ts +optional resourceName: string; +``` + +### resourcePolicyUri? {#resourcepolicyuri} + +```ts +optional resourcePolicyUri: string; +``` + +### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} + +```ts +optional resourceSigningAlgValuesSupported: string[]; +``` + +### resourceTosUri? {#resourcetosuri} + +```ts +optional resourceTosUri: string; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### signedMetadata? {#signedmetadata} + +```ts +optional signedMetadata: string; +``` + +### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} + +```ts +optional tlsClientCertificateBoundAccessTokens: boolean; +``` + +## 参见 {#see} + +[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) 以获取原始类型和字段信息。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md new file mode 100644 index 0000000..c29c7f4 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md @@ -0,0 +1,55 @@ +--- +sidebar_label: MCPAuthBearerAuthErrorDetails +--- + +# 类型别名:MCPAuthBearerAuthErrorDetails + +```ts +type MCPAuthBearerAuthErrorDetails = { + actual?: unknown; + cause?: unknown; + expected?: unknown; + missingScopes?: string[]; + uri?: URL; +}; +``` + +## 属性 {#properties} + +### actual? {#actual} + +```ts +optional actual: unknown; +``` + +*** + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +*** + +### expected? {#expected} + +```ts +optional expected: unknown; +``` + +*** + +### missingScopes? {#missingscopes} + +```ts +optional missingScopes: string[]; +``` + +*** + +### uri? {#uri} + +```ts +optional uri: URL; +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md new file mode 100644 index 0000000..dfe0b52 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md @@ -0,0 +1,13 @@ +--- +sidebar_label: MCPAuthConfig +--- + +# 类型别名:MCPAuthConfig + +```ts +type MCPAuthConfig = + | AuthServerModeConfig + | ResourceServerModeConfig; +``` + +用于 [MCPAuth](/references/js/classes/MCPAuth.md) 类的配置,支持单一传统 `authorization server` 或 `resource server` 配置。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md new file mode 100644 index 0000000..6daa15a --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md @@ -0,0 +1,9 @@ +--- +sidebar_label: MCPAuthTokenVerificationErrorCode +--- + +# 类型别名:MCPAuthTokenVerificationErrorCode + +```ts +type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md new file mode 100644 index 0000000..ba8c708 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md @@ -0,0 +1,150 @@ +--- +sidebar_label: ProtectedResourceMetadata +--- + +# 类型别名:ProtectedResourceMetadata + +```ts +type ProtectedResourceMetadata = { + authorization_details_types_supported?: string[]; + authorization_servers?: string[]; + bearer_methods_supported?: string[]; + dpop_bound_access_tokens_required?: boolean; + dpop_signing_alg_values_supported?: string[]; + jwks_uri?: string; + resource: string; + resource_documentation?: string; + resource_name?: string; + resource_policy_uri?: string; + resource_signing_alg_values_supported?: string[]; + resource_tos_uri?: string; + scopes_supported?: string[]; + signed_metadata?: string; + tls_client_certificate_bound_access_tokens?: boolean; +}; +``` + +OAuth 2.0 受保护资源元数据的模式定义。 + +## 类型声明 {#type-declaration} + +### authorization\_details\_types\_supported? {#authorization-details-types-supported} + +```ts +optional authorization_details_types_supported: string[]; +``` + +在使用 authorization_details 请求参数时支持的授权详情类型值。 + +### authorization\_servers? {#authorization-servers} + +```ts +optional authorization_servers: string[]; +``` + +可与此受保护资源一起使用的 OAuth 授权 (Authorization) 服务器发行者标识符列表。 + +### bearer\_methods\_supported? {#bearer-methods-supported} + +```ts +optional bearer_methods_supported: string[]; +``` + +支持的 OAuth 2.0 持有者令牌发送方式。可选值:["header", "body", "query"]。 + +### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} + +```ts +optional dpop_bound_access_tokens_required: boolean; +``` + +该受保护资源是否始终要求 DPoP 绑定访问令牌 (Access token)。 + +### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} + +```ts +optional dpop_signing_alg_values_supported: string[]; +``` + +用于验证 DPoP 证明 JWT 的 JWS 算法。 + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +受保护资源的 JSON Web Key (JWK) 集合文档的 URL。该文档包含可用于验证该受保护资源返回的响应或数据数字签名的公钥。 +这与授权 (Authorization) 服务器的 jwks_uri 不同,后者用于令牌验证。当受保护资源对其响应进行签名时,客户端可以获取这些公钥以验证接收数据的真实性和完整性。 + +### resource {#resource} + +```ts +resource: string; +``` + +受保护资源的资源标识符。 + +### resource\_documentation? {#resource-documentation} + +```ts +optional resource_documentation: string; +``` + +包含用于开发者使用该受保护资源的文档的 URL。 + +### resource\_name? {#resource-name} + +```ts +optional resource_name: string; +``` + +用于展示给终端用户的受保护资源的人类可读名称。 + +### resource\_policy\_uri? {#resource-policy-uri} + +```ts +optional resource_policy_uri: string; +``` + +包含受保护资源数据使用要求信息的 URL。 + +### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} + +```ts +optional resource_signing_alg_values_supported: string[]; +``` + +受保护资源用于对资源响应进行签名所支持的 JWS 签名算法。 + +### resource\_tos\_uri? {#resource-tos-uri} + +```ts +optional resource_tos_uri: string; +``` + +包含受保护资源服务条款的 URL。 + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +在授权 (Authorization) 请求中用于访问该受保护资源的权限 (Scope) 值列表。 + +### signed\_metadata? {#signed-metadata} + +```ts +optional signed_metadata: string; +``` + +包含元数据参数作为声明 (Claim) 的已签名 JWT。该 JWT 必须使用 JWS 签名,并包含 'iss' 声明 (Claim)。此字段提供了一种加密方式来验证元数据本身的真实性。签名可通过 `jwks_uri` 端点提供的公钥进行验证。当存在时,该已签名元数据中的值优先于本元数据文档中对应的普通 JSON 值。这有助于防止资源元数据被篡改。 + +### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} + +```ts +optional tls_client_certificate_bound_access_tokens: boolean; +``` + +该受保护资源是否支持基于双向 TLS 客户端证书绑定的访问令牌 (Access token)。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md new file mode 100644 index 0000000..2b45c0b --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md @@ -0,0 +1,23 @@ +--- +sidebar_label: ResourceServerModeConfig +--- + +# 类型别名:ResourceServerModeConfig + +```ts +type ResourceServerModeConfig = { + protectedResources: ResourceServerConfig | ResourceServerConfig[]; +}; +``` + +MCP 服务器作为资源服务器模式的配置。 + +## 属性 {#properties} + +### protectedResources {#protectedresources} + +```ts +protectedResources: ResourceServerConfig | ResourceServerConfig[]; +``` + +单个资源服务器配置或其数组。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md new file mode 100644 index 0000000..97920bc --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md @@ -0,0 +1,30 @@ +--- +sidebar_label: ValidateIssuerFunction +--- + +# 类型别名:ValidateIssuerFunction() + +```ts +type ValidateIssuerFunction = (tokenIssuer: string) => void; +``` + +用于验证访问令牌 (Access token) 的发行者 (Issuer) 的函数类型。 + +如果发行者 (Issuer) 无效,此函数应抛出一个带有代码 'invalid_issuer' 的 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)。发行者 (Issuer) 应根据以下内容进行验证: + +1. MCP-Auth 的授权服务器 (Authorization server) 元数据中配置的授权服务器 (Authorization server) +2. 受保护资源元数据中列出的授权服务器 (Authorization server) + +## 参数 {#parameters} + +### tokenIssuer {#tokenissuer} + +`string` + +## 返回 {#returns} + +`void` + +## 抛出 {#throws} + +当发行者 (Issuer) 未被识别或无效时。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md new file mode 100644 index 0000000..9e24845 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md @@ -0,0 +1,36 @@ +--- +sidebar_label: VerifyAccessTokenFunction +--- + +# 类型别名:VerifyAccessTokenFunction() + +```ts +type VerifyAccessTokenFunction = (token: string) => MaybePromise; +``` + +用于验证访问令牌 (Access token) 的函数类型。 + +如果令牌无效,此函数应抛出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md); +如果令牌有效,则返回一个 AuthInfo 对象。 + +例如,如果你有一个 JWT 验证函数,它至少应检查令牌的签名、验证其过期时间,并提取必要的声明 (Claims) 以返回一个 `AuthInfo` 对象。 + +**注意:** 无需验证令牌中的以下字段,因为它们会由处理程序进行检查: + +- `iss`(发行者 (Issuer)) +- `aud`(受众 (Audience)) +- `scope`(权限 (Scopes)) + +## 参数 {#parameters} + +### token {#token} + +`string` + +要验证的访问令牌 (Access token) 字符串。 + +## 返回值 {#returns} + +`MaybePromise`\<`AuthInfo`\> + +一个 Promise(或同步值),当令牌有效时解析为 AuthInfo 对象。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md new file mode 100644 index 0000000..a616dbc --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: VerifyAccessTokenMode +--- + +# 类型别名:VerifyAccessTokenMode + +```ts +type VerifyAccessTokenMode = "jwt"; +``` + +`bearerAuth` 支持的内置验证模式。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md new file mode 100644 index 0000000..ebd2c2d --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: authServerErrorDescription +--- + +# 变量:authServerErrorDescription + +```ts +const authServerErrorDescription: Readonly>; +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md new file mode 100644 index 0000000..1840b81 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: authorizationServerMetadataSchema +--- + +# 变量:authorizationServerMetadataSchema + +```ts +const authorizationServerMetadataSchema: ZodObject; +``` + +用于 OAuth 2.0 授权服务器元数据 (Authorization Server Metadata) 的 Zod schema,定义见 RFC 8414。 + +## 参考 {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md new file mode 100644 index 0000000..17d19d6 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: bearerAuthErrorDescription +--- + +# 变量:bearerAuthErrorDescription + +```ts +const bearerAuthErrorDescription: Readonly>; +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md new file mode 100644 index 0000000..d42244a --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseAuthorizationServerMetadataSchema +--- + +# 变量:camelCaseAuthorizationServerMetadataSchema + +```ts +const camelCaseAuthorizationServerMetadataSchema: ZodObject; +``` + +OAuth 2.0 授权服务器元数据 (Authorization Server Metadata) Zod schema 的 camelCase 版本。 + +## 参见 {#see} + +[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) 以获取原始 schema 和字段信息。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md new file mode 100644 index 0000000..e05876b --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseProtectedResourceMetadataSchema +--- + +# 变量:camelCaseProtectedResourceMetadataSchema + +```ts +const camelCaseProtectedResourceMetadataSchema: ZodObject; +``` + +OAuth 2.0 受保护资源元数据 Zod schema 的 camelCase 版本。 + +## 参见 {#see} + +[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) 以获取原始 schema 和字段信息。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md new file mode 100644 index 0000000..6563112 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md @@ -0,0 +1,9 @@ +--- +sidebar_label: defaultValues +--- + +# 变量:defaultValues + +```ts +const defaultValues: Readonly>; +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md new file mode 100644 index 0000000..b108660 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md @@ -0,0 +1,11 @@ +--- +sidebar_label: protectedResourceMetadataSchema +--- + +# 变量:protectedResourceMetadataSchema + +```ts +const protectedResourceMetadataSchema: ZodObject; +``` + +用于 OAuth 2.0 受保护资源元数据的 Zod schema。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md new file mode 100644 index 0000000..1c3c1a6 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md @@ -0,0 +1,12 @@ +--- +sidebar_label: serverMetadataPaths +--- + +# 变量:serverMetadataPaths + +```ts +const serverMetadataPaths: Readonly<{ + oauth: "/.well-known/oauth-authorization-server"; + oidc: "/.well-known/openid-configuration"; +}>; +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md new file mode 100644 index 0000000..06504fa --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: tokenVerificationErrorDescription +--- + +# 变量:tokenVerificationErrorDescription + +```ts +const tokenVerificationErrorDescription: Readonly>; +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md new file mode 100644 index 0000000..5428676 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md @@ -0,0 +1,9 @@ +--- +sidebar_label: validateServerConfig +--- + +# 变量:validateServerConfig + +```ts +const validateServerConfig: ValidateServerConfig; +``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx b/i18n/zh-CN/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx new file mode 100644 index 0000000..00f677a --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx @@ -0,0 +1,73 @@ +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + + + + +```python +mcp = FastMCP("MyMCPServer") +resource_identifier = "https://api.example.com" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_identifier, + authorization_servers=[fetch_server_config('', AuthServerType.OIDC)], + scopes_supported=["read", "write"], + ) + ) +) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + Mount('/', app=mcp.sse_app(), middleware=[Middleware( + mcp_auth.bearer_auth_middleware("jwt", + resource=resource_identifier, + audience=resource_identifier, + required_scopes=["read", "write"] + ) + )]) + ] +) + +@mcp.tool() +def whoami(): + return mcp_auth.auth_info.claims +``` + + + + +```ts +const server = new McpServer(/* ... */); +const resourceIdentifier = 'https://api.example.com'; + +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceIdentifier, + authorizationServers: [await fetchServerConfig('', { type: 'oidc' })], + scopesSupported: ['read', 'write'], + } + } +}); + +const app = express(); + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +app.use(mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, + requiredScopes: ['read', 'write'] +})); + +server.tool('whoami', ({ authInfo }) => { + return authInfo.claims; +}); +``` + + + diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx b/i18n/zh-CN/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx new file mode 100644 index 0000000..a060d4f --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx @@ -0,0 +1,1393 @@ +--- +sidebar_position: 2 +sidebar_label: '教程:构建一个待办事项管理器' +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + +# 教程:构建一个待办事项管理器 + +在本教程中,我们将构建一个带有用户认证 (Authentication) 和授权 (Authorization) 的待办事项管理器 MCP 服务器。按照最新的 MCP 规范,我们的 MCP 服务器将作为 OAuth 2.0 **资源服务器 (Resource Server)**,用于验证访问令牌 (Access token) 并强制执行基于权限 (Scope) 的权限控制。 + +完成本教程后,你将获得: + +- ✅ 对如何在 MCP 服务器中设置基于角色的访问控制 (RBAC) 有基本了解 +- ✅ 一个作为资源服务器 (Resource Server) 的 MCP 服务器,能够消费由授权服务器 (Authorization Server) 颁发的访问令牌 (Access token) +- ✅ 一个基于权限 (Scope) 的待办事项操作权限控制的实际实现 + +## 概览 \{#overview} + +本教程涉及以下组件: + +- **MCP 客户端(MCP Inspector)**:一个用于测试 MCP 服务器的可视化工具,作为 OAuth 2.0/OIDC 客户端。它发起与授权服务器的授权流程,并获取访问令牌 (Access token) 以认证 (Authentication) 对 MCP 服务器的请求。 +- **授权服务器 (Authorization Server)**:一个 OAuth 2.1 或 OpenID Connect 提供商,负责管理用户身份、认证 (Authentication) 用户,并向授权客户端颁发带有相应权限 (Scope) 的访问令牌 (Access token)。 +- **MCP 服务器(资源服务器 Resource Server)**:根据最新的 MCP 规范,MCP 服务器在 OAuth 2.0 框架中作为资源服务器 (Resource Server)。它验证授权服务器颁发的访问令牌 (Access token),并对待办事项操作强制执行基于权限 (Scope) 的权限控制。 + +该架构遵循标准的 OAuth 2.0 流程: + +- **MCP Inspector** 代表用户请求受保护资源 +- **授权服务器 (Authorization Server)** 认证 (Authentication) 用户并颁发访问令牌 (Access token) +- **MCP 服务器** 验证令牌并根据授予的权限 (Scope) 提供受保护资源 + +以下是这些组件之间交互的高级流程图: + +```mermaid +sequenceDiagram + autonumber + participant Client as MCP Inspector
(OAuth 客户端) + participant RS as MCP 服务器
(资源服务器 Resource Server) + participant AS as 授权服务器 (Authorization Server) + + Client->>RS: MCP 请求(无令牌) + RS-->>Client: 401 未授权 (WWW-Authenticate) + Note over Client: 从 WWW-Authenticate 头中提取 resource_metadata URL + + Client->>RS: GET /.well-known/oauth-protected-resource (resource_metadata) + RS-->>Client: 受保护资源元数据
(包含授权服务器 URL) + + Client->>AS: GET /.well-known/oauth-authorization-server + AS-->>Client: 授权服务器元数据 + Client->>AS: OAuth 授权(登录 & 同意) + AS-->>Client: 访问令牌 (Access token) + + Client->>RS: MCP 请求 (Authorization: Bearer ) + RS->>RS: 验证访问令牌 (Access token) 是否有效且已授权 + RS-->>Client: MCP 响应 +``` + +## 了解你的授权服务器 \{#understand-your-authorization-server} + +### 带有权限 (Scope) 的访问令牌 (Access token) \{#access-tokens-with-scopes} + +要在 MCP 服务器中实现[基于角色的访问控制 (RBAC)](https://auth.wiki/rbac),你的授权服务器需要支持颁发带有权限 (Scope) 的访问令牌 (Access token)。权限 (Scope) 代表用户被授予的权限。 + + + + +[Logto](https://logto.io) 通过其 API 资源(符合 [RFC 8707: OAuth 2.0 的资源指示器 Resource Indicator])和角色 (Role) 功能提供 RBAC 支持。设置方法如下: + +1. 登录 [Logto Console](https://cloud.logto.io)(或你的自托管 Logto Console) + +2. 创建 API 资源和权限 (Scope): + + - 进入“API 资源” + - 创建一个名为“Todo Manager”的新 API 资源 + - 添加以下权限 (Scope): + - `create:todos`:“创建新的待办事项” + - `read:todos`:“读取所有待办事项” + - `delete:todos`:“删除任意待办事项” + +3. 创建角色 (Role)(推荐,便于管理): + + - 进入“角色 (Roles)” + - 创建一个“Admin”角色,并分配所有权限 (`create:todos`, `read:todos`, `delete:todos`) + - 创建一个“User”角色,仅分配 `create:todos` 权限 + +4. 分配权限: + - 进入“用户” + - 选择一个用户 + - 你可以: + - 在“角色 (Roles)”标签页分配角色(推荐) + - 或直接在“权限 (Permissions)”标签页分配权限 (Scope) + +这些权限 (Scope) 会作为空格分隔的字符串包含在 JWT 访问令牌 (Access token) 的 `scope` 声明 (Claim) 中。 + + + + +OAuth 2.0 / OIDC 提供商通常支持基于权限 (Scope) 的访问控制。实现 RBAC 时: + +1. 在授权服务器中定义所需的权限 (Scope) +2. 配置客户端在授权流程中请求这些权限 (Scope) +3. 确保授权服务器在访问令牌 (Access token) 中包含授予的权限 (Scope) +4. 权限 (Scope) 通常包含在 JWT 访问令牌 (Access token) 的 `scope` 声明 (Claim) 中 + +请查阅你的提供商文档,了解: + +- 如何定义和管理权限 (Scope) +- 权限 (Scope) 如何包含在访问令牌 (Access token) 中 +- 是否有额外的 RBAC 功能,如角色 (Role) 管理 + + + + +### 验证令牌并检查权限 \{#validating-tokens-and-checking-permissions} + +根据最新的 MCP 规范,MCP 服务器在 OAuth 2.0 框架中作为**资源服务器 (Resource Server)**。作为资源服务器 (Resource Server),MCP 服务器有以下职责: + +1. **令牌验证**:验证从 MCP 客户端收到的访问令牌 (Access token) 的真实性和完整性 +2. **权限 (Scope) 强制**:从访问令牌 (Access token) 中提取并验证权限 (Scope),以确定客户端被授权执行哪些操作 +3. **资源保护**:仅在客户端提供有效且权限 (Scope) 足够的令牌时,才提供受保护资源(执行工具) + +当 MCP 服务器收到请求时,会执行如下验证流程: + +1. 从 `Authorization` 头中提取访问令牌 (Access token)(Bearer token 格式) +2. 验证访问令牌 (Access token) 的签名和过期时间 +3. 从已验证的令牌中提取权限 (Scope) 和用户信息 +4. 检查令牌是否包含所请求操作所需的权限 (Scope) + +例如,如果用户想创建新的待办事项,其访问令牌 (Access token) 必须包含 `create:todos` 权限 (Scope)。以下是资源服务器 (Resource Server) 验证流程: + +```mermaid +sequenceDiagram + participant Client as MCP 客户端 + participant Server as MCP 服务器
(资源服务器 Resource Server) + participant Auth as 授权服务器 (Authorization Server) + + Client->>Server: 携带访问令牌的请求
(Authorization: Bearer ) + + alt JWT 验证(推荐) + Server->>Auth: 获取 JWKS(如未缓存) + Auth-->>Server: 返回 JWKS + Server->>Server: 本地验证 JWT 签名和声明 (Claim) + else 令牌自省(备用) + Server->>Auth: POST /introspect
(token=access_token) + Auth-->>Server: 返回令牌信息
(active, scope, user_id 等) + end + + Server->>Server: 从已验证令牌中提取权限 (Scope) 和用户上下文 + + alt 拥有所需权限 (Scope) + Server->>Server: 执行请求的操作 + Server->>Client: 返回操作结果 + else 缺少所需权限 (Scope) + Server->>Client: 返回 403 Forbidden
(insufficient_scope 错误) + end +``` + +### 动态客户端注册 \{#dynamic-client-registration} + +本教程不要求动态客户端注册,但如果你想自动化 MCP 客户端注册流程,可以参考 [是否需要动态客户端注册?](/provider-list#is-dcr-required) 获取更多信息。 + +## 了解待办事项管理器中的 RBAC \{#understand-rbac-in-todo-manager} + +为了演示,我们将在待办事项管理器 MCP 服务器中实现一个简单的基于角色的访问控制 (RBAC) 系统。这将向你展示 RBAC 的基本原理,同时保持实现简洁。 + +:::note +虽然本教程演示了基于 RBAC 的权限 (Scope) 管理,但需要注意,并非所有认证 (Authentication) 提供商都通过角色 (Role) 实现权限 (Scope) 管理。有些提供商可能有自己独特的访问控制和权限管理机制。 +::: + +### 工具与权限 (Scope) \{#tools-and-scopes} + +我们的待办事项管理器 MCP 服务器提供三个主要工具: + +- `create-todo`:创建新的待办事项 +- `get-todos`:列出所有待办事项 +- `delete-todo`:根据 ID 删除待办事项 + +为了控制对这些工具的访问,我们定义如下权限 (Scope): + +- `create:todos`:允许创建新的待办事项 +- `delete:todos`:允许删除已有的待办事项 +- `read:todos`:允许查询和获取所有待办事项列表 + +### 角色 (Role) 与权限 (Permission) \{#roles-and-permissions} + +我们将定义两个具有不同访问级别的角色 (Role): + +| 角色 (Role) | create:todos | read:todos | delete:todos | +| ----- | ------------ | ---------- | ------------ | +| Admin | ✅ | ✅ | ✅ | +| User | ✅ | | | + +- **User**:普通用户,可以创建待办事项,仅能查看或删除自己的待办事项 +- **Admin**:管理员,可以创建、查看和删除所有待办事项,无论归属谁 + +### 资源归属 \{#resource-ownership} + +虽然上表显示了分配给每个角色 (Role) 的显式权限 (Scope),但还有一个重要的资源归属原则: + +- **User** 没有 `read:todos` 或 `delete:todos` 权限 (Scope),但仍然可以: + - 查看自己的待办事项 + - 删除自己的待办事项 +- **Admin** 拥有全部权限 (`read:todos` 和 `delete:todos`),可以: + - 查看系统中所有待办事项 + - 删除任意待办事项,无论归属谁 + +这展示了 RBAC 系统中的常见模式:资源归属为用户自己的资源隐式授予权限,而管理员角色 (Role) 则对所有资源拥有显式权限。 + +:::tip 了解更多 +想深入了解 RBAC 概念和最佳实践,请参阅 [精通 RBAC:一个全面的真实案例](https://blog.logto.io/mastering-rbac)。 +::: + +## 在你的提供商中配置授权 (Authorization) \{#configure-authorization-in-your-provider} + +要实现上述访问控制系统,你需要在授权服务器中配置所需的权限 (Scope)。不同提供商的配置方法如下: + + + + +[Logto](https://logto.io) 通过其 API 资源和角色 (Role) 功能提供 RBAC 支持。设置方法如下: + +1. 登录 [Logto Console](https://cloud.logto.io)(或你的自托管 Logto Console) + +2. 创建 API 资源和权限 (Scope): + + - 进入“API 资源” + - 创建一个名为“Todo Manager”的新 API 资源,并使用 `http://localhost:3001` 作为资源指示器 (Resource indicator)。 + - **重要**:资源指示器 (Resource indicator) 必须与你的 MCP 服务器 URL 匹配。本教程使用 `http://localhost:3001`,因为 MCP 服务器运行在 3001 端口。生产环境请使用实际 MCP 服务器 URL(如 `https://your-mcp-server.example.com`)。 + - 创建以下权限 (Scope): + - `create:todos`:“创建新的待办事项” + - `read:todos`:“读取所有待办事项” + - `delete:todos`:“删除任意待办事项” + +3. 创建角色 (Role)(推荐,便于管理): + + - 进入“角色 (Roles)” + - 创建一个“Admin”角色,并分配所有权限 (`create:todos`, `read:todos`, `delete:todos`) + - 创建一个“User”角色,仅分配 `create:todos` 权限 + - 在“User”角色详情页,切换到“常规”标签,并将“User”角色设置为“默认角色 (Default role)”。 + +4. 管理用户角色 (Role) 和权限 (Permission): + - 新用户: + - 因为设置了默认角色,注册后会自动获得“User”角色 + - 已有用户: + - 进入“用户管理” + - 选择一个用户 + - 在“角色 (Roles)”标签页为用户分配角色 + +:::tip 编程方式管理角色 (Role) +你也可以使用 Logto 的 [Management API](https://docs.logto.io/integrate-logto/interact-with-management-api) 以编程方式管理用户角色 (Role)。这对于自动化用户管理或构建管理后台非常有用。 +::: + +请求访问令牌 (Access token) 时,Logto 会根据用户角色 (Role) 权限将权限 (Scope) 包含在令牌的 `scope` 声明 (Claim) 中。 + + + + +对于 OAuth 2.0 或 OpenID Connect 提供商,你需要配置代表不同权限的权限 (Scope)。具体步骤视提供商而定,但通常包括: + +1. 定义权限 (Scope): + + - 配置授权服务器支持: + - `create:todos` + - `read:todos` + - `delete:todos` + +2. 配置客户端: + + - 注册或更新客户端以请求这些权限 (Scope) + - 确保权限 (Scope) 被包含在访问令牌 (Access token) 中 + +3. 分配权限 (Permission): + - 使用提供商界面为用户授予相应权限 (Scope) + - 有些提供商支持基于角色 (Role) 的管理,有些则直接分配权限 (Scope) + - 查阅提供商文档获取推荐做法 + +:::tip +大多数提供商会在访问令牌 (Access token) 的 `scope` 声明 (Claim) 中包含授予的权限 (Scope)。格式通常为空格分隔的权限 (Scope) 字符串。 +::: + + + + +配置好授权服务器后,用户将获得包含其权限 (Scope) 的访问令牌 (Access token)。MCP 服务器将使用这些权限 (Scope) 判断: + +- 用户是否可以创建新的待办事项(`create:todos`) +- 用户是否可以查看所有待办事项(`read:todos`)或仅能查看自己的 +- 用户是否可以删除任意待办事项(`delete:todos`)或仅能删除自己的 + +## 搭建 MCP 服务器 \{#set-up-the-mcp-server} + +我们将使用 [MCP 官方 SDK](https://github.com/modelcontextprotocol) 创建我们的待办事项管理器 MCP 服务器。 + +### 创建新项目 \{#create-a-new-project} + + + + +创建一个新的 Python 项目: + +```bash +mkdir mcp-todo-server +cd mcp-todo-server + +# 初始化新 Python 项目 +uv init + +# 使用 uv 创建虚拟环境 +uv venv + +# 激活虚拟环境(使用 'uv run' 时可选) +source .venv/bin/activate +``` + +:::note +本项目使用 `uv` 进行包管理,你也可以选择 `pip`、`poetry` 或 `conda` 等其他包管理器。 +::: + + + + +创建一个新的 Node.js 项目: + +```bash +mkdir mcp-server +cd mcp-server +npm init -y # 或使用 `pnpm init` +npm pkg set type="module" +npm pkg set main="todo-manager.ts" +npm pkg set scripts.start="node --experimental-strip-types todo-manager.ts" +``` + +:::note +我们的示例使用 TypeScript,因为 Node.js v22.6.0+ 原生支持 `--experimental-strip-types` 运行 TypeScript。如果你使用 JavaScript,代码类似——只需确保 Node.js 版本为 v22.6.0 或更高。详见 Node.js 官方文档。 +::: + + + + +### 安装 MCP SDK 及依赖 \{#install-the-mcp-sdk-and-dependencies} + + + + +安装所需依赖: + +```bash +uv add "mcp[cli]" uvicorn starlette +``` + + + + +```bash +npm install @modelcontextprotocol/sdk express zod +``` + +或使用你喜欢的包管理器,如 `pnpm` 或 `yarn`。 + + + + +### 创建 MCP 服务器 \{#create-the-mcp-server} + +首先,创建一个基础的 MCP 服务器和工具定义: + + + + +创建 `server.py` 文件并添加如下代码: + +```python +# server.py + +import contextlib +from typing import Any +from mcp.server.fastmcp import FastMCP +from starlette.applications import Starlette +from starlette.routing import Mount + +# 初始化 FastMCP 服务器 +mcp = FastMCP(name="Todo Manager", stateless_http=True, streamable_http_path='/') + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """创建新的待办事项。需要 'create:todos' 权限 (Scope)。""" + return {"error": "Not implemented"} + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """列出待办事项。拥有 'read:todos' 权限 (Scope) 的用户可查看所有待办事项。""" + return {"error": "Not implemented"} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """根据 id 删除待办事项。用户可删除自己的待办事项。""" + return {"error": "Not implemented"} + +@contextlib.asynccontextmanager +async def lifespan(app: Starlette): + async with contextlib.AsyncExitStack() as stack: + await stack.enter_async_context(mcp.session_manager.run()) + yield + +# 创建 app +app = Starlette( + routes=[ + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + +使用如下命令启动服务器: + +```bash +# 使用 uvicorn 启动 Todo Manager 服务器 +uvicorn server:app --host 127.0.0.1 --port 3001 + +# 或使用 uv: +# uv run uvicorn server:app --host 127.0.0.1 --port 3001 +``` + + + + +创建 `todo-manager.ts` 文件并添加如下代码: + +```ts +// todo-manager.ts + +import { z } from 'zod'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import express, { type Request, type Response } from 'express'; + +// 创建 MCP 服务器 +const server = new McpServer({ + name: 'Todo Manager', + version: '0.0.0', +}); + +server.tool('create-todo', '创建新的待办事项', { content: z.string() }, async ({ content }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('get-todos', '列出所有待办事项', async () => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('delete-todo', '根据 id 删除待办事项', { id: z.string() }, async ({ id }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +// 以下为 MCP SDK 文档中的样板代码 +const PORT = 3001; +const app = express(); + +app.post('/', async (request: Request, response: Response) => { + // 在无状态模式下,为每个请求创建新的 transport 和 server 实例以确保完全隔离。 + // 单一实例会导致多个客户端并发连接时请求 ID 冲突。 + + try { + const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + }); + response.on('close', async () => { + console.log('Request closed'); + await transport.close(); + await server.close(); + }); + await server.connect(transport); + await transport.handleRequest(request, response, request.body); + } catch (error) { + console.error('Error handling MCP request:', error); + if (!response.headersSent) { + response.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32_603, + message: 'Internal server error', + }, + id: null, + }); + } + } +}); + +// 无状态模式下不支持 SSE 通知 +app.get('/', async (request: Request, response: Response) => { + console.log('Received GET MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +// 无状态模式下无需会话终止 +app.delete('/', async (request: Request, response: Response) => { + console.log('Received DELETE MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +app.listen(PORT); +``` + +使用如下命令启动服务器: + +```bash +npm start +``` + + + + +### 检查 MCP 服务器 \{#inspect-the-mcp-server} + +#### 克隆并运行 MCP inspector \{#clone-and-run-mcp-inspector} + +现在 MCP 服务器已运行,我们可以使用 MCP inspector 检查工具是否可用。 + +官方 MCP inspector v0.16.2 存在影响认证 (Authentication) 功能的 bug。为了解决这些问题,我们提供了一个[修补版 MCP inspector](https://github.com/mcp-auth/inspector/tree/patch/0.16.2-fixes),包含了 OAuth/OIDC 认证 (Authentication) 流程的必要修复。我们也已向官方仓库提交了 PR。 + +运行 MCP inspector: + +```bash +git clone https://github.com/mcp-auth/inspector.git -b patch/0.16.2-fixes +cd inspector +npm install +npm run dev +``` + +MCP inspector 会自动在默认浏览器打开,或你也可以手动点击终端输出中的链接(确保点击带有 `MCP_PROXY_AUTH_TOKEN` 参数的链接,如 `http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=458ae4a4...acab1907`)。 + +#### 连接 MCP inspector 到 MCP 服务器 \{#connect-mcp-inspector-to-the-mcp-server} + +继续前请检查 MCP inspector 的如下配置: + +- **Transport Type**:设置为 `Streamable HTTP` +- **URL**:设置为你的 MCP 服务器 URL,本例为 `http://localhost:3001` + +现在点击“Connect”按钮,检查 MCP inspector 是否能连接 MCP 服务器。如果一切正常,你会在 MCP inspector 中看到“Connected”状态。 + +#### 检查点:运行待办事项管理工具 \{#checkpoint-run-todo-manager-tools} + +1. 在 MCP inspector 顶部菜单点击“Tools”标签 +2. 点击“List Tools”按钮 +3. 你应该能在页面上看到 `create-todo`、`get-todos` 和 `delete-todo` 工具,点击可查看工具详情 +4. 右侧会有“Run Tool”按钮,点击并输入所需参数运行工具 +5. 你会看到工具返回的 JSON 响应 `{"error": "Not implemented"}` + +![MCP inspector 首次运行](/docs-assets/images/tutorials/todo-manager/inspector-first-run.png) + +## 集成你的授权服务器 \{#integrate-with-your-authorization-server} + +完成本节需要考虑以下几点: + +
+**你的授权服务器的发行者 (Issuer) URL** + +通常是你的授权服务器的基础 URL,如 `https://auth.example.com`。有些提供商可能是 `https://example.logto.app/oidc`,请查阅你的提供商文档。 + +
+ +
+**如何获取授权服务器元数据** + +- 如果你的授权服务器符合 [OAuth 2.0 授权服务器元数据](https://datatracker.ietf.org/doc/html/rfc8414) 或 [OpenID Connect 发现](https://openid.net/specs/openid-connect-discovery-1_0.html),可以用 MCP Auth 内置工具自动获取元数据 +- 如果不符合上述标准,你需要在 MCP 服务器配置中手动指定元数据 URL 或端点。请查阅提供商文档 + +
+ +
+**如何将 MCP inspector 注册为授权服务器的客户端** + +- 如果你的授权服务器支持 [动态客户端注册 (Dynamic Client Registration)](https://datatracker.ietf.org/doc/html/rfc7591),可跳过此步,MCP inspector 会自动注册 +- 如果不支持动态客户端注册,需要手动在授权服务器中注册 MCP inspector 作为客户端 + +
+ +
+**了解令牌请求参数** + +向不同授权服务器请求访问令牌 (Access token) 时,指定目标资源和权限 (Scope) 的方式各异,主要有: + +- **基于资源指示器 (Resource indicator)**: + + - 使用 `resource` 参数指定目标 API(见 [RFC 8707: OAuth 2.0 的资源指示器]) + - 现代 OAuth 2.0 实现常见 + - 示例请求: + ```json + { + "resource": "http://localhost:3001", + "scope": "create:todos read:todos" + } + ``` + - 服务器颁发专门绑定到请求资源的令牌 + +- **基于受众 (Audience)**: + + - 使用 `audience` 参数指定令牌接收方 + - 与资源指示器类似但语义不同 + - 示例请求: + ```json + { + "audience": "todo-api", + "scope": "create:todos read:todos" + } + ``` + +- **纯权限 (Scope) 模式**: + - 仅依赖权限 (Scope),无 resource/audience 参数 + - 传统 OAuth 2.0 做法 + - 示例请求: + ```json + { + "scope": "todo-api:create todo-api:read openid profile" + } + ``` + - 常用前缀权限 (Scope) 进行命名空间隔离 + - 简单 OAuth 2.0 实现常见 + +:::tip 最佳实践 + +- 查阅你的提供商文档,了解支持哪些参数 +- 有些提供商同时支持多种方式 +- 资源指示器 (Resource indicator) 通过受众限制提升安全性 +- 如可用,建议优先使用资源指示器 (Resource indicator) 以获得更好的访问控制 + ::: + +
+ +虽然每个提供商有自己的具体要求,以下步骤将指导你如何结合 MCP inspector 和 MCP 服务器进行提供商特定配置。 + +### 注册 MCP inspector 为客户端 \{#register-mcp-inspector-as-a-client} + + + + +将待办事项管理器集成到 [Logto](https://logto.io) 非常简单,因为它是支持资源指示器 (Resource indicator) 和权限 (Scope) 的 OpenID Connect 提供商,可以用 `http://localhost:3001` 作为资源指示器保护你的 todo API。 + +由于 Logto 目前尚不支持动态客户端注册,你需要手动在 Logto 租户中注册 MCP inspector 作为客户端: + +1. 打开 MCP inspector,进入 Authentication 配置,点击 "OAuth2.0 Flow" 配置,复制 **Redirect URI**,如 `http://localhost:6274/oauth/callback` +2. 登录 [Logto Console](https://cloud.logto.io)(或你的自托管 Logto Console) +3. 进入“应用程序”标签,点击“创建应用程序”。页面底部点击“无框架创建应用” +4. 填写应用信息,点击“创建应用程序”: + - **选择应用类型**:选择“单页应用” + - **应用名称**:如“MCP Inspector” +5. 在“设置 / Redirect URIs”部分,粘贴 MCP inspector 复制的 **Redirect URI**,然后点击底部栏“保存更改” +6. 顶部卡片会显示“App ID”,复制它 +7. 回到 MCP inspector,在 Authentication 配置的 "OAuth2.0 Flow" 下的 "Client ID" 字段粘贴 "App ID" +8. 在 "Scope" 字段输入:`create:todos read:todos delete:todos`,确保 Logto 返回的访问令牌 (Access token) 包含访问 todo manager 所需的权限 (Scope) + + + + +:::note +这是通用的 OAuth 2.0 / OpenID Connect 提供商集成指南。OIDC 基于 OAuth 2.0,步骤类似。具体细节请查阅你的提供商文档。 +::: + +如果你的提供商支持动态客户端注册,可直接跳到第 8 步配置 MCP inspector,否则需手动注册 MCP inspector 为客户端: + +1. 打开 MCP inspector,进入 Authentication 配置,点击 "OAuth2.0 Flow" 配置,复制 **Redirect URI**,如 `http://localhost:6274/oauth/callback` + +2. 登录你的提供商控制台 + +3. 进入“应用程序”或“客户端”部分,创建新应用或客户端 + +4. 如需选择客户端类型,选“单页应用”或“公开客户端” + +5. 创建应用后,配置重定向 URI,粘贴 MCP inspector 复制的 **Redirect URI** + +6. 找到新建应用的 "Client ID" 或 "Application ID",复制 + +7. 回到 MCP inspector,在 Authentication 配置的 "OAuth2.0 Flow" 下的 "Client ID" 字段粘贴 + +8. 在 "Scope" 字段输入以下权限 (Scope) 以请求待办事项操作所需权限: + +```text +create:todos read:todos delete:todos +``` + + + + +### 配置 MCP Auth \{#set-up-mcp-auth} + +首先,在 MCP 服务器项目中安装 MCP Auth SDK。 + + + + +```bash +uv add mcpauth==0.2.0b1 +``` + + + + +```bash +npm install mcp-auth@0.2.0-beta.1 +``` + + + + +现在需要在 MCP 服务器中初始化 MCP Auth,主要分两步: + +1. **获取授权服务器元数据**:用于后续 MCP Auth 验证授权服务器颁发的访问令牌 (Access token),并在资源元数据中包含授权服务器的发行者 (Issuer) 标识 +2. **配置受保护资源元数据**:定义 MCP 服务器的资源标识符和支持的权限 (Scope) + +#### 步骤 1:获取授权服务器元数据 \{#step-1-fetch-authorization-server-metadata\} + +根据 OAuth / OIDC 规范,我们可以根据授权服务器的发行者 (Issuer) URL 获取授权服务器元数据。 + + + + + +在 Logto 中,你可以在 Logto Console 的应用详情页 "Endpoints & Credentials / Issuer endpoint" 部分找到发行者 (Issuer) URL,格式如 `https://my-project.logto.app/oidc`。 + + + + + +对于 OAuth 2.0 提供商,你需要: + +1. 查阅提供商文档,获取授权服务器 URL(通常称为发行者 (Issuer) URL 或基础 URL) +2. 有些提供商会在 `https://{your-domain}/.well-known/oauth-authorization-server` 暴露 +3. 在提供商管理后台的 OAuth/API 设置中查找 + + + + + +现在,使用 MCP Auth 工具函数获取授权服务器元数据: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +issuer_url = "" # 替换为你的授权服务器发行者 (Issuer) URL + +# 获取授权服务器配置 +auth_server_config = fetch_server_config(issuer_url, AuthServerType.OIDC) # 或 AuthServerType.OAUTH +``` + + + +```js +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const issuerUrl = ''; // 替换为你的授权服务器发行者 (Issuer) URL + +// 获取授权服务器配置(OIDC 发现) +const authServerConfig = await fetchServerConfig(issuerUrl, { type: 'oidc' }); // 或 { type: 'oauth' } +``` + + + + +如需其他方式获取授权服务器元数据或自定义配置,请参考[其他配置授权服务器元数据的方法](/docs/configure-server/mcp-auth#other-ways)。 + +#### 步骤 2:配置受保护资源元数据 \{#step-2-configure-protected-resource-metadata} + +接下来,在构建 MCP Auth 实例时配置受保护资源元数据。随后,MCP 服务器会通过 MCP Auth 暴露配置的资源元数据。 + + + + +```python +# server.py + +# 其他导入... +from mcpauth.types import ResourceServerConfig, ResourceServerMetadata + +# 定义 MCP 服务器的资源标识符 +resource_id = "http://localhost:3001" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + # 上一步获取的授权服务器元数据 + authorization_servers=[auth_server_config], + # MCP 服务器支持的权限 (Scope) + scopes_supported=[ + "create:todos", + "read:todos", + "delete:todos" + ] + ) + ) +) +``` + + + +```js +// todo-manager.ts + +// 定义 MCP 服务器的资源标识符 +const resourceId = 'http://localhost:3001'; + +// 配置 MCP Auth 的受保护资源元数据 +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceId, + // 上一步获取的授权服务器元数据 + authorizationServers: [authServerConfig], + // MCP 服务器支持的权限 (Scope) + scopesSupported: [ + "create:todos", + "read:todos", + "delete:todos" + ] + } + } +}); +``` + + + + +### 更新 MCP 服务器 \{#update-mcp-server} + +快完成了!现在需要更新 MCP 服务器,应用 MCP Auth 路由和中间件函数,并基于用户权限 (Scope) 实现待办事项工具的权限控制。 + +首先,应用受保护资源元数据路由,让 MCP 客户端可以从 MCP 服务器获取资源元数据。 + + + +```python +# server.py + +# ..其他代码 + +app = Starlette( + routes=[ + # 设置受保护资源元数据路由 + # 这会为 OAuth 客户端暴露本资源服务器的元数据 + *mcp_auth.resource_metadata_router().routes, + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +// 设置受保护资源元数据路由 +// 这会为 OAuth 客户端暴露本资源服务器的元数据 +app.use(mcpAuth.protectedResourceMetadataRouter()); + +``` + + + +接下来,应用 MCP Auth 中间件到 MCP 服务器。该中间件将处理所有请求的认证 (Authentication) 和授权 (Authorization),确保只有被授权用户才能访问待办事项工具。 + + + +```python +# server.py + +# 其他导入... +from starlette.middleware import Middleware + +# 其他代码... + +# 创建中间件 +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', resource=resource_id, audience=resource_id)) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # 应用 MCP Auth 中间件 + Mount("/", app=mcp.streamable_http_app(), middleware=[bearer_auth]), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// 应用 MCP Auth 中间件 +app.use( + mcpAuth.bearerAuth('jwt', { + resource: resourceId, + audience: resourceId, + }) +); +``` + + + +现在可以更新待办事项工具的实现,让其利用 MCP Auth 中间件进行认证 (Authentication) 和授权 (Authorization)。 + + + +```python +# server.py + +# 其他导入... + +from typing import Any, List, Optional +from mcpauth.exceptions import MCPAuthBearerAuthException, BearerAuthExceptionCode +from mcpauth.types import AuthInfo, ResourceServerConfig, ResourceServerMetadata + +# 下一节会用到 +from service import TodoService + +def assert_user_id(auth_info: Optional[AuthInfo]) -> str: + """断言 auth_info 包含有效用户 ID 并返回。""" + if not auth_info or not auth_info.subject: + raise Exception("Invalid auth info") + return auth_info.subject + +def has_required_scopes(user_scopes: List[str], required_scopes: List[str]) -> bool: + """检查用户是否拥有所有必需权限 (Scope)。""" + return all(scope in user_scopes for scope in required_scopes) + +# 创建 TodoService 实例 +todo_service = TodoService() + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """创建新的待办事项。需要 'create:todos' 权限 (Scope)。""" + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # 只有拥有 'create:todos' 权限 (Scope) 的用户才能创建 + user_scopes = auth_info.scopes if auth_info else [] + if not has_required_scopes(user_scopes, ["create:todos"]): + raise MCPAuthBearerAuthException(BearerAuthExceptionCode.MISSING_REQUIRED_SCOPES) + + created_todo = todo_service.create_todo(content=content, owner_id=user_id) + return created_todo + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """ + 列出待办事项。拥有 'read:todos' 权限 (Scope) 的用户可查看所有待办事项, + 否则只能查看自己的。 + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # 有 'read:todos' 权限 (Scope) 可访问所有待办事项,否则只能访问自己的 + user_scopes = auth_info.scopes if auth_info else [] + todo_owner_id = None if has_required_scopes(user_scopes, ["read:todos"]) else user_id + + todos = todo_service.get_all_todos(todo_owner_id) + return {"todos": todos} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """ + 根据 id 删除待办事项。用户可删除自己的待办事项。 + 拥有 'delete:todos' 权限 (Scope) 的用户可删除任意待办事项。 + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + todo = todo_service.get_todo_by_id(id) + + if not todo: + return {"error": "Failed to delete todo"} + + # 用户只能删除自己的待办事项 + # 拥有 'delete:todos' 权限 (Scope) 可删除任意待办事项 + user_scopes = auth_info.scopes if auth_info else [] + if todo.owner_id != user_id and not has_required_scopes(user_scopes, ["delete:todos"]): + return {"error": "Failed to delete todo"} + + deleted_todo = todo_service.delete_todo(id) + + if deleted_todo: + return { + "message": f"Todo {id} deleted", + "details": deleted_todo + } + else: + return {"error": "Failed to delete todo"} +``` + + + +```js +// todo-manager.ts + +// 其他导入... +import assert from 'node:assert'; +import { fetchServerConfig, MCPAuth, MCPAuthBearerAuthError } from 'mcp-auth'; +import { type AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js'; + +// 下一节会用到 +import { TodoService } from './todo-service.js'; + +const assertUserId = (authInfo?: AuthInfo) => { + const { subject } = authInfo ?? {}; + assert(subject, 'Invalid auth info'); + return subject; +}; + +const hasRequiredScopes = (userScopes: string[], requiredScopes: string[]): boolean => { + return requiredScopes.every((scope) => userScopes.includes(scope)); +}; + +const todoService = new TodoService(); + +server.tool( + 'create-todo', + '创建新的待办事项', + { content: z.string() }, + ({ content }: { content: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * 只有拥有 'create:todos' 权限 (Scope) 的用户才能创建 + */ + if (!hasRequiredScopes(authInfo?.scopes ?? [], ['create:todos'])) { + throw new MCPAuthBearerAuthError('missing_required_scopes'); + } + + const createdTodo = todoService.createTodo({ content, ownerId: userId }); + + return { + content: [{ type: 'text', text: JSON.stringify(createdTodo) }], + }; + } +); + +server.tool('get-todos', '列出所有待办事项', ({ authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * 有 'read:todos' 权限 (Scope) 可访问所有待办事项(todoOwnerId = undefined) + * 没有 'read:todos' 权限 (Scope) 只能访问自己的(todoOwnerId = userId) + */ + const todoOwnerId = hasRequiredScopes(authInfo?.scopes ?? [], ['read:todos']) + ? undefined + : userId; + + const todos = todoService.getAllTodos(todoOwnerId); + + return { + content: [{ type: 'text', text: JSON.stringify(todos) }], + }; +}); + +server.tool( + 'delete-todo', + '根据 id 删除待办事项', + { id: z.string() }, + ({ id }: { id: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + const todo = todoService.getTodoById(id); + + if (!todo) { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Failed to delete todo' }) }], + }; + } + + /** + * 用户只能删除自己的待办事项 + * 拥有 'delete:todos' 权限 (Scope) 可删除任意待办事项 + */ + if (todo.ownerId !== userId && !hasRequiredScopes(authInfo?.scopes ?? [], ['delete:todos'])) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ error: 'Failed to delete todo' }), + }, + ], + }; + } + + const deletedTodo = todoService.deleteTodo(id); + + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + message: `Todo ${id} deleted`, + details: deletedTodo, + }), + }, + ], + }; + } +); +``` + + + +现在,创建上述代码中用到的 "Todo service" 实现相关功能: + + + + +创建 `service.py` 文件: + +```python +""" +一个简单的 Todo 服务,仅用于演示。 +使用内存列表存储待办事项。 +""" + +from datetime import datetime +from typing import List, Optional, Dict, Any +import random +import string + +class Todo: + """待办事项实体""" + + def __init__(self, id: str, content: str, owner_id: str, created_at: str): + self.id = id + self.content = content + self.owner_id = owner_id + self.created_at = created_at + + def to_dict(self) -> Dict[str, Any]: + """转换为字典,便于 JSON 序列化""" + return { + "id": self.id, + "content": self.content, + "ownerId": self.owner_id, + "createdAt": self.created_at + } + + +class TodoService: + """简单的 Todo 服务,仅用于演示""" + + def __init__(self): + self._todos: List[Todo] = [] + + def get_all_todos(self, owner_id: Optional[str] = None) -> List[Dict[str, Any]]: + """ + 获取所有待办事项,可选按 owner_id 过滤 + + Args: + owner_id: 如提供,仅返回该用户的待办事项 + + Returns: + 待办事项字典列表 + """ + if owner_id: + filtered_todos = [todo for todo in self._todos if todo.owner_id == owner_id] + return [todo.to_dict() for todo in filtered_todos] + return [todo.to_dict() for todo in self._todos] + + def get_todo_by_id(self, todo_id: str) -> Optional[Todo]: + """ + 根据 ID 获取待办事项 + + Args: + todo_id: 待办事项 ID + + Returns: + 找到则返回 Todo 对象,否则返回 None + """ + for todo in self._todos: + if todo.id == todo_id: + return todo + return None + + def create_todo(self, content: str, owner_id: str) -> Dict[str, Any]: + """ + 创建新的待办事项 + + Args: + content: 待办事项内容 + owner_id: 用户 ID + + Returns: + 创建的待办事项字典 + """ + todo = Todo( + id=self._generate_id(), + content=content, + owner_id=owner_id, + created_at=datetime.now().isoformat() + ) + self._todos.append(todo) + return todo.to_dict() + + def delete_todo(self, todo_id: str) -> Optional[Dict[str, Any]]: + """ + 根据 ID 删除待办事项 + + Args: + todo_id: 待办事项 ID + + Returns: + 删除的待办事项字典,如未找到返回 None + """ + for i, todo in enumerate(self._todos): + if todo.id == todo_id: + deleted_todo = self._todos.pop(i) + return deleted_todo.to_dict() + return None + + def _generate_id(self) -> str: + """生成随机 ID""" + return ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)) +``` + + + + +创建 `todo-service.ts` 文件: + +```ts +// todo-service.ts + +type Todo = { + id: string; + content: string; + ownerId: string; + createdAt: string; +}; + +/** + * 简单的 Todo 服务,仅用于演示。 + * 使用内存数组存储待办事项 + */ +export class TodoService { + private readonly todos: Todo[] = []; + + getAllTodos(ownerId?: string): Todo[] { + if (ownerId) { + return this.todos.filter((todo) => todo.ownerId === ownerId); + } + return this.todos; + } + + getTodoById(id: string): Todo | undefined { + return this.todos.find((todo) => todo.id === id); + } + + createTodo({ content, ownerId }: { content: string; ownerId: string }): Todo { + const todo: Todo = { + id: this.genId(), + content, + ownerId, + createdAt: new Date().toISOString(), + }; + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + this.todos.push(todo); + return todo; + } + + deleteTodo(id: string): Todo | undefined { + const index = this.todos.findIndex((todo) => todo.id === id); + + if (index === -1) { + return undefined; + } + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + const [deleted] = this.todos.splice(index, 1); + return deleted; + } + + private genId(): string { + return Math.random().toString(36).slice(2, 10); + } +} +``` + + + + +🎉 恭喜!我们已经成功实现了一个带有认证 (Authentication) 和授权 (Authorization) 的完整 MCP 服务器! + +你也可以参考我们的示例代码: + + + + +:::info +完整 MCP 服务器(OIDC 版本)代码请参考 [MCP Auth Python SDK 仓库](https://github.com/mcp-auth/python/tree/master/samples/current/todo-manager)。 +::: + + + + +:::info +完整 MCP 服务器(OIDC 版本)代码请参考 [MCP Auth Node.js SDK 仓库](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src)。 +::: + + + + +## 检查点:运行 `todo-manager` 工具 \{#checkpoint-run-the-todo-manager-tools} + +重启 MCP 服务器,并在浏览器中打开 MCP inspector。点击“Connect”按钮后,你会被重定向到授权服务器的登录页面。 + +登录并返回 MCP inspector 后,重复前面检查点的操作运行待办事项工具。此时,你可以用认证 (Authentication) 后的用户身份使用这些工具。工具的行为将根据你用户的角色 (Role) 和权限 (Permission) 不同而不同: + +- 如果你以 **User**(仅有 `create:todos` 权限 (Scope))登录: + + - 可以用 `create-todo` 工具创建新待办事项 + - 只能查看和删除自己的待办事项 + - 无法查看或删除其他用户的待办事项 + +- 如果你以 **Admin**(拥有所有权限:`create:todos`、`read:todos`、`delete:todos`)登录: + - 可以创建新待办事项 + - 可以用 `get-todos` 工具查看系统中所有待办事项 + - 可以用 `delete-todo` 工具删除任意待办事项,无论归属谁 + +你可以通过以下方式测试不同权限级别: + +1. 退出当前会话(点击 MCP inspector 的“Disconnect”按钮) +2. 用拥有不同角色 (Role)/权限 (Permission) 的其他用户账号登录 +3. 再次尝试相同工具,观察用户权限变化带来的行为差异 + +这展示了基于角色的访问控制 (RBAC) 在实际中的工作方式,不同用户对系统功能有不同访问级别。 + +![MCP inspector 待办事项工具结果](/docs-assets/images/tutorials/todo-manager/result.png) + + + + +:::info +完整 MCP 服务器(OIDC 版本)代码请参考 [MCP Auth Python SDK 仓库](https://github.com/mcp-auth/python)。 +::: + + + + +:::info +完整 MCP 服务器(OIDC 版本)代码请参考 [MCP Auth Node.js SDK 仓库](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src)。 +::: + + + + +## 结语 \{#closing-notes} + +🎊 恭喜!你已成功完成本教程。让我们回顾一下所做的内容: + +- 搭建了一个基础 MCP 服务器,包含待办事项管理工具(`create-todo`、`get-todos`、`delete-todo`) +- 实现了基于角色的访问控制 (RBAC),为用户和管理员设置不同权限级别 +- 使用 MCP Auth 将 MCP 服务器与授权服务器集成 +- 配置 MCP Inspector 认证 (Authentication) 用户,并用带权限 (Scope) 的访问令牌 (Access token) 调用工具 + +欢迎查阅其他教程和文档,充分发挥 MCP Auth 的强大功能。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/README.mdx b/i18n/zh-TW/docusaurus-plugin-content-docs/current/README.mdx new file mode 100644 index 0000000..6ea71ef --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/README.mdx @@ -0,0 +1,297 @@ +--- +sidebar_position: 1 +sidebar_label: 開始使用 +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# 開始使用 + +:::info MCP 授權 (Authorization) 規範支援 +本版本支援 [MCP 授權 (Authorization) 規範(2025-06-18 版)](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization)。 +::: + + +## 選擇相容的 OAuth 2.1 或 OpenID Connect 提供者 \{#choose-a-compatible-oauth-2-1-or-openid-connect-provider} + +MCP 規範對授權 (Authorization) 有[特定要求](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#standards-compliance)。授權 (Authorization) 機制基於既有規範,實作其部分功能子集,以確保安全性與互通性,同時維持簡潔: + +- OAuth 2.1 IETF DRAFT ([draft-ietf-oauth-v2-1-13](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13)) +- OAuth 2.0 授權伺服器中繼資料 (Authorization Server Metadata)([RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)) +- OAuth 2.0 動態用戶端註冊協定([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) +- OAuth 2.0 受保護資源中繼資料([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)) + +這些規範共同提供 MCP 實作所需的安全且標準化的授權 (Authorization) 框架。 + +你可以查閱 [MCP 相容提供者清單](/provider-list) 來確認你的提供者是否支援。 + +## 安裝 MCP Auth SDK \{#install-mcp-auth-sdk} + +MCP Auth 提供 Python 與 TypeScript 版本。如需支援其他語言或框架,歡迎告訴我們! + + + + +```bash +pip install mcpauth +``` + +或使用你偏好的套件管理工具,例如 pipenv 或 poetry。 + + + + +```bash +npm install mcp-auth +``` + +或使用你偏好的套件管理工具,例如 pnpm 或 yarn。 + + + + +## 初始化 MCP Auth \{#init-mcp-auth} + +第一步是定義你的資源標示符,並設定將被信任進行驗證 (Authentication) 的授權伺服器。MCP Auth 現在以資源伺服器模式運作,符合新版 MCP 規範,要求支援 OAuth 2.0 受保護資源中繼資料(RFC 9728)。 + +如果你的提供者符合: + +- [OAuth 2.0 授權伺服器中繼資料(RFC 8414)](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +你可以使用內建函式自動取得中繼資料並初始化 MCP Auth 實例: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType, ResourceServerConfig, ResourceServerMetadata +from mcpauth.utils import fetch_server_config + +# 1. 定義你的資源標示符,並取得其信任的授權伺服器設定。 +resource_id = "https://api.example.com/notes" +auth_server_config = fetch_server_config("https://auth.logto.io/oidc", AuthServerType.OIDC) + +# 2. 以資源伺服器模式初始化 MCPAuth。 +# `protected_resources` 可為單一物件或多個資源的清單。 +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +// 1. 定義你的資源標示符,並取得其信任的授權伺服器設定。 +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +// 2. 以資源伺服器模式初始化 MCPAuth。 +// `protectedResources` 可為單一物件或多個資源的陣列。 +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +如需其他設定授權伺服器中繼資料的方式(包含自訂中繼資料 URL、資料轉換或手動指定中繼資料),請參閱 [其他 MCP Auth 設定方式](./configure-server/mcp-auth.mdx#other-ways)。 + +## 掛載受保護資源中繼資料端點 \{#mount-the-protected-resource-metadata-endpoint} + +為符合新版 MCP 規範,MCP Auth 會將 OAuth 2.0 受保護資源中繼資料端點(RFC 9728)掛載到你的 MCP 伺服器。此端點讓用戶端能查詢: + +- 哪些授權伺服器可為你的受保護資源簽發有效權杖 +- 每個資源支援哪些權限範圍(scopes) +- 權杖驗證所需的其他中繼資料 + +端點路徑會根據你的資源標示符的路徑自動決定: + +- **無路徑**:`https://api.example.com` → `/.well-known/oauth-protected-resource` +- **有路徑**:`https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + +MCP 伺服器現在**作為資源伺服器**,負責驗證權杖並提供其受保護資源的中繼資料,並完全依賴外部授權伺服器進行驗證 (Authentication) 與授權 (Authorization)。 + +你可以使用 SDK 提供的方法掛載此端點: + + + + +```python +from starlette.applications import Starlette + +# 掛載路由以提供受保護資源中繼資料。 +# 資源 "https://api.example.com" → 端點: /.well-known/oauth-protected-resource +# 資源 "https://api.example.com/notes" → 端點: /.well-known/oauth-protected-resource/notes +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// 掛載路由以提供受保護資源中繼資料。 +// 資源 "https://api.example.com" → 端點: /.well-known/oauth-protected-resource +// 資源 "https://api.example.com/notes" → 端點: /.well-known/oauth-protected-resource/notes +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + + +## 使用 Bearer 驗證 (Authentication) 中介軟體 \{#use-the-bearer-auth-middleware} + +初始化 MCP Auth 實例後,你可以套用 Bearer 驗證 (Authentication) 中介軟體來保護 MCP 路由。此中介軟體現在需指定端點所屬資源,以正確驗證權杖: + +:::note 受眾 (Audience) 驗證 +OAuth 2.0 規範要求 `audience` 參數以確保權杖驗證安全。然而,目前為了相容尚未支援資源標示符的授權伺服器,此參數**為選填**。出於安全考量,**請盡可能加上 audience 參數**。未來版本將強制要求受眾 (Audience) 驗證,以完全符合規範。 +::: + + + + +```python +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount + +# 建立中介軟體,以資源專屬政策保護你的 MCP 伺服器。 +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', + resource=resource_id, + audience=resource_id, # 啟用受眾 (Audience) 驗證以提升安全性 + required_scopes=['read:notes'] +)) + +# 掛載路由以提供受保護資源中繼資料並保護 MCP 伺服器。 +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # 以 Bearer 驗證 (Authentication) 中介軟體保護 MCP 伺服器。 + Mount("/", app=mcp.sse_app(), middleware=[bearer_auth]), + ], +) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +// 掛載路由以提供受保護資源中繼資料。 +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// 以資源專屬政策保護 API 端點。 +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, // 啟用受眾 (Audience) 驗證以提升安全性 + requiredScopes: ['read:notes'], + }), + (req, res) => { + // 權杖驗證通過後,`req.auth` 會帶有宣告 (Claims)。 + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); + +app.listen(3000); +``` + + + + +如上例所示,我們指定 `jwt` 權杖類型與資源標示符。中介軟體會自動根據該資源所設定的信任授權伺服器驗證 JWT 權杖,並填入已驗證使用者資訊。 + +:::info +還沒聽過 JWT(JSON Web Token)嗎?別擔心,繼續閱讀文件,我們會在需要時說明。你也可以參考 [Auth Wiki](https://auth.wiki/jwt) 快速入門。 +::: + +更多 Bearer 驗證 (Authentication) 設定資訊,請參閱 [Bearer 驗證 (Authentication) 設定](./configure-server/bearer-auth.mdx)。 + +## 在 MCP 實作中取得驗證 (Authentication) 資訊 \{#retrieve-the-auth-info-in-your-mcp-implementation} + +套用 Bearer 驗證 (Authentication) 中介軟體後,你可以在 MCP 實作中存取已驗證使用者(或身分)的資訊: + + + + +MCP Auth 會在 Bearer 驗證 (Authentication) 中介軟體驗證成功後,將已驗證使用者資訊存入 context 變數。你可以在 MCP 工具處理函式中這樣存取: + +```python +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP() + +# 如前述範例初始化 MCP Auth +# ... + +@mcp.tool() +def add(a: int, b: int): + """ + 加總兩個數字的工具。 + 已驗證使用者資訊會在 context 中取得。 + """ + auth_info = mcp_auth.auth_info # 於目前 context 取得驗證 (Authentication) 資訊 + if auth_info: + print(f"Authenticated user: {auth_info.claims}") + return a + b +``` + + + + +工具處理函式的第二個參數會包含 `authInfo` 物件,內含已驗證使用者資訊: + +```ts +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { z } from 'zod'; + +const server = new McpServer(/* ... */); + +// 如前述範例初始化 MCP Auth +// ... + +server.tool('add', { a: z.number(), b: z.number() }, async ({ a, b }, { authInfo }) => { + // 你現在可以透過 `authInfo` 物件存取驗證 (Authentication) 資訊 +}); +``` + + + + +## 下一步 \{#next-steps} + +繼續閱讀,了解如何將 MCP Auth 與你的 MCP 伺服器整合的端到端範例,以及如何在 MCP 用戶端處理驗證 (Authentication) 流程。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx b/i18n/zh-TW/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx new file mode 100644 index 0000000..0adba49 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/configure-server/bearer-auth.mdx @@ -0,0 +1,280 @@ +--- +sidebar_position: 2 +sidebar_label: Bearer auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# 在 MCP 伺服器中設定 Bearer 驗證 (Bearer auth) + +根據最新的 MCP 規範,你的 MCP 伺服器會作為**資源伺服器 (Resource Server)**,負責驗證受保護資源的存取權杖 (Access tokens)。MCP Auth 提供多種方式來設定 Bearer 授權 (Authorization): + +- [JWT (JSON Web Token)](https://auth.wiki/jwt) 模式:內建的授權方法,透過宣告 (Claims) 驗證 JWT。 +- 自訂模式:允許你實作自己的授權邏輯。 + +Bearer auth 中介軟體現在需要指定端點所屬的資源,以便正確地根據設定的授權伺服器進行權杖驗證。 + +## 使用 JWT 模式設定 Bearer 驗證 (Configure Bearer auth with JWT mode) \{#configure-bearer-auth-with-jwt-mode} + +如果你的 OAuth / OIDC 提供者發行 JWT 作為授權權杖 (Authorization token),你可以在 MCP Auth 中使用內建的 JWT 模式。它會驗證 JWT 的簽章、過期時間以及你指定的其他宣告 (Claims);然後將驗證資訊填入請求上下文,供 MCP 實作進一步處理。 + +### 權限範圍驗證 (Scope validation) \{#scope-validation} + +以下是基本權限範圍驗證的範例: + + + + +```python +from mcpauth import MCPAuth +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.routing import Mount +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP("MyMCPServer") +mcp_auth = MCPAuth( + # Initialize with your auth server config +) +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", # 指定此端點所屬的資源 + audience="https://api.example.com", # 啟用受眾 (Audience) 驗證以提升安全性 + required_scopes=["read", "write"] # [!code highlight] +) + +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + /* ... */ +}); +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // 指定此端點所屬的資源 + audience: 'https://api.example.com', // 啟用受眾 (Audience) 驗證以提升安全性 + requiredScopes: ['read', 'write'] // [!code highlight] +}); + +app.use('/mcp', bearerAuth, (req, res) => { + // 現在 `req.auth` 包含驗證資訊 + console.log(req.auth); +}); +``` + + + + +在上述範例中,我們指定 JWT 必須包含 `read` 和 `write` 權限範圍 (Scopes)。如果 JWT 未包含**任一**這些權限範圍,請求將被拒絕並回傳 403 Forbidden 錯誤。 + +### 受眾驗證 (Audience validation, RFC 8707) \{#audience-validation-rfc-8707} + +為了安全的權杖驗證,你應該始終透過指定 `audience` 參數來啟用受眾驗證。這會驗證 JWT 中的 `aud`(受眾)宣告 (Claim),以確保權杖是專為你的 MCP 伺服器資源所簽發。 + +:::note Audience Validation +根據 OAuth 2.0 規範,`audience` 參數是安全權杖驗證的**必要**條件。但目前為了相容尚未支援資源標示符 (Resource indicator) 的授權伺服器,此參數仍為**選填**。出於安全考量,**請盡可能總是包含 audience 參數**。未來版本將強制要求受眾驗證,以完全符合規範。 +::: + +受眾值通常應與你的資源標示符 (Resource indicator) 相符: + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", # 指定此端點所屬的資源 + audience="https://api.example.com", # 啟用受眾 (Audience) 驗證以提升安全性 [!code highlight] + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', // 指定此端點所屬的資源 + audience: 'https://api.example.com', // 啟用受眾 (Audience) 驗證以提升安全性 [!code highlight] + requiredScopes: ['read', 'write'], +}); +``` + + + + +在上述範例中,MCP Auth 會同時驗證 JWT 的 `aud` 宣告 (Claim) 以及所需的權限範圍 (Scopes)。 + +### 提供自訂 JWT 驗證選項 (Provide custom options to the JWT verification) \{#provide-custom-options-to-the-jwt-verification} + +你也可以為底層的 JWT 驗證函式庫提供自訂選項: + + + + +在 Python SDK 中,我們使用 [PyJWT](https://pyjwt.readthedocs.io/en/stable/) 進行 JWT 驗證。你可以設定以下選項: + +- `leeway`:驗證 JWT 過期時間時允許的寬限秒數。預設為 60 秒。 + +```python +bearer_auth = mcp_auth.bearer_auth_middleware( + "jwt", + resource="https://api.example.com", + audience="https://api.example.com", + required_scopes=["read", "write"], + leeway=10, # 允許 10 秒時鐘誤差以減少時差問題 [!code highlight] +) +``` + + + + +在 Node.js SDK 中,我們使用 [jose](https://github.com/panva/jose) 函式庫進行 JWT 驗證。你可以提供以下選項: + +- `jwtVerify`:JWT 驗證過程的選項(`jose` 的 `jwtVerify` 函式)。 +- `remoteJwtSet`:遠端 JWT set 取得的選項(`jose` 的 `createRemoteJWKSet` 函式)。 + +```ts {5-10} +const bearerAuth = mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', + requiredScopes: ['read', 'write'], + jwtVerify: { + clockTolerance: 60, // 允許 60 秒時鐘誤差 + }, + remoteJwtSet: { + timeoutDuration: 10 * 1000, // 取得遠端 JWT set 的逾時時間為 10 秒 + }, +}); +``` + + + + +## 使用自訂驗證設定 Bearer 驗證 (Configure Bearer auth with custom verification) \{#configure-bearer-auth-with-custom-verification} + +如果你的 OAuth / OIDC 提供者不發行 JWT,或你想自行實作授權邏輯,MCP Auth 允許你建立自訂驗證函式: + +:::info +由於 Bearer auth 中介軟體會根據驗證結果自動檢查簽發者 (Issuer, `iss`)、受眾 (Audience, `aud`) 及所需權限範圍 (Scope),你無需在自訂驗證函式中重複這些檢查。你只需專注於驗證權杖有效性(如簽章、過期等)並回傳驗證資訊物件即可。 +::: + + + + +```python +from mcpauth.exceptions import MCPAuthJwtVerificationException, MCPAuthJwtVerificationExceptionCode +from mcpauth.types import AuthInfo + +async def custom_verification(token: str) -> AuthInfo: + # 在這裡實作你的自訂驗證邏輯 + info = await verify_token(token) + if not info: + raise MCPAuthJwtVerificationException( + MCPAuthJwtVerificationExceptionCode.JWT_VERIFICATION_FAILED + ) + return info # 回傳驗證資訊物件 + +bearer_auth = mcp_auth.bearer_auth_middleware( + custom_verification, + resource="https://api.example.com", + audience="https://api.example.com", # 啟用受眾 (Audience) 驗證以提升安全性 + required_scopes=["read", "write"] +) +``` + + + + +```ts +const bearerAuth = mcpAuth.bearerAuth( + async (token) => { + // 在這裡實作你的自訂驗證邏輯 + const info = await verifyToken(token); + if (!info) { + throw new MCPAuthJwtVerificationError('jwt_verification_failed'); + } + return info; // 回傳驗證資訊物件 + }, + { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // 啟用受眾 (Audience) 驗證以提升安全性 + requiredScopes: ['read', 'write'] + } +); +``` + + + + +## 在 MCP 伺服器中套用 Bearer 驗證 (Apply Bearer auth in your MCP server) \{#apply-bearer-auth-in-your-mcp-server} + +要用 Bearer 驗證保護你的 MCP 伺服器,你需要將 Bearer auth 中介軟體套用到 MCP 伺服器實例。 + + + + +```python +bearer_auth = mcp_auth.bearer_auth_middleware("jwt", + resource="https://api.example.com", + audience="https://api.example.com", # 啟用受眾 (Audience) 驗證以提升安全性 + required_scopes=["read", "write"] +) +app = Starlette( + routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])] +) +``` + + + + +```js +const app = express(); +app.use(mcpAuth.bearerAuth('jwt', { + resource: 'https://api.example.com', + audience: 'https://api.example.com', // 啟用受眾 (Audience) 驗證以提升安全性 + requiredScopes: ['read', 'write'] +})); +``` + + + + +這將確保所有進入的請求都會根據設定的 Bearer 驗證規則進行驗證與授權 (Authorization),且驗證資訊會存於請求上下文中。 + +你可以在 MCP 伺服器實作中存取這些資訊: + + + + +```python +@mcp.tool() +async def whoami() -> dict: + # `mcp_auth.auth_info` 是目前請求的驗證資訊物件 + auth_info = mcp_auth.auth_info + print(f"Authenticated user: {auth_info.subject}") + return {"subject": auth_info.subject} +``` + + + + +```js +// `authInfo` 會從 `req.auth` 物件帶入 +server.tool('whoami', ({ authInfo }) => { + console.log(`Authenticated user: ${authInfo.subject}`); + return { subject: authInfo.subject }; +}); +``` + + + diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx b/i18n/zh-TW/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx new file mode 100644 index 0000000..c871c57 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/configure-server/mcp-auth.mdx @@ -0,0 +1,290 @@ +--- +sidebar_position: 1 +sidebar_label: MCP Auth +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +# 在 MCP 伺服器中設定 MCP Auth + +根據最新的 [MCP 規範 (2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18),你的 MCP 伺服器將作為**資源伺服器 (Resource Server)**,用於驗證由外部授權伺服器簽發的存取權杖 (Access tokens)。 + +設定 MCP Auth 主要分為兩個步驟: +1. **設定授權伺服器中繼資料 (Authorization Server Metadata)** —— 定義哪些授權伺服器可以為你的 MCP 伺服器簽發有效權杖,並指引 MCP 客戶端從哪裡取得存取權杖 (Access tokens) +2. **設定受保護資源中繼資料 (Protected Resource Metadata)** —— 將你的 MCP 伺服器定義為受保護資源,並設定支援的權限範圍 (Scopes) + +## 步驟 1:設定授權伺服器中繼資料 (Configure Authorization Server Metadata) \{#configure-authorization-server-metadata} + +### 自動抓取中繼資料 (Automatic metadata fetching) \{#automatic-metadata-fetching} + +最簡單的設定方式是使用內建函式,從 well-known URL 自動抓取中繼資料。如果你的提供者符合下列標準之一: + +- [OAuth 2.0 授權伺服器中繼資料 (Authorization Server Metadata)](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect 探索 (Discovery)](https://openid.net/specs/openid-connect-discovery-1_0.html) + +你可以透過 `fetchServerConfig`,傳入 `issuer` URL,自動取得中繼資料: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +# 抓取授權伺服器中繼資料 +auth_server_config = fetch_server_config( + "https://auth.logto.io/oidc", + AuthServerType.OIDC # 或 AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +// 抓取授權伺服器中繼資料 +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); // 或 'oauth' +``` + + + + +如果你的 issuer 包含路徑,OAuth 2.0 與 OpenID Connect 的行為略有不同: + +- **OAuth 2.0**:well-known URL 會加在 issuer 的**網域**後。例如,若 issuer 為 `https://my-project.logto.app/oauth`,well-known URL 會是 `https://auth.logto.io/.well-known/oauth-authorization-server/oauth`。 +- **OpenID Connect**:well-known URL 會直接加在**issuer**後。例如,若 issuer 為 `https://my-project.logto.app/oidc`,well-known URL 會是 `https://auth.logto.io/oidc/.well-known/openid-configuration`。 + +### 其他設定授權伺服器中繼資料的方法 (Other ways to configure authorization server metadata) \{#other-ways} + +#### 自訂資料轉換 (Custom data transpilation) \{#custom-data-transpilation} + +有時候,提供者回傳的中繼資料格式不符預期。如果你確定提供者是合規的,可以用 `transpile_data` 選項在使用前修改中繼資料: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +auth_server_config = fetch_server_config( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +import { fetchServerConfig } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfig('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +這讓你能在 MCP Auth 使用前,先修改中繼資料物件。例如新增或移除欄位、變更值、或轉換格式。 + +#### 從特定 URL 抓取中繼資料 (Fetch metadata from a specific URL) \{#fetch-metadata-from-a-specific-url} + +如果你的提供者有專屬的中繼資料 URL(而非標準 URL),也可以這樣使用: + + + + +```python +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC # 或 AuthServerType.OAUTH +) +``` + + + + +```ts +import { fetchServerConfigByWellKnownUrl } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { type: 'oidc' }); // 或 'oauth' +``` + + + + +#### 從特定 URL 並自訂資料轉換 (Fetch metadata from a specific URL with custom data transpilation) \{#fetch-metadata-from-a-specific-url-with-custom-data-transpilation} + +有時候,提供者回應格式不正確或不符預期。如果你確定提供者合規,可以透過 config 選項轉換中繼資料: + + + + +```python +from mcpauth.config import AuthServerType, fetch_server_config_by_well_known_url + +auth_server_config = fetch_server_config_by_well_known_url( + '', + type=AuthServerType.OIDC, + transpile_data=lambda data: {**data, 'response_types_supported': ['code']} # [!code highlight] +) +``` + + + + +```ts +const authServerConfig = await fetchServerConfigByWellKnownUrl('', { + type: 'oidc', + transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] +}); +``` + + + + +#### 手動提供中繼資料 (Manually provide metadata) \{#manually-provide-metadata} + +如果你的提供者不支援自動抓取中繼資料,可以手動提供中繼資料物件: + + + + +```python +from mcpauth.config import AuthServerConfig, AuthServerType, AuthorizationServerMetadata + +auth_server_config = AuthServerConfig( + type=AuthServerType.OIDC, # 或 AuthServerType.OAUTH + metadata=AuthorizationServerMetadata( + issuer='', + authorization_endpoint='', + # ... 其他中繼資料欄位 + ), +) +``` + + + + +```ts +const authServerConfig = { + metadata: { + issuer: '', + // Metadata fields 應為 camelCase + authorizationEndpoint: '', + // ... 其他中繼資料欄位 + }, + type: 'oidc', // 或 'oauth' +}; +``` + + + + +## 步驟 2:設定受保護資源中繼資料 (Configure Protected Resource Metadata) \{#configure-protected-resource-metadata} + +設定好授權伺服器中繼資料後,你需要將 MCPAuth 初始化為資源伺服器 (Resource Server),並定義你的受保護資源中繼資料。 + +此步驟遵循 [RFC 9728 (OAuth 2.0 Protected Resource Metadata)](https://datatracker.ietf.org/doc/html/rfc9728) 規範,將你的 MCP 伺服器描述為受保護資源: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import ResourceServerConfig, ResourceServerMetadata + +# 定義你的資源識別碼 +resource_id = "https://api.example.com/notes" + +# 以資源伺服器模式初始化 MCPAuth +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + authorization_servers=[auth_server_config], # 使用步驟 1 的 config + scopes_supported=[ + "read:notes", + "write:notes", + ], + ) + ) +) +``` + + + + +```ts +import { MCPAuth } from 'mcp-auth'; + +// 定義你的資源識別碼 +const resourceIdentifier = 'https://api.example.com/notes'; + +// 以資源伺服器模式初始化 MCPAuth +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], // 使用步驟 1 的 config + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); +``` + + + + +若有多個資源,可傳入受保護資源陣列,每個資源有自己的中繼資料設定。 + +上述設定涵蓋基本流程。若需進階中繼資料參數,請參閱 [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata)。 + +## 步驟 3:掛載受保護資源中繼資料端點 (Mount the protected resource metadata endpoint) \{#mount-the-protected-resource-metadata-endpoint} + +掛載路由器以提供受保護資源中繼資料端點。端點路徑會根據你的資源識別碼的 path 自動決定: + +- **無 path**:`https://api.example.com` → `/.well-known/oauth-protected-resource` +- **有 path**:`https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` + + + + +```python +from starlette.applications import Starlette +from mcpauth import MCPAuth + +mcp_auth = MCPAuth({/* ... */}) + +app = Starlette(routes=[ + *mcp_auth.resource_metadata_router().routes, +]) +``` + + + + +```ts +import express from 'express'; + +const app = express(); + +const mcpAuth = new MCPAuth({/* ... */}); + +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` + + + diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/README.md new file mode 100644 index 0000000..58a91d0 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/README.md @@ -0,0 +1,59 @@ +--- +sidebar_label: Node.js SDK +--- + +# MCP Auth Node.js SDK 參考文件 + +## 類別 {#classes} + +- [MCPAuth](/references/js/classes/MCPAuth.md) +- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) +- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) +- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) +- [MCPAuthError](/references/js/classes/MCPAuthError.md) +- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) + +## 型別別名 {#type-aliases} + +- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) +- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) +- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) +- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) +- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) +- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) +- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) +- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) +- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) +- [AuthServerType](/references/js/type-aliases/AuthServerType.md) +- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) +- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) +- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) +- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) +- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) +- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) +- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) +- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) +- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) +- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) +- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) +- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) + +## 變數 {#variables} + +- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) +- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) +- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) +- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) +- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) +- [defaultValues](/references/js/variables/defaultValues.md) +- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) +- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) +- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) +- [validateServerConfig](/references/js/variables/validateServerConfig.md) + +## 函式 {#functions} + +- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) +- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) +- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) +- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md new file mode 100644 index 0000000..4dff6e8 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md @@ -0,0 +1,281 @@ +--- +sidebar_label: MCPAuth +--- + +# 類別:MCPAuth + +mcp-auth 函式庫的主要類別。它作為工廠與註冊中心,用於建立你受保護資源的驗證 (Authentication) 政策。 + +初始化時需傳入伺服器設定,並提供 `bearerAuth` 方法,用於產生基於權杖的 Express 中介軟體(middleware)。 + +## 範例 {#example} + +### 在 `resource server` 模式下的用法 {#usage-in-resource-server-mode} + +這是新應用程式推薦的做法。 + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); + +const resourceIdentifier = 'https://api.example.com/notes'; +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); + +const mcpAuth = new MCPAuth({ + // `protectedResources` 可以是單一設定物件或其陣列。 + protectedResources: [ + { + metadata: { + resource: resourceIdentifier, + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes', 'write:notes'], + }, + }, + ], +}); + +// 掛載路由以處理受保護資源中繼資料 +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// 保護已設定資源的 API 端點 +app.get( + '/notes', + mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, // 指定此端點所屬資源 + audience: resourceIdentifier, // 可選,驗證 'aud' 宣告 (Claim) + requiredScopes: ['read:notes'], + }), + (req, res) => { + console.log('Auth info:', req.auth); + res.json({ notes: [] }); + }, +); +``` + +### 傳統 `authorization server` 模式用法(已棄用) {#legacy-usage-in-authorization-server-mode-deprecated} + +此做法為相容舊系統而保留。 + +```ts +import express from 'express'; +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const app = express(); +const mcpAuth = new MCPAuth({ + server: await fetchServerConfig( + 'https://auth.logto.io/oidc', + { type: 'oidc' } + ), +}); + +// 掛載路由以處理舊版授權伺服器中繼資料 +app.use(mcpAuth.delegatedRouter()); + +// 使用預設政策保護端點 +app.get( + '/mcp', + mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), + (req, res) => { + console.log('Auth info:', req.auth); + // 在此處理 MCP 請求 + }, +); +``` + +## 建構子 {#constructors} + +### 建構子 {#constructor} + +```ts +new MCPAuth(config: MCPAuthConfig): MCPAuth; +``` + +建立 MCPAuth 實例。 +會預先驗證整份設定,若有錯誤可及早失敗。 + +#### 參數 {#parameters} + +##### config {#config} + +[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) + +驗證 (Authentication) 設定。 + +#### 回傳 {#returns} + +`MCPAuth` + +## 屬性 {#properties} + +### config {#config} + +```ts +readonly config: MCPAuthConfig; +``` + +驗證 (Authentication) 設定。 + +## 方法 {#methods} + +### bearerAuth() {#bearerauth} + +#### 呼叫簽章 {#call-signature} + +```ts +bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; +``` + +建立一個 Bearer 權杖驗證處理器(Express 中介軟體),用於驗證請求的 `Authorization` 標頭中的存取權杖 (Access token)。 + +##### 參數 {#parameters} + +###### verifyAccessToken {#verifyaccesstoken} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +驗證存取權杖 (Access token) 的函式。應接受字串型態的權杖並回傳一個 promise(或值),解析為驗證結果。 + +**參見** + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以取得 `verifyAccessToken` 函式的型別定義。 + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> + +Bearer 權杖驗證處理器的選用設定。 + +**參見** + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以取得可用設定選項(不含 `verifyAccessToken` 與 `issuer`)。 + +##### 回傳 {#returns} + +`RequestHandler` + +一個 Express 中介軟體函式,會驗證存取權杖 (Access token) 並將驗證結果加入請求物件(`req.auth`)。 + +##### 參見 {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以瞭解實作細節與 `req.auth`(`AuthInfo`)物件的擴充型別。 + +#### 呼叫簽章 {#call-signature} + +```ts +bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; +``` + +建立一個 Bearer 權杖驗證處理器(Express 中介軟體),使用預設驗證模式驗證請求 `Authorization` 標頭中的存取權杖 (Access token)。 + +在 `'jwt'` 模式下,處理器會使用授權伺服器 JWKS URI 的 JWK Set 建立 JWT 驗證函式。 + +##### 參數 {#parameters} + +###### mode {#mode} + +`"jwt"` + +存取權杖 (Access token) 的驗證模式。目前僅支援 'jwt'。 + +**參見** + +[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) 以取得可用模式。 + +###### config? {#config} + +`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` + +Bearer 權杖驗證處理器的選用設定,包含 JWT 驗證選項與遠端 JWK Set 選項。 + +**參見** + + - VerifyJwtConfig 以取得 JWT 驗證可用設定選項。 + - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以取得可用設定選項(不含 `verifyAccessToken` 與 `issuer`)。 + +##### 回傳 {#returns} + +`RequestHandler` + +一個 Express 中介軟體函式,會驗證存取權杖 (Access token) 並將驗證結果加入請求物件(`req.auth`)。 + +##### 參見 {#see} + +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以瞭解實作細節與 `req.auth`(`AuthInfo`)物件的擴充型別。 + +##### 例外 {#throws} + +若在 `'jwt'` 模式下伺服器中繼資料未提供 JWKS URI,則會拋出例外。 + +*** + +### ~~delegatedRouter()~~ {#delegatedrouter} + +```ts +delegatedRouter(): Router; +``` + +建立一個代理路由器,用於提供舊版 OAuth 2.0 授權伺服器中繼資料端點 +(`/.well-known/oauth-authorization-server`),並使用實例提供的中繼資料。 + +#### 回傳 {#returns} + +`Router` + +一個路由器,會以實例提供的中繼資料服務 OAuth 2.0 授權伺服器中繼資料端點。 + +#### 已棄用 {#deprecated} + +請改用 [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter)。 + +#### 範例 {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +const app = express(); +const mcpAuth: MCPAuth; // 假設已初始化 +app.use(mcpAuth.delegatedRouter()); +``` + +#### 例外 {#throws} + +若於 `resource server` 模式下呼叫會拋出例外。 + +*** + +### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} + +```ts +protectedResourceMetadataRouter(): Router; +``` + +建立一個路由器,為所有已設定資源提供 OAuth 2.0 受保護資源中繼資料端點。 + +此路由器會根據你設定的資源識別符,自動建立正確的 `.well-known` 端點。 + +#### 回傳 {#returns} + +`Router` + +一個路由器,會服務 OAuth 2.0 受保護資源中繼資料端點。 + +#### 例外 {#throws} + +若於 `authorization server` 模式下呼叫會拋出例外。 + +#### 範例 {#example} + +```ts +import express from 'express'; +import { MCPAuth } from 'mcp-auth'; + +// 假設 mcpAuth 已以一個或多個 `protectedResources` 設定初始化 +const mcpAuth: MCPAuth; +const app = express(); + +// 這會根據你的資源識別符,在 `/.well-known/oauth-protected-resource/...` 提供中繼資料 +app.use(mcpAuth.protectedResourceMetadataRouter()); +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md new file mode 100644 index 0000000..68bd37b --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md @@ -0,0 +1,237 @@ +--- +sidebar_label: MCPAuthAuthServerError +--- + +# 類別:MCPAuthAuthServerError + +當遠端授權伺服器發生問題時所拋出的錯誤。 + +## 繼承自 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 建構子 {#constructors} + +### 建構子 {#constructor} + +```ts +new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; +``` + +#### 參數 {#parameters} + +##### code {#code} + +[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### 回傳 {#returns} + +`MCPAuthAuthServerError` + +#### 覆寫自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 屬性 {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: AuthServerErrorCode; +``` + +錯誤代碼,採用 snake_case 格式。 + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthAuthServerError'; +``` + +#### 覆寫自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 屬性指定堆疊追蹤(無論是由 `new Error().stack` 或 `Error.captureStackTrace(obj)` 產生)所收集的堆疊框架數量。 + +預設值為 `10`,但可設為任何有效的 JavaScript 數字。變更後將影響之後捕獲的所有堆疊追蹤。 + +如果設為非數字值或負數,則不會捕獲任何堆疊框架。 + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 方法 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +將錯誤轉換為適合 HTTP 回應的 JSON 格式。 + +#### 參數 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +是否在 JSON 回應中包含錯誤原因。預設為 `false`。 + +#### 回傳 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +在 `targetObject` 上建立 `.stack` 屬性,當存取時會回傳一個字串,表示呼叫 `Error.captureStackTrace()` 時的程式碼位置。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // 類似於 `new Error().stack` +``` + +追蹤的第一行會以 `${myObject.name}: ${myObject.message}` 為前綴。 + +可選的 `constructorOpt` 參數接受一個函式。如果提供,則所有在 `constructorOpt` 之上的堆疊框架(包含 `constructorOpt`)都會從產生的堆疊追蹤中省略。 + +`constructorOpt` 參數有助於隱藏錯誤產生的實作細節。例如: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 建立一個沒有堆疊追蹤的錯誤,以避免重複計算堆疊追蹤。 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 捕獲 function b 之上的堆疊追蹤 + Error.captureStackTrace(error, b); // 堆疊追蹤中不包含 function c 與 b + throw error; +} + +a(); +``` + +#### 參數 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 回傳 {#returns} + +`void` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 參數 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 回傳 {#returns} + +`any` + +#### 參考 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md new file mode 100644 index 0000000..3e0d659 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md @@ -0,0 +1,237 @@ +--- +sidebar_label: MCPAuthBearerAuthError +--- + +# 類別:MCPAuthBearerAuthError + +當使用 Bearer 權杖進行驗證 (Authentication) 時發生問題時所拋出的錯誤。 + +## 繼承自 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 建構子 {#constructors} + +### 建構子 {#constructor} + +```ts +new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; +``` + +#### 參數 {#parameters} + +##### code {#code} + +[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) + +##### cause? {#cause} + +[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) + +#### 回傳 {#returns} + +`MCPAuthBearerAuthError` + +#### 覆寫 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 屬性 {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: MCPAuthBearerAuthErrorDetails; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: BearerAuthErrorCode; +``` + +錯誤代碼,採用 snake_case 格式。 + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthBearerAuthError'; +``` + +#### 覆寫 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 屬性指定堆疊追蹤(無論是由 `new Error().stack` 或 `Error.captureStackTrace(obj)` 產生)所收集的堆疊框架數量。 + +預設值為 `10`,但可以設為任何有效的 JavaScript 數字。變更後將影響之後所擷取的所有堆疊追蹤。 + +如果設為非數字或負數,則不會擷取任何堆疊框架。 + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 方法 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +將錯誤轉換為適合 HTTP 回應的 JSON 格式。 + +#### 參數 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +是否在 JSON 回應中包含錯誤原因。預設為 `false`。 + +#### 回傳 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 覆寫 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +在 `targetObject` 上建立 `.stack` 屬性,當存取時會回傳一個字串,表示呼叫 `Error.captureStackTrace()` 時的程式碼位置。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // 類似於 `new Error().stack` +``` + +追蹤的第一行會以 `${myObject.name}: ${myObject.message}` 為前綴。 + +可選的 `constructorOpt` 參數接受一個函式。如果提供,則所有在 `constructorOpt` 之上的堆疊框架(包含 `constructorOpt`)都會從產生的堆疊追蹤中省略。 + +`constructorOpt` 參數可用於隱藏錯誤產生的實作細節。例如: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 建立一個沒有堆疊追蹤的錯誤,以避免重複計算堆疊追蹤。 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 擷取 function b 之上的堆疊追蹤 + Error.captureStackTrace(error, b); // 堆疊追蹤中不包含 function c 與 b + throw error; +} + +a(); +``` + +#### 參數 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 回傳 {#returns} + +`void` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 參數 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 回傳 {#returns} + +`any` + +#### 參見 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md new file mode 100644 index 0000000..2d225b6 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md @@ -0,0 +1,241 @@ +--- +sidebar_label: MCPAuthConfigError +--- + +# 類別:MCPAuthConfigError + +當 mcp-auth 發生設定問題時所拋出的錯誤。 + +## 繼承自 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 建構子 {#constructors} + +### 建構子 {#constructor} + +```ts +new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; +``` + +#### 參數 {#parameters} + +##### code {#code} + +`string` + +錯誤代碼,採用 snake_case 格式。 + +##### message {#message} + +`string` + +錯誤的人類可讀描述。 + +#### 回傳 {#returns} + +`MCPAuthConfigError` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 屬性 {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +錯誤代碼,採用 snake_case 格式。 + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthConfigError'; +``` + +#### 覆寫自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 屬性指定堆疊追蹤(無論是由 `new Error().stack` 或 `Error.captureStackTrace(obj)` 產生)所收集的堆疊框架數量。 + +預設值為 `10`,但可設為任何有效的 JavaScript 數字。變更後會影響之後所擷取的所有堆疊追蹤。 + +若設為非數字或負數,則不會擷取任何堆疊框架。 + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 方法 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +將錯誤轉換為適合 HTTP 回應的 JSON 格式。 + +#### 參數 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +是否在 JSON 回應中包含錯誤原因。預設為 `false`。 + +#### 回傳 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +在 `targetObject` 上建立 `.stack` 屬性,當存取時會回傳一個字串,表示呼叫 `Error.captureStackTrace()` 時在程式碼中的位置。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // 類似於 `new Error().stack` +``` + +追蹤的第一行會以 `${myObject.name}: ${myObject.message}` 為前綴。 + +可選的 `constructorOpt` 參數接受一個函式。如果提供,則所有在 `constructorOpt` 之上的堆疊框架(包含 `constructorOpt`)都會從產生的堆疊追蹤中省略。 + +`constructorOpt` 參數有助於隱藏錯誤產生的實作細節。例如: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 建立一個沒有堆疊追蹤的錯誤,以避免重複計算堆疊追蹤。 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 擷取 function b 之上的堆疊追蹤 + Error.captureStackTrace(error, b); // 堆疊追蹤中不包含 function c 與 b + throw error; +} + +a(); +``` + +#### 參數 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 回傳 {#returns} + +`void` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 參數 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 回傳 {#returns} + +`any` + +#### 參見 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md new file mode 100644 index 0000000..1900095 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md @@ -0,0 +1,259 @@ +--- +sidebar_label: MCPAuthError +--- + +# 類別:MCPAuthError + +所有 mcp-auth 錯誤的基礎類別。 + +它提供一種標準化方式來處理與 MCP 驗證 (Authentication) 和授權 (Authorization) 相關的錯誤。 + +## 繼承自 {#extends} + +- `Error` + +## 被以下類別擴充 {#extended-by} + +- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) +- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) +- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) +- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) + +## 建構子 {#constructors} + +### 建構子 {#constructor} + +```ts +new MCPAuthError(code: string, message: string): MCPAuthError; +``` + +#### 參數 {#parameters} + +##### code {#code} + +`string` + +錯誤代碼,採用 snake_case 格式。 + +##### message {#message} + +`string` + +錯誤的人類可讀描述。 + +#### 回傳 {#returns} + +`MCPAuthError` + +#### 覆寫 {#overrides} + +```ts +Error.constructor +``` + +## 屬性 {#properties} + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +#### 繼承自 {#inherited-from} + +```ts +Error.cause +``` + +*** + +### code {#code} + +```ts +readonly code: string; +``` + +錯誤代碼,採用 snake_case 格式。 + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 繼承自 {#inherited-from} + +```ts +Error.message +``` + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthError'; +``` + +#### 覆寫 {#overrides} + +```ts +Error.name +``` + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 繼承自 {#inherited-from} + +```ts +Error.stack +``` + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 屬性指定堆疊追蹤(無論是由 `new Error().stack` 或 `Error.captureStackTrace(obj)` 產生)所收集的堆疊框架數量。 + +預設值為 `10`,但可以設為任何有效的 JavaScript 數字。更改後會影響之後捕獲的所有堆疊追蹤。 + +如果設為非數字值或負數,則堆疊追蹤將不會捕獲任何框架。 + +#### 繼承自 {#inherited-from} + +```ts +Error.stackTraceLimit +``` + +## 方法 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +將錯誤轉換為適合 HTTP 回應的 JSON 格式。 + +#### 參數 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +是否在 JSON 回應中包含錯誤原因(cause)。 +預設為 `false`。 + +#### 回傳 {#returns} + +`Record`\<`string`, `unknown`\> + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +在 `targetObject` 上建立 `.stack` 屬性,當存取時會回傳一個字串,表示呼叫 `Error.captureStackTrace()` 時的程式碼位置。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // 類似於 `new Error().stack` +``` + +追蹤的第一行會以 `${myObject.name}: ${myObject.message}` 為前綴。 + +可選的 `constructorOpt` 參數接受一個函式。如果提供,則所有在 `constructorOpt` 之上的堆疊框架(包含 `constructorOpt`)都會從產生的堆疊追蹤中省略。 + +`constructorOpt` 參數有助於隱藏錯誤產生的實作細節。例如: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 建立一個沒有堆疊追蹤的錯誤,以避免重複計算堆疊追蹤。 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 捕獲 function b 之上的堆疊追蹤 + Error.captureStackTrace(error, b); // 堆疊追蹤中不包含 function c 與 b + throw error; +} + +a(); +``` + +#### 參數 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 回傳 {#returns} + +`void` + +#### 繼承自 {#inherited-from} + +```ts +Error.captureStackTrace +``` + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 參數 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 回傳 {#returns} + +`any` + +#### 參考 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 繼承自 {#inherited-from} + +```ts +Error.prepareStackTrace +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md new file mode 100644 index 0000000..ab49f22 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md @@ -0,0 +1,238 @@ +--- +sidebar_label: MCPAuthTokenVerificationError +--- + +# 類別:MCPAuthTokenVerificationError + +當驗證權杖時發生問題時所拋出的錯誤。 + +## 繼承自 {#extends} + +- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) + +## 建構子 {#constructors} + +### 建構子 {#constructor} + +```ts +new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; +``` + +#### 參數 {#parameters} + +##### code {#code} + +[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) + +##### cause? {#cause} + +`unknown` + +#### 回傳 {#returns} + +`MCPAuthTokenVerificationError` + +#### 覆寫自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) + +## 屬性 {#properties} + +### cause? {#cause} + +```ts +readonly optional cause: unknown; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) + +*** + +### code {#code} + +```ts +readonly code: MCPAuthTokenVerificationErrorCode; +``` + +錯誤代碼,採用 snake_case 格式。 + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) + +*** + +### message {#message} + +```ts +message: string; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) + +*** + +### name {#name} + +```ts +name: string = 'MCPAuthTokenVerificationError'; +``` + +#### 覆寫自 {#overrides} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) + +*** + +### stack? {#stack} + +```ts +optional stack: string; +``` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` + +`Error.stackTraceLimit` 屬性指定堆疊追蹤(stack trace)所收集的堆疊框架數量(無論是由 `new Error().stack` 或 `Error.captureStackTrace(obj)` 產生)。 + +預設值為 `10`,但可以設為任何有效的 JavaScript 數字。變更後會影響之後所擷取的所有堆疊追蹤。 + +若設為非數字或負數,則不會擷取任何堆疊框架。 + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) + +## 方法 {#methods} + +### toJson() {#tojson} + +```ts +toJson(showCause: boolean): Record; +``` + +將錯誤轉換為適合 HTTP 回應的 JSON 格式。 + +#### 參數 {#parameters} + +##### showCause {#showcause} + +`boolean` = `false` + +是否在 JSON 回應中包含錯誤原因(cause)。 +預設為 `false`。 + +#### 回傳 {#returns} + +`Record`\<`string`, `unknown`\> + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) + +*** + +### captureStackTrace() {#capturestacktrace} + +```ts +static captureStackTrace(targetObject: object, constructorOpt?: Function): void; +``` + +在 `targetObject` 上建立 `.stack` 屬性,當存取時會回傳一個字串,表示呼叫 `Error.captureStackTrace()` 時的程式碼位置。 + +```js +const myObject = {}; +Error.captureStackTrace(myObject); +myObject.stack; // 類似於 `new Error().stack` +``` + +追蹤的第一行會加上 `${myObject.name}: ${myObject.message}` 前綴。 + +可選的 `constructorOpt` 參數接受一個函式。如果提供,則產生的堆疊追蹤中,`constructorOpt` 及其以上的所有框架都會被省略。 + +`constructorOpt` 參數可用於隱藏錯誤產生的實作細節。例如: + +```js +function a() { + b(); +} + +function b() { + c(); +} + +function c() { + // 建立一個沒有堆疊追蹤的錯誤,以避免重複計算堆疊追蹤。 + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + const error = new Error(); + Error.stackTraceLimit = stackTraceLimit; + + // 擷取 function b 以上的堆疊追蹤 + Error.captureStackTrace(error, b); // 堆疊追蹤中不包含 function c 與 b + throw error; +} + +a(); +``` + +#### 參數 {#parameters} + +##### targetObject {#targetobject} + +`object` + +##### constructorOpt? {#constructoropt} + +`Function` + +#### 回傳 {#returns} + +`void` + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) + +*** + +### prepareStackTrace() {#preparestacktrace} + +```ts +static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; +``` + +#### 參數 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 回傳 {#returns} + +`any` + +#### 參見 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### 繼承自 {#inherited-from} + +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md new file mode 100644 index 0000000..cabf98e --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md @@ -0,0 +1,43 @@ +--- +sidebar_label: createVerifyJwt +--- + +# 函式:createVerifyJwt() + +```ts +function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; +``` + +建立一個函式,使用提供的金鑰取得函式與選項來驗證 JWT 存取權杖 (Access token)。 + +## 參數 {#parameters} + +### getKey {#getkey} + +`JWTVerifyGetKey` + +用於取得驗證 JWT 所需金鑰的函式。 + +**參見** + +JWTVerifyGetKey 以瞭解金鑰取得函式的型別定義。 + +### options? {#options} + +`JWTVerifyOptions` + +可選的 JWT 驗證選項。 + +**參見** + +JWTVerifyOptions 以瞭解選項的型別定義。 + +## 回傳值 {#returns} + +[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) + +一個用於驗證 JWT 存取權杖 (Access token) 的函式,若權杖有效則回傳 AuthInfo 物件。此函式要求 JWT 的 payload 中必須包含 `iss`、`client_id` 與 `sub` 欄位,且可選擇性包含 `scope` 或 `scopes` 欄位。該函式底層使用 `jose` 函式庫進行 JWT 驗證。 + +## 參見 {#see} + +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以瞭解回傳函式的型別定義。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md new file mode 100644 index 0000000..b0af0e4 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md @@ -0,0 +1,60 @@ +--- +sidebar_label: fetchServerConfig +--- + +# 函式:fetchServerConfig() + +```ts +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +``` + +根據簽發者 (Issuer) 與授權伺服器類型,取得伺服器設定。 + +此函式會根據伺服器類型自動判斷 well-known URL,因為 OAuth 及 OpenID Connect 伺服器的 metadata endpoint 慣例不同。 + +## 參數 {#parameters} + +### issuer {#issuer} + +`string` + +授權伺服器的簽發者 (Issuer) URL。 + +### config {#config} + +`ServerMetadataConfig` + +包含伺服器類型與可選轉換函式的設定物件。 + +## 回傳值 {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +一個 promise,解析後會得到伺服器設定。 + +## 參見 {#see} + + - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) 以瞭解底層實作。 + - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) 參考 OAuth 2.0 授權伺服器 metadata 規範。 + - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) 參考 OpenID Connect Discovery 規範。 + +## 範例 {#example} + +```ts +import { fetchServerConfig } from 'mcp-auth'; +// 取得 OAuth 伺服器設定 +// 這會從 `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` 取得 metadata +const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); + +// 取得 OpenID Connect 伺服器設定 +// 這會從 `https://auth.logto.io/oidc/.well-known/openid-configuration` 取得 metadata +const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); +``` + +## 例外 {#throws} + +若 fetch 操作失敗則會拋出例外。 + +## 例外 {#throws} + +若伺服器 metadata 無效或不符合 MCP 規範則會拋出例外。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md new file mode 100644 index 0000000..f44bf19 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md @@ -0,0 +1,41 @@ +--- +sidebar_label: fetchServerConfigByWellKnownUrl +--- + +# 函式:fetchServerConfigByWellKnownUrl() + +```ts +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +``` + +從提供的 well-known URL 取得伺服器設定,並依據 MCP 規範進行驗證。 + +如果伺服器中繼資料不符合預期的結構,但你確定其相容,你可以定義 `transpileData` 函式,將中繼資料轉換為預期格式。 + +## 參數 {#parameters} + +### wellKnownUrl {#wellknownurl} + +要從中取得伺服器設定的 well-known URL。可以是字串或 URL 物件。 + +`string` | `URL` + +### config {#config} + +`ServerMetadataConfig` + +包含伺服器類型與可選轉換函式的設定物件。 + +## 回傳值 {#returns} + +`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> + +一個 promise,解析後會得到伺服器設定。 + +## 例外 {#throws} + +當取得操作失敗時會丟出例外。 + +## 例外 {#throws} + +當伺服器中繼資料無效或不符合 MCP 規範時會丟出例外。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md new file mode 100644 index 0000000..117283a --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md @@ -0,0 +1,39 @@ +--- +sidebar_label: handleBearerAuth +--- + +# 函式:handleBearerAuth() + +```ts +function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; +``` + +建立一個用於在 Express 應用程式中處理 Bearer 驗證 (Authentication) 的中介軟體函式。 + +此中介軟體會從 `Authorization` 標頭中擷取 Bearer 存取權杖 (Access token),使用提供的 `verifyAccessToken` 函式進行驗證,並檢查簽發者 (Issuer)、受眾 (Audience) 及所需權限範圍 (Scopes)。 + +- 如果權杖有效,會將驗證資訊加入 `request.auth` 屬性; + 若無效,則回應相應的錯誤訊息。 +- 若存取權杖 (Access token) 驗證失敗,會回應 401 未授權錯誤。 +- 若權杖未包含所需權限範圍 (Scopes),會回應 403 禁止存取錯誤。 +- 若驗證 (Authentication) 流程中發生非預期錯誤,中介軟體會重新拋出錯誤。 + +**注意:** `request.auth` 物件會包含比 `@modelcontextprotocol/sdk` 模組中定義的標準 AuthInfo 介面更多的延伸欄位。詳情請參閱本檔案中的延伸介面。 + +## 參數 {#parameters} + +### param0 {#param0} + +[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) + +Bearer 驗證 (Authentication) 處理器的設定。 + +## 回傳值 {#returns} + +`RequestHandler` + +一個處理 Bearer 驗證 (Authentication) 的 Express 中介軟體函式。 + +## 參見 {#see} + +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以瞭解設定選項。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md new file mode 100644 index 0000000..1927ee0 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md @@ -0,0 +1,49 @@ +--- +sidebar_label: AuthServerConfig +--- + +# 型別別名:AuthServerConfig + +```ts +type AuthServerConfig = { + metadata: CamelCaseAuthorizationServerMetadata; + type: AuthServerType; +}; +``` + +與 MCP 伺服器整合的遠端授權伺服器(Authorization Server)設定。 + +## 屬性 {#properties} + +### metadata {#metadata} + +```ts +metadata: CamelCaseAuthorizationServerMetadata; +``` + +授權伺服器(Authorization Server)的中繼資料,需符合 MCP 規範 +(基於 OAuth 2.0 授權伺服器中繼資料)。 + +這些中繼資料通常從伺服器的 well-known endpoint(OAuth 2.0 +授權伺服器中繼資料或 OpenID Connect Discovery)取得;若伺服器不支援此類 endpoint,也可直接在設定中提供。 + +**注意:** 中繼資料應採用 camelCase 格式,符合 mcp-auth 函式庫的偏好。 + +#### 參考 {#see} + + - [OAuth 2.0 授權伺服器中繼資料 (Authorization Server Metadata)](https://datatracker.ietf.org/doc/html/rfc8414) + - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + +*** + +### type {#type} + +```ts +type: AuthServerType; +``` + +授權伺服器(Authorization Server)的類型。 + +#### 參考 {#see} + +[AuthServerType](/references/js/type-aliases/AuthServerType.md) 以取得可能的值。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md new file mode 100644 index 0000000..efb48cd --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md @@ -0,0 +1,45 @@ +--- +sidebar_label: AuthServerConfigError +--- + +# 型別別名:AuthServerConfigError (Type Alias: AuthServerConfigError) + +```ts +type AuthServerConfigError = { + cause?: Error; + code: AuthServerConfigErrorCode; + description: string; +}; +``` + +表示在驗證授權伺服器中繼資料時發生的錯誤。 + +## 屬性 {#properties} + +### cause? {#cause} + +```ts +optional cause: Error; +``` + +錯誤的可選原因,通常是 `Error` 實例,用於提供更多背景資訊。 + +*** + +### code {#code} + +```ts +code: AuthServerConfigErrorCode; +``` + +代表特定驗證錯誤的代碼。 + +*** + +### description {#description} + +```ts +description: string; +``` + +對錯誤的人類可讀描述。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md new file mode 100644 index 0000000..74bcbbd --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: AuthServerConfigErrorCode +--- + +# 型別別名:AuthServerConfigErrorCode (Type Alias: AuthServerConfigErrorCode) + +```ts +type AuthServerConfigErrorCode = + | "invalid_server_metadata" + | "code_response_type_not_supported" + | "authorization_code_grant_not_supported" + | "pkce_not_supported" + | "s256_code_challenge_method_not_supported"; +``` + +驗證授權伺服器中繼資料時可能發生的錯誤代碼 (The codes for errors that can occur when validating the authorization server metadata)。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md new file mode 100644 index 0000000..2cd45b3 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md @@ -0,0 +1,34 @@ +--- +sidebar_label: AuthServerConfigWarning +--- + +# 型別別名:AuthServerConfigWarning + +```ts +type AuthServerConfigWarning = { + code: AuthServerConfigWarningCode; + description: string; +}; +``` + +表示在驗證授權伺服器中繼資料時發生的警告。 + +## 屬性 {#properties} + +### code {#code} + +```ts +code: AuthServerConfigWarningCode; +``` + +代表特定驗證警告的代碼。 + +*** + +### description {#description} + +```ts +description: string; +``` + +對警告的人類可讀描述。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md new file mode 100644 index 0000000..e141dc2 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerConfigWarningCode +--- + +# 型別別名:AuthServerConfigWarningCode (Type Alias: AuthServerConfigWarningCode) + +```ts +type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; +``` + +驗證授權伺服器中繼資料時可能出現的警告代碼。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md new file mode 100644 index 0000000..f90473a --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md @@ -0,0 +1,12 @@ +--- +sidebar_label: AuthServerErrorCode +--- + +# 型別別名:AuthServerErrorCode (Type Alias: AuthServerErrorCode) + +```ts +type AuthServerErrorCode = + | "invalid_server_metadata" + | "invalid_server_config" + | "missing_jwks_uri"; +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md new file mode 100644 index 0000000..84ec125 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md @@ -0,0 +1,31 @@ +--- +sidebar_label: AuthServerModeConfig +--- + +# 型別別名:~~AuthServerModeConfig~~ + +```ts +type AuthServerModeConfig = { + server: AuthServerConfig; +}; +``` + +舊版 MCP 伺服器作為授權伺服器模式的設定。 + +## 已淘汰 {#deprecated} + +請改用 `ResourceServerModeConfig` 設定。 + +## 屬性 {#properties} + +### ~~server~~ {#server} + +```ts +server: AuthServerConfig; +``` + +單一授權伺服器設定。 + +#### 已淘汰 {#deprecated} + +請改用 `protectedResources` 設定。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md new file mode 100644 index 0000000..3c23d46 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md @@ -0,0 +1,17 @@ +--- +sidebar_label: AuthServerSuccessCode +--- + +# 型別別名:AuthServerSuccessCode + +```ts +type AuthServerSuccessCode = + | "server_metadata_valid" + | "dynamic_registration_supported" + | "pkce_supported" + | "s256_code_challenge_method_supported" + | "authorization_code_grant_supported" + | "code_response_type_supported"; +``` + +授權伺服器中繼資料驗證成功時所使用的代碼 (The codes for successful validation of the authorization server metadata)。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md new file mode 100644 index 0000000..c372f2b --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md @@ -0,0 +1,11 @@ +--- +sidebar_label: AuthServerType +--- + +# 型別別名:AuthServerType + +```ts +type AuthServerType = "oauth" | "oidc"; +``` + +授權伺服器 (Authorization server) 的型別。此資訊應由伺服器設定提供,用以指示該伺服器是 OAuth 2.0 還是 OpenID Connect (OIDC) 授權伺服器 (Authorization server)。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md new file mode 100644 index 0000000..0309624 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md @@ -0,0 +1,229 @@ +--- +sidebar_label: AuthorizationServerMetadata +--- + +# 型別別名:AuthorizationServerMetadata + +```ts +type AuthorizationServerMetadata = { + authorization_endpoint: string; + code_challenge_methods_supported?: string[]; + grant_types_supported?: string[]; + introspection_endpoint?: string; + introspection_endpoint_auth_methods_supported?: string[]; + introspection_endpoint_auth_signing_alg_values_supported?: string[]; + issuer: string; + jwks_uri?: string; + op_policy_uri?: string; + op_tos_uri?: string; + registration_endpoint?: string; + response_modes_supported?: string[]; + response_types_supported: string[]; + revocation_endpoint?: string; + revocation_endpoint_auth_methods_supported?: string[]; + revocation_endpoint_auth_signing_alg_values_supported?: string[]; + scopes_supported?: string[]; + service_documentation?: string; + token_endpoint: string; + token_endpoint_auth_methods_supported?: string[]; + token_endpoint_auth_signing_alg_values_supported?: string[]; + ui_locales_supported?: string[]; + userinfo_endpoint?: string; +}; +``` + +OAuth 2.0 授權伺服器中繼資料(Authorization Server Metadata)的結構,定義於 RFC 8414。 + +## 型別宣告 {#type-declaration} + +### authorization\_endpoint {#authorization-endpoint} + +```ts +authorization_endpoint: string; +``` + +授權伺服器的授權端點(authorization endpoint)URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 +除非不支援任何使用授權端點的授權類型(grant types),否則此欄位為必填。 + +#### 參見 {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.1 + +### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} + +```ts +optional code_challenge_methods_supported: string[]; +``` + +JSON 陣列,包含此授權伺服器支援的 PKCE(Proof Key for Code Exchange) +[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] code challenge 方法列表。 + +### grant\_types\_supported? {#grant-types-supported} + +```ts +optional grant_types_supported: string[]; +``` + +JSON 陣列,包含此授權伺服器支援的 OAuth 2.0 授權類型(grant type)值。 +陣列值與「OAuth 2.0 動態用戶端註冊協議」[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]中 `grant_types` 參數所用值相同。 +若省略,預設值為 `["authorization_code", "implicit"]`。 + +### introspection\_endpoint? {#introspection-endpoint} + +```ts +optional introspection_endpoint: string; +``` + +授權伺服器的 OAuth 2.0 introspection 端點 URL +[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]。 + +### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} + +```ts +optional introspection_endpoint_auth_methods_supported: string[]; +``` + +### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} + +```ts +optional introspection_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +授權伺服器的簽發者(Issuer)識別符,為一個使用 `https` 協定且無查詢或片段組件的 URL。 + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +授權伺服器 JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] +文件的 URL。該文件包含用戶端用於驗證授權伺服器簽章的簽名金鑰。此 URL 必須使用 `https` 協定。 + +### op\_policy\_uri? {#op-policy-uri} + +```ts +optional op_policy_uri: string; +``` + +### op\_tos\_uri? {#op-tos-uri} + +```ts +optional op_tos_uri: string; +``` + +### registration\_endpoint? {#registration-endpoint} + +```ts +optional registration_endpoint: string; +``` + +授權伺服器的 OAuth 2.0 動態用戶端註冊端點 URL +[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]。 + +### response\_modes\_supported? {#response-modes-supported} + +```ts +optional response_modes_supported: string[]; +``` + +JSON 陣列,包含此授權伺服器支援的 OAuth 2.0 `response_mode` 值,詳見「OAuth 2.0 多重回應型態編碼實踐」 +[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]。 + +若省略,預設為 `["query", "fragment"]`。回應模式值 `"form_post"` 亦定義於「OAuth 2.0 表單回傳回應模式」 +[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]。 + +### response\_types\_supported {#response-types-supported} + +```ts +response_types_supported: string[]; +``` + +JSON 陣列,包含此授權伺服器支援的 OAuth 2.0 `response_type` 值。 +陣列值與「OAuth 2.0 動態用戶端註冊協議」[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]中 `response_types` 參數所用值相同。 + +### revocation\_endpoint? {#revocation-endpoint} + +```ts +optional revocation_endpoint: string; +``` + +授權伺服器的 OAuth 2.0 撤銷端點(revocation endpoint)URL +[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]。 + +### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} + +```ts +optional revocation_endpoint_auth_methods_supported: string[]; +``` + +### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} + +```ts +optional revocation_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +JSON 陣列,包含此授權伺服器支援的 OAuth 2.0 `scope` 值。 +[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] + +### service\_documentation? {#service-documentation} + +```ts +optional service_documentation: string; +``` + +### token\_endpoint {#token-endpoint} + +```ts +token_endpoint: string; +``` + +授權伺服器的權杖端點(token endpoint)URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 +除非僅支援 implicit 授權類型,否則此欄位為必填。 + +#### 參見 {#see} + +https://rfc-editor.org/rfc/rfc6749#section-3.2 + +### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} + +```ts +optional token_endpoint_auth_methods_supported: string[]; +``` + +### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} + +```ts +optional token_endpoint_auth_signing_alg_values_supported: string[]; +``` + +### ui\_locales\_supported? {#ui-locales-supported} + +```ts +optional ui_locales_supported: string[]; +``` + +### userinfo\_endpoint? {#userinfo-endpoint} + +```ts +optional userinfo_endpoint: string; +``` + +OpenID Connect [userinfo 端點](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo)的 URL。 +此端點用於取得已驗證使用者的資訊。 + +## 參見 {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md new file mode 100644 index 0000000..85f5b54 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md @@ -0,0 +1,107 @@ +--- +sidebar_label: BearerAuthConfig +--- + +# 型別別名:BearerAuthConfig (Type Alias: BearerAuthConfig) + +```ts +type BearerAuthConfig = { + audience?: string; + issuer: | string + | ValidateIssuerFunction; + requiredScopes?: string[]; + resource?: string; + showErrorDetails?: boolean; + verifyAccessToken: VerifyAccessTokenFunction; +}; +``` + +## 屬性 (Properties) {#properties} + +### audience? {#audience} + +```ts +optional audience: string; +``` + +存取權杖 (Access token) 預期的受眾 (Audience)(`aud` 宣告 (claim))。這通常是該權杖預期要存取的資源伺服器(API)。如果未提供,將略過受眾檢查。 + +**注意:** 如果你的授權伺服器不支援資源標示符 (Resource Indicators, RFC 8707),可以省略此欄位,因為受眾可能不適用。 + +#### 參考 {#see} + +https://datatracker.ietf.org/doc/html/rfc8707 + +*** + +### issuer {#issuer} + +```ts +issuer: + | string + | ValidateIssuerFunction; +``` + +代表有效簽發者 (Issuer) 的字串,或用於驗證存取權杖 (Access token) 簽發者的函式。 + +如果提供字串,將作為預期的簽發者值進行直接比對。 + +如果提供函式,應依據 [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 的規則驗證簽發者。 + +#### 參考 {#see} + +更多驗證函式細節請見 [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md)。 + +*** + +### requiredScopes? {#requiredscopes} + +```ts +optional requiredScopes: string[]; +``` + +存取權杖 (Access token) 必須具備的權限範圍 (Scopes) 陣列。如果權杖未包含所有這些權限範圍,將拋出錯誤。 + +**注意:** 處理器會檢查權杖中的 `scope` 宣告 (claim),其內容可能為以空格分隔的字串或字串陣列,取決於授權伺服器的實作方式。如果 `scope` 宣告不存在,則會檢查 `scopes` 宣告(若有)。 + +*** + +### resource? {#resource} + +```ts +optional resource: string; +``` + +受保護資源的識別符。若提供此欄位,處理器將使用針對該資源所設定的授權伺服器來驗證收到的權杖。當與 `protectedResources` 設定搭配使用時,此欄位為必填。 + +*** + +### showErrorDetails? {#showerrordetails} + +```ts +optional showErrorDetails: boolean; +``` + +是否在回應中顯示詳細錯誤資訊。這對於開發階段除錯很有幫助,但在生產環境中應關閉,以避免洩漏敏感資訊。 + +#### 預設值 (Default) {#default} + +```ts +false +``` + +*** + +### verifyAccessToken {#verifyaccesstoken} + +```ts +verifyAccessToken: VerifyAccessTokenFunction; +``` + +用於驗證存取權杖 (Access token) 的函式型別。 + +此函式若權杖無效應拋出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md),若權杖有效則回傳 AuthInfo 物件。 + +#### 參考 {#see} + +更多細節請見 [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md)。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md new file mode 100644 index 0000000..2fc8402 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md @@ -0,0 +1,16 @@ +--- +sidebar_label: BearerAuthErrorCode +--- + +# 型別別名:BearerAuthErrorCode (Type Alias: BearerAuthErrorCode) + +```ts +type BearerAuthErrorCode = + | "missing_auth_header" + | "invalid_auth_header_format" + | "missing_bearer_token" + | "invalid_issuer" + | "invalid_audience" + | "missing_required_scopes" + | "invalid_token"; +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md new file mode 100644 index 0000000..b903332 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md @@ -0,0 +1,179 @@ +--- +sidebar_label: CamelCaseAuthorizationServerMetadata +--- + +# 型別別名:CamelCaseAuthorizationServerMetadata + +```ts +type CamelCaseAuthorizationServerMetadata = { + authorizationEndpoint: string; + codeChallengeMethodsSupported?: string[]; + grantTypesSupported?: string[]; + introspectionEndpoint?: string; + introspectionEndpointAuthMethodsSupported?: string[]; + introspectionEndpointAuthSigningAlgValuesSupported?: string[]; + issuer: string; + jwksUri?: string; + opPolicyUri?: string; + opTosUri?: string; + registrationEndpoint?: string; + responseModesSupported?: string[]; + responseTypesSupported: string[]; + revocationEndpoint?: string; + revocationEndpointAuthMethodsSupported?: string[]; + revocationEndpointAuthSigningAlgValuesSupported?: string[]; + scopesSupported?: string[]; + serviceDocumentation?: string; + tokenEndpoint: string; + tokenEndpointAuthMethodsSupported?: string[]; + tokenEndpointAuthSigningAlgValuesSupported?: string[]; + uiLocalesSupported?: string[]; + userinfoEndpoint?: string; +}; +``` + +OAuth 2.0 授權伺服器中繼資料(Authorization Server Metadata)型別的 camelCase 版本。 + +## 型別宣告 {#type-declaration} + +### authorizationEndpoint {#authorizationendpoint} + +```ts +authorizationEndpoint: string; +``` + +### codeChallengeMethodsSupported? {#codechallengemethodssupported} + +```ts +optional codeChallengeMethodsSupported: string[]; +``` + +### grantTypesSupported? {#granttypessupported} + +```ts +optional grantTypesSupported: string[]; +``` + +### introspectionEndpoint? {#introspectionendpoint} + +```ts +optional introspectionEndpoint: string; +``` + +### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} + +```ts +optional introspectionEndpointAuthMethodsSupported: string[]; +``` + +### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} + +```ts +optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### issuer {#issuer} + +```ts +issuer: string; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### opPolicyUri? {#oppolicyuri} + +```ts +optional opPolicyUri: string; +``` + +### opTosUri? {#optosuri} + +```ts +optional opTosUri: string; +``` + +### registrationEndpoint? {#registrationendpoint} + +```ts +optional registrationEndpoint: string; +``` + +### responseModesSupported? {#responsemodessupported} + +```ts +optional responseModesSupported: string[]; +``` + +### responseTypesSupported {#responsetypessupported} + +```ts +responseTypesSupported: string[]; +``` + +### revocationEndpoint? {#revocationendpoint} + +```ts +optional revocationEndpoint: string; +``` + +### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} + +```ts +optional revocationEndpointAuthMethodsSupported: string[]; +``` + +### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} + +```ts +optional revocationEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### serviceDocumentation? {#servicedocumentation} + +```ts +optional serviceDocumentation: string; +``` + +### tokenEndpoint {#tokenendpoint} + +```ts +tokenEndpoint: string; +``` + +### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} + +```ts +optional tokenEndpointAuthMethodsSupported: string[]; +``` + +### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} + +```ts +optional tokenEndpointAuthSigningAlgValuesSupported: string[]; +``` + +### uiLocalesSupported? {#uilocalessupported} + +```ts +optional uiLocalesSupported: string[]; +``` + +### userinfoEndpoint? {#userinfoendpoint} + +```ts +optional userinfoEndpoint: string; +``` + +## 參見 {#see} + +[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) 以取得原始型別與欄位資訊。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md new file mode 100644 index 0000000..913b073 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md @@ -0,0 +1,123 @@ +--- +sidebar_label: CamelCaseProtectedResourceMetadata +--- + +# 型別別名:CamelCaseProtectedResourceMetadata + +```ts +type CamelCaseProtectedResourceMetadata = { + authorizationDetailsTypesSupported?: string[]; + authorizationServers?: string[]; + bearerMethodsSupported?: string[]; + dpopBoundAccessTokensRequired?: boolean; + dpopSigningAlgValuesSupported?: string[]; + jwksUri?: string; + resource: string; + resourceDocumentation?: string; + resourceName?: string; + resourcePolicyUri?: string; + resourceSigningAlgValuesSupported?: string[]; + resourceTosUri?: string; + scopesSupported?: string[]; + signedMetadata?: string; + tlsClientCertificateBoundAccessTokens?: boolean; +}; +``` + +OAuth 2.0 Protected Resource Metadata 型別的 camelCase 版本。 + +## 型別宣告 {#type-declaration} + +### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} + +```ts +optional authorizationDetailsTypesSupported: string[]; +``` + +### authorizationServers? {#authorizationservers} + +```ts +optional authorizationServers: string[]; +``` + +### bearerMethodsSupported? {#bearermethodssupported} + +```ts +optional bearerMethodsSupported: string[]; +``` + +### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} + +```ts +optional dpopBoundAccessTokensRequired: boolean; +``` + +### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} + +```ts +optional dpopSigningAlgValuesSupported: string[]; +``` + +### jwksUri? {#jwksuri} + +```ts +optional jwksUri: string; +``` + +### resource {#resource} + +```ts +resource: string; +``` + +### resourceDocumentation? {#resourcedocumentation} + +```ts +optional resourceDocumentation: string; +``` + +### resourceName? {#resourcename} + +```ts +optional resourceName: string; +``` + +### resourcePolicyUri? {#resourcepolicyuri} + +```ts +optional resourcePolicyUri: string; +``` + +### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} + +```ts +optional resourceSigningAlgValuesSupported: string[]; +``` + +### resourceTosUri? {#resourcetosuri} + +```ts +optional resourceTosUri: string; +``` + +### scopesSupported? {#scopessupported} + +```ts +optional scopesSupported: string[]; +``` + +### signedMetadata? {#signedmetadata} + +```ts +optional signedMetadata: string; +``` + +### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} + +```ts +optional tlsClientCertificateBoundAccessTokens: boolean; +``` + +## 參見 {#see} + +[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) 以取得原始型別與欄位資訊。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md new file mode 100644 index 0000000..7f65917 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md @@ -0,0 +1,55 @@ +--- +sidebar_label: MCPAuthBearerAuthErrorDetails +--- + +# 型別別名:MCPAuthBearerAuthErrorDetails + +```ts +type MCPAuthBearerAuthErrorDetails = { + actual?: unknown; + cause?: unknown; + expected?: unknown; + missingScopes?: string[]; + uri?: URL; +}; +``` + +## 屬性 {#properties} + +### actual? {#actual} + +```ts +optional actual: unknown; +``` + +*** + +### cause? {#cause} + +```ts +optional cause: unknown; +``` + +*** + +### expected? {#expected} + +```ts +optional expected: unknown; +``` + +*** + +### missingScopes? {#missingscopes} + +```ts +optional missingScopes: string[]; +``` + +*** + +### uri? {#uri} + +```ts +optional uri: URL; +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md new file mode 100644 index 0000000..77ab46b --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md @@ -0,0 +1,13 @@ +--- +sidebar_label: MCPAuthConfig +--- + +# 型別別名:MCPAuthConfig (Type Alias: MCPAuthConfig) + +```ts +type MCPAuthConfig = + | AuthServerModeConfig + | ResourceServerModeConfig; +``` + +[MCPAuth](/references/js/classes/MCPAuth.md) 類別的設定,支援單一舊版 `authorization server` 或 `resource server` 設定。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md new file mode 100644 index 0000000..6038b98 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md @@ -0,0 +1,9 @@ +--- +sidebar_label: MCPAuthTokenVerificationErrorCode +--- + +# 型別別名:MCPAuthTokenVerificationErrorCode (Type Alias: MCPAuthTokenVerificationErrorCode) + +```ts +type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md new file mode 100644 index 0000000..00da031 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md @@ -0,0 +1,149 @@ +--- +sidebar_label: ProtectedResourceMetadata +--- + +# 型別別名:ProtectedResourceMetadata + +```ts +type ProtectedResourceMetadata = { + authorization_details_types_supported?: string[]; + authorization_servers?: string[]; + bearer_methods_supported?: string[]; + dpop_bound_access_tokens_required?: boolean; + dpop_signing_alg_values_supported?: string[]; + jwks_uri?: string; + resource: string; + resource_documentation?: string; + resource_name?: string; + resource_policy_uri?: string; + resource_signing_alg_values_supported?: string[]; + resource_tos_uri?: string; + scopes_supported?: string[]; + signed_metadata?: string; + tls_client_certificate_bound_access_tokens?: boolean; +}; +``` + +OAuth 2.0 受保護資源中繼資料的結構描述。 + +## 型別宣告 {#type-declaration} + +### authorization\_details\_types\_supported? {#authorization-details-types-supported} + +```ts +optional authorization_details_types_supported: string[]; +``` + +在使用 authorization_details 請求參數時支援的授權細節類型值。 + +### authorization\_servers? {#authorization-servers} + +```ts +optional authorization_servers: string[]; +``` + +可與此受保護資源搭配使用的 OAuth 授權伺服器簽發者 (Issuer) 識別碼清單。 + +### bearer\_methods\_supported? {#bearer-methods-supported} + +```ts +optional bearer_methods_supported: string[]; +``` + +支援的 OAuth 2.0 bearer 權杖 (Access token) 傳遞方式。可選值:["header", "body", "query"]。 + +### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} + +```ts +optional dpop_bound_access_tokens_required: boolean; +``` + +此受保護資源是否始終要求 DPoP 綁定的存取權杖 (Access token)。 + +### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} + +```ts +optional dpop_signing_alg_values_supported: string[]; +``` + +用於驗證 DPoP 證明 JWT 的支援 JWS 演算法。 + +### jwks\_uri? {#jwks-uri} + +```ts +optional jwks_uri: string; +``` + +受保護資源的 JSON Web Key (JWK) Set 文件的 URL。此文件包含可用於驗證此受保護資源回應或資料數位簽章的公鑰。這與授權伺服器的 jwks_uri 不同,後者用於權杖驗證。當受保護資源對回應進行簽章時,客戶端可透過此 URL 取得公鑰,以驗證收到資料的真實性與完整性。 + +### resource {#resource} + +```ts +resource: string; +``` + +受保護資源的資源標示符 (Resource identifier)。 + +### resource\_documentation? {#resource-documentation} + +```ts +optional resource_documentation: string; +``` + +包含使用此受保護資源開發者文件的 URL。 + +### resource\_name? {#resource-name} + +```ts +optional resource_name: string; +``` + +用於顯示給終端使用者的人類可讀受保護資源名稱。 + +### resource\_policy\_uri? {#resource-policy-uri} + +```ts +optional resource_policy_uri: string; +``` + +包含受保護資源資料使用需求相關資訊的 URL。 + +### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} + +```ts +optional resource_signing_alg_values_supported: string[]; +``` + +受保護資源用於簽署資源回應的支援 JWS 簽章演算法。 + +### resource\_tos\_uri? {#resource-tos-uri} + +```ts +optional resource_tos_uri: string; +``` + +包含受保護資源服務條款的 URL。 + +### scopes\_supported? {#scopes-supported} + +```ts +optional scopes_supported: string[]; +``` + +在授權請求中用於存取此受保護資源的權限範圍 (Scope) 值清單。 + +### signed\_metadata? {#signed-metadata} + +```ts +optional signed_metadata: string; +``` + +包含中繼資料參數作為宣告 (Claim) 的已簽署 JWT。此 JWT 必須使用 JWS 簽署,並包含 'iss' 宣告。此欄位提供一種密碼學方式驗證中繼資料本身的真實性。可使用 `jwks_uri` 端點提供的公鑰驗證簽章。若存在,已簽署中繼資料中的值優先於本文件中對應的純 JSON 值,有助於防止資源中繼資料被竄改。 + +### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} + +```ts +optional tls_client_certificate_bound_access_tokens: boolean; +``` + +此受保護資源是否支援 mutual-TLS 用戶端憑證綁定的存取權杖 (Access token)。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md new file mode 100644 index 0000000..a551dad --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md @@ -0,0 +1,23 @@ +--- +sidebar_label: ResourceServerModeConfig +--- + +# 型別別名:ResourceServerModeConfig (Type Alias: ResourceServerModeConfig) + +```ts +type ResourceServerModeConfig = { + protectedResources: ResourceServerConfig | ResourceServerConfig[]; +}; +``` + +MCP 伺服器作為資源伺服器模式的設定。 + +## 屬性 (Properties) {#properties} + +### protectedResources {#protectedresources} + +```ts +protectedResources: ResourceServerConfig | ResourceServerConfig[]; +``` + +單一資源伺服器設定或其陣列。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md new file mode 100644 index 0000000..05e66bd --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md @@ -0,0 +1,30 @@ +--- +sidebar_label: ValidateIssuerFunction +--- + +# 型別別名:ValidateIssuerFunction() + +```ts +type ValidateIssuerFunction = (tokenIssuer: string) => void; +``` + +用於驗證存取權杖 (Access token) 簽發者 (Issuer) 的函式型別。 + +當簽發者 (Issuer) 無效時,此函式應拋出帶有 'invalid_issuer' 代碼的 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)。簽發者應根據以下條件進行驗證: + +1. MCP-Auth 的授權伺服器 (Authorization server) 中設定的授權伺服器元資料 +2. 受保護資源 (Protected resource) 元資料中列出的授權伺服器 + +## 參數 {#parameters} + +### tokenIssuer {#tokenissuer} + +`string` + +## 回傳值 {#returns} + +`void` + +## 拋出例外 {#throws} + +當簽發者 (Issuer) 未被識別或無效時。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md new file mode 100644 index 0000000..1b1252a --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md @@ -0,0 +1,36 @@ +--- +sidebar_label: VerifyAccessTokenFunction +--- + +# 型別別名:VerifyAccessTokenFunction() + +```ts +type VerifyAccessTokenFunction = (token: string) => MaybePromise; +``` + +用於驗證存取權杖 (Access token) 的函式型別。 + +此函式若權杖無效,應拋出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md); +若權杖有效,則回傳 AuthInfo 物件。 + +舉例來說,若你有一個 JWT 驗證函式,至少應檢查權杖的簽章、驗證其過期時間,並擷取必要的宣告 (Claims) 以回傳 `AuthInfo` 物件。 + +**注意:** 權杖中的下列欄位無需自行驗證,因為這些會由處理器自動檢查: + +- `iss`(簽發者 (Issuer)) +- `aud`(受眾 (Audience)) +- `scope`(權限範圍 (Scopes)) + +## 參數 {#parameters} + +### token {#token} + +`string` + +要驗證的存取權杖 (Access token) 字串。 + +## 回傳值 {#returns} + +`MaybePromise`\<`AuthInfo`\> + +一個 Promise,當權杖有效時解析為 AuthInfo 物件,或同步回傳值。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md new file mode 100644 index 0000000..bd53bec --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md @@ -0,0 +1,11 @@ +--- +sidebar_label: VerifyAccessTokenMode +--- + +# 型別別名:VerifyAccessTokenMode + +```ts +type VerifyAccessTokenMode = "jwt"; +``` + +`bearerAuth` 支援的內建驗證模式。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md new file mode 100644 index 0000000..91f5bfc --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: authServerErrorDescription +--- + +# 變數:authServerErrorDescription (authServerErrorDescription) + +```ts +const authServerErrorDescription: Readonly>; +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md new file mode 100644 index 0000000..01b8d5c --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: authorizationServerMetadataSchema +--- + +# 變數:authorizationServerMetadataSchema + +```ts +const authorizationServerMetadataSchema: ZodObject; +``` + +Zod schema,對應 RFC 8414 中定義的 OAuth 2.0 授權伺服器中繼資料(Authorization Server Metadata)。 + +## 參考 {#see} + +https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md new file mode 100644 index 0000000..ef9c398 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: bearerAuthErrorDescription +--- + +# 變數:bearerAuthErrorDescription (bearerAuthErrorDescription) + +```ts +const bearerAuthErrorDescription: Readonly>; +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md new file mode 100644 index 0000000..a7112c2 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseAuthorizationServerMetadataSchema +--- + +# 變數:camelCaseAuthorizationServerMetadataSchema + +```ts +const camelCaseAuthorizationServerMetadataSchema: ZodObject; +``` + +OAuth 2.0 授權伺服器中繼資料(Authorization Server Metadata)Zod schema 的 camelCase 版本。 + +## 參見 {#see} + +[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) 以取得原始 schema 及欄位資訊。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md new file mode 100644 index 0000000..a8fbb01 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md @@ -0,0 +1,15 @@ +--- +sidebar_label: camelCaseProtectedResourceMetadataSchema +--- + +# 變數:camelCaseProtectedResourceMetadataSchema + +```ts +const camelCaseProtectedResourceMetadataSchema: ZodObject; +``` + +OAuth 2.0 受保護資源中繼資料 Zod schema 的 camelCase 版本。 + +## 參見 {#see} + +[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) 以瞭解原始 schema 與欄位資訊。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md new file mode 100644 index 0000000..822b791 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md @@ -0,0 +1,9 @@ +--- +sidebar_label: defaultValues +--- + +# 變數:defaultValues (defaultValues) + +```ts +const defaultValues: Readonly>; +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md new file mode 100644 index 0000000..fcd8799 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md @@ -0,0 +1,11 @@ +--- +sidebar_label: protectedResourceMetadataSchema +--- + +# 變數:protectedResourceMetadataSchema + +```ts +const protectedResourceMetadataSchema: ZodObject; +``` + +用於 OAuth 2.0 受保護資源中繼資料(Protected Resource Metadata)的 Zod schema。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md new file mode 100644 index 0000000..ff1fe69 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md @@ -0,0 +1,12 @@ +--- +sidebar_label: serverMetadataPaths +--- + +# 變數:serverMetadataPaths (serverMetadataPaths) + +```ts +const serverMetadataPaths: Readonly<{ + oauth: "/.well-known/oauth-authorization-server"; + oidc: "/.well-known/openid-configuration"; +}>; +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md new file mode 100644 index 0000000..0c0db40 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md @@ -0,0 +1,9 @@ +--- +sidebar_label: 權杖驗證錯誤描述 (tokenVerificationErrorDescription) +--- + +# 變數:權杖驗證錯誤描述 (tokenVerificationErrorDescription) + +```ts +const tokenVerificationErrorDescription: Readonly>; +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md new file mode 100644 index 0000000..5c85420 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md @@ -0,0 +1,9 @@ +--- +sidebar_label: validateServerConfig +--- + +# 變數:validateServerConfig (validateServerConfig) + +```ts +const validateServerConfig: ValidateServerConfig; +``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx b/i18n/zh-TW/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx new file mode 100644 index 0000000..00f677a --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/snippets/_get-started-code.mdx @@ -0,0 +1,73 @@ +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + + + + +```python +mcp = FastMCP("MyMCPServer") +resource_identifier = "https://api.example.com" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_identifier, + authorization_servers=[fetch_server_config('', AuthServerType.OIDC)], + scopes_supported=["read", "write"], + ) + ) +) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + Mount('/', app=mcp.sse_app(), middleware=[Middleware( + mcp_auth.bearer_auth_middleware("jwt", + resource=resource_identifier, + audience=resource_identifier, + required_scopes=["read", "write"] + ) + )]) + ] +) + +@mcp.tool() +def whoami(): + return mcp_auth.auth_info.claims +``` + + + + +```ts +const server = new McpServer(/* ... */); +const resourceIdentifier = 'https://api.example.com'; + +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceIdentifier, + authorizationServers: [await fetchServerConfig('', { type: 'oidc' })], + scopesSupported: ['read', 'write'], + } + } +}); + +const app = express(); + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +app.use(mcpAuth.bearerAuth('jwt', { + resource: resourceIdentifier, + audience: resourceIdentifier, + requiredScopes: ['read', 'write'] +})); + +server.tool('whoami', ({ authInfo }) => { + return authInfo.claims; +}); +``` + + + diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx b/i18n/zh-TW/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx new file mode 100644 index 0000000..340c9e5 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/tutorials/todo-manager/README.mdx @@ -0,0 +1,1393 @@ +--- +sidebar_position: 2 +sidebar_label: '教學:打造一個待辦事項管理器' +--- + +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + + +# 教學:打造一個待辦事項管理器 + +在本教學中,我們將建立一個具備使用者驗證 (Authentication) 與授權 (Authorization) 的 todo manager MCP 伺服器。根據最新的 MCP 規範,我們的 MCP 伺服器將作為 OAuth 2.0 **資源伺服器 (Resource Server)**,負責驗證存取權杖 (Access token) 並強制執行基於權限範圍 (Scope) 的權限。 + +完成本教學後,你將擁有: + +- ✅ 基本瞭解如何在 MCP 伺服器中設定角色型存取控制 (RBAC, Role-based access control) +- ✅ 一個作為資源伺服器 (Resource Server) 的 MCP 伺服器,能消耗由授權伺服器 (Authorization Server) 發出的存取權杖 (Access token) +- ✅ 一個可運作的基於權限範圍 (Scope) 的權限控管實作,適用於 todo 操作 + +## 概覽 \{#overview} + +本教學將包含以下元件: + +- **MCP 用戶端 (MCP Inspector)**:一個用於測試 MCP 伺服器的視覺化工具,作為 OAuth 2.0 / OIDC 用戶端。它會啟動授權流程,並向 MCP 伺服器發送帶有存取權杖 (Access token) 的請求。 +- **授權伺服器 (Authorization Server)**:一個 OAuth 2.1 或 OpenID Connect 簽發者 (Issuer),負責管理使用者身分、驗證使用者,並向授權用戶端發出帶有適當權限範圍 (Scope) 的存取權杖 (Access token)。 +- **MCP 伺服器 (Resource Server)**:根據最新 MCP 規範,MCP 伺服器在 OAuth 2.0 架構中作為資源伺服器 (Resource Server)。它驗證授權伺服器發出的存取權杖 (Access token),並根據權限範圍 (Scope) 強制執行 todo 操作的權限。 + +此架構遵循標準 OAuth 2.0 流程: + +- **MCP Inspector** 代表使用者請求受保護資源 +- **授權伺服器 (Authorization Server)** 驗證使用者並發出存取權杖 (Access token) +- **MCP 伺服器 (Resource Server)** 驗證權杖並根據授權權限提供受保護資源 + +以下是這些元件互動的高階流程圖: + +```mermaid +sequenceDiagram + autonumber + participant Client as MCP Inspector
(OAuth 用戶端) + participant RS as MCP 伺服器
(資源伺服器) + participant AS as 授權伺服器 (Authorization Server) + + Client->>RS: MCP 請求(無權杖) + RS-->>Client: 401 未授權 (WWW-Authenticate) + Note over Client: 從 WWW-Authenticate 標頭
擷取 resource_metadata URL + + Client->>RS: GET /.well-known/oauth-protected-resource (resource_metadata) + RS-->>Client: 受保護資源中繼資料
(包含授權伺服器 URL) + + Client->>AS: GET /.well-known/oauth-authorization-server + AS-->>Client: 授權伺服器中繼資料 + Client->>AS: OAuth 授權(登入與同意) + AS-->>Client: 存取權杖 (Access token) + + Client->>RS: MCP 請求 (Authorization: Bearer ) + RS->>RS: 驗證存取權杖有效且已授權 + RS-->>Client: MCP 回應 +``` + +## 瞭解你的授權伺服器 \{#understand-your-authorization-server} + +### 具備權限範圍 (Scope) 的存取權杖 (Access tokens) \{#access-tokens-with-scopes} + +若要在 MCP 伺服器中實作 [角色型存取控制 (RBAC)](https://auth.wiki/rbac),你的授權伺服器需支援發出帶有權限範圍 (Scope) 的存取權杖 (Access token)。權限範圍 (Scope) 代表使用者被授予的權限。 + + + + +[Logto](https://logto.io) 透過其 API 資源 (API resources)(符合 [RFC 8707: OAuth 2.0 資源標示符 (Resource Indicators)](https://datatracker.ietf.org/doc/html/rfc8707))與角色 (Roles) 功能提供 RBAC 支援。設定方式如下: + +1. 登入 [Logto Console](https://cloud.logto.io)(或你的自架 Logto Console) + +2. 建立 API 資源與權限範圍 (Scope): + + - 前往「API 資源」 + - 建立一個名為「Todo Manager」的新 API 資源 + - 新增以下權限範圍 (Scope): + - `create:todos`:「建立新的待辦事項」 + - `read:todos`:「讀取所有待辦事項」 + - `delete:todos`:「刪除任一待辦事項」 + +3. 建立角色(建議以便管理): + + - 前往「角色」 + - 建立「Admin」角色並指派所有權限範圍(`create:todos`、`read:todos`、`delete:todos`) + - 建立「User」角色並僅指派 `create:todos` 權限範圍 + +4. 指派權限: + - 前往「使用者」 + - 選擇一位使用者 + - 你可以: + - 在「角色」分頁指派角色(建議) + - 或直接在「權限」分頁指派權限範圍 + +權限範圍 (Scope) 會以空格分隔字串的形式包含在 JWT 存取權杖 (Access token) 的 `scope` 宣告 (Claim) 中。 + + + + +OAuth 2.0 / OIDC 簽發者 (Issuer) 通常支援基於權限範圍 (Scope) 的存取控制。實作 RBAC 時: + +1. 在授權伺服器中定義所需的權限範圍 (Scope) +2. 設定用戶端在授權流程中請求這些權限範圍 +3. 確保授權伺服器在存取權杖 (Access token) 中包含授予的權限範圍 +4. 權限範圍通常會包含在 JWT 存取權杖的 `scope` 宣告 (Claim) 中 + +請查閱你的簽發者 (Issuer) 文件以瞭解: + +- 如何定義與管理權限範圍 (Scope) +- 權限範圍如何包含在存取權杖 (Access token) 中 +- 是否有額外的 RBAC 功能如角色管理 + + + + +### 權杖驗證與權限檢查 \{#validating-tokens-and-checking-permissions} + +根據最新 MCP 規範,MCP 伺服器在 OAuth 2.0 架構中作為 **資源伺服器 (Resource Server)**。作為資源伺服器,MCP 伺服器有以下職責: + +1. **權杖驗證**:驗證從 MCP 用戶端收到的存取權杖 (Access token) 的真實性與完整性 +2. **權限範圍強制執行**:從存取權杖中擷取並驗證權限範圍 (Scope),以決定用戶端被授權執行哪些操作 +3. **資源保護**:僅在用戶端提供有效且具備足夠權限的權杖時,才提供受保護資源(執行工具) + +當 MCP 伺服器收到請求時,會執行以下驗證流程: + +1. 從 `Authorization` 標頭擷取存取權杖(Bearer 權杖格式) +2. 驗證存取權杖的簽章與有效期限 +3. 從已驗證的權杖中擷取權限範圍與使用者資訊 +4. 檢查權杖是否具備執行請求操作所需的權限範圍 + +例如,若使用者要建立新的待辦事項,其存取權杖必須包含 `create:todos` 權限範圍。以下為資源伺服器驗證流程: + +```mermaid +sequenceDiagram + participant Client as MCP 用戶端 + participant Server as MCP 伺服器
(資源伺服器) + participant Auth as 授權伺服器 (Authorization Server) + + Client->>Server: 帶存取權杖的請求
(Authorization: Bearer ) + + alt JWT 驗證(推薦) + Server->>Auth: 取得 JWKS(若未快取) + Auth-->>Server: 回傳 JWKS + Server->>Server: 本地驗證 JWT 簽章與宣告 + else 權杖內省(備用) + Server->>Auth: POST /introspect
(token=access_token) + Auth-->>Server: 回傳權杖資訊
(active, scope, user_id, 等) + end + + Server->>Server: 從已驗證權杖擷取權限範圍與使用者上下文 + + alt 具備所需權限範圍 + Server->>Server: 執行請求操作 + Server->>Client: 回傳操作結果 + else 欠缺所需權限範圍 + Server->>Client: 回傳 403 Forbidden
(insufficient_scope error) + end +``` + +### 動態用戶端註冊 (Dynamic Client Registration) \{#dynamic-client-registration} + +本教學不強制要求動態用戶端註冊,但若你想自動化 MCP 用戶端在授權伺服器的註冊流程,可參考 [是否需要動態用戶端註冊?](/provider-list#is-dcr-required) 以取得更多資訊。 + +## 瞭解 todo manager 中的 RBAC \{#understand-rbac-in-todo-manager} + +為了示範,我們會在 todo manager MCP 伺服器中實作一個簡單的角色型存取控制 (RBAC) 系統。這將讓你瞭解 RBAC 的基本原理,同時保持實作簡潔。 + +:::note +雖然本教學以 RBAC 為基礎進行權限範圍管理,但需注意並非所有驗證 (Authentication) 簽發者 (Issuer) 都透過角色來管理權限範圍。有些簽發者可能有自己獨特的存取控制與權限管理機制。 +::: + +### 工具與權限範圍 (Scope) \{#tools-and-scopes} + +我們的 todo manager MCP 伺服器提供三個主要工具: + +- `create-todo`:建立新的待辦事項 +- `get-todos`:列出所有待辦事項 +- `delete-todo`:根據 ID 刪除待辦事項 + +為了控管這些工具的存取,我們定義以下權限範圍 (Scope): + +- `create:todos`:允許建立新的待辦事項 +- `delete:todos`:允許刪除現有待辦事項 +- `read:todos`:允許查詢並取得所有待辦事項列表 + +### 角色與權限 \{#roles-and-permissions} + +我們將定義兩個不同存取層級的角色: + +| 角色 | create:todos | read:todos | delete:todos | +| ----- | ------------ | ---------- | ------------ | +| Admin | ✅ | ✅ | ✅ | +| User | ✅ | | | + +- **User**:一般使用者,可建立待辦事項,僅能檢視或刪除自己的待辦事項 +- **Admin**:管理員,可建立、檢視並刪除所有待辦事項,不論擁有者為誰 + +### 資源擁有權 \{#resource-ownership} + +雖然上表明確列出每個角色被指派的權限範圍 (Scope),但還有一個重要的資源擁有權原則: + +- **User** 沒有 `read:todos` 或 `delete:todos` 權限範圍,但仍可: + - 檢視自己的待辦事項 + - 刪除自己的待辦事項 +- **Admin** 具備完整權限(`read:todos` 與 `delete:todos`),可: + - 檢視系統中所有待辦事項 + - 刪除任何待辦事項,不論擁有者為誰 + +這展現了 RBAC 系統中常見的模式:資源擁有權會隱含授予使用者對自己資源的權限,而管理角色則獲得對所有資源的明確權限。 + +:::tip 深入學習 +想更深入瞭解 RBAC 概念與最佳實踐,請參考 [精通 RBAC:完整實戰範例](https://blog.logto.io/mastering-rbac)。 +::: + +## 在你的簽發者 (Issuer) 中設定授權 (Authorization) \{#configure-authorization-in-your-provider} + +要實作上述存取控制系統,你需要在授權伺服器設定所需的權限範圍 (Scope)。以下是不同簽發者的設定方式: + + + + +[Logto](https://logto.io) 透過 API 資源與角色功能提供 RBAC 支援。設定方式如下: + +1. 登入 [Logto Console](https://cloud.logto.io)(或你的自架 Logto Console) + +2. 建立 API 資源與權限範圍 (Scope): + + - 前往「API 資源」 + - 建立一個名為「Todo Manager」的新 API 資源,並將 `http://localhost:3001` 設為資源標示符 (Resource indicator)。 + - **重要**:資源標示符必須與你的 MCP 伺服器 URL 相符。本教學使用 `http://localhost:3001`,因 MCP 伺服器運行於 3001 埠。正式環境請使用實際 MCP 伺服器 URL(如 `https://your-mcp-server.example.com`)。 + - 建立以下權限範圍 (Scope): + - `create:todos`:「建立新的待辦事項」 + - `read:todos`:「讀取所有待辦事項」 + - `delete:todos`:「刪除任一待辦事項」 + +3. 建立角色(建議以便管理): + + - 前往「角色」 + - 建立「Admin」角色並指派所有權限範圍(`create:todos`、`read:todos`、`delete:todos`) + - 建立「User」角色並僅指派 `create:todos` 權限範圍 + - 在「User」角色詳細頁切換至「一般」分頁,將「User」設為「預設角色」 + +4. 管理使用者角色與權限: + - 新使用者: + - 由於已設為預設角色,將自動獲得「User」角色 + - 現有使用者: + - 前往「使用者管理」 + - 選擇一位使用者 + - 在「角色」分頁指派角色 + +:::tip 程式化角色管理 +你也可以使用 Logto 的 [Management API](https://docs.logto.io/integrate-logto/interact-with-management-api) 以程式方式管理使用者角色。這對自動化使用者管理或建立管理後台特別有用。 +::: + +請求存取權杖時,Logto 會根據使用者角色權限將權限範圍 (Scope) 加入權杖的 `scope` 宣告 (Claim)。 + + + + +對於 OAuth 2.0 或 OpenID Connect 簽發者 (Issuer),你需要設定代表不同權限的權限範圍 (Scope)。具體步驟依簽發者而異,但一般流程如下: + +1. 定義權限範圍 (Scope): + + - 設定授權伺服器支援: + - `create:todos` + - `read:todos` + - `delete:todos` + +2. 設定用戶端: + + - 註冊或更新用戶端以請求這些權限範圍 + - 確保權限範圍會包含在存取權杖中 + +3. 指派權限: + - 使用簽發者介面將適當權限範圍指派給使用者 + - 有些簽發者支援基於角色的管理,有些則直接指派權限範圍 + - 請查閱簽發者文件以獲得建議做法 + +:::tip +大多數簽發者會將授予的權限範圍包含在存取權杖的 `scope` 宣告 (Claim) 中。格式通常為以空格分隔的權限範圍字串。 +::: + + + + +設定好授權伺服器後,使用者將收到包含其授權權限範圍的存取權杖。MCP 伺服器會根據這些權限範圍判斷: + +- 使用者是否能建立新的待辦事項(`create:todos`) +- 使用者是否能檢視所有待辦事項(`read:todos`)或僅能檢視自己的 +- 使用者是否能刪除任一待辦事項(`delete:todos`)或僅能刪除自己的 + +## 建立 MCP 伺服器 \{#set-up-the-mcp-server} + +我們將使用 [MCP 官方 SDK](https://github.com/modelcontextprotocol) 來建立 todo manager MCP 伺服器。 + +### 建立新專案 \{#create-a-new-project} + + + + +建立新的 Python 專案: + +```bash +mkdir mcp-todo-server +cd mcp-todo-server + +# 初始化新的 Python 專案 +uv init + +# 使用 uv 建立虛擬環境 +uv venv + +# 啟用虛擬環境(使用 'uv run' 時可選擇性略過) +source .venv/bin/activate +``` + +:::note +本專案使用 `uv` 進行套件管理,但你也可以選擇 `pip`、`poetry` 或 `conda` 等其他套件管理工具。 +::: + + + + +建立新的 Node.js 專案: + +```bash +mkdir mcp-server +cd mcp-server +npm init -y # 或使用 `pnpm init` +npm pkg set type="module" +npm pkg set main="todo-manager.ts" +npm pkg set scripts.start="node --experimental-strip-types todo-manager.ts" +``` + +:::note +我們的範例使用 TypeScript,因為 Node.js v22.6.0+ 原生支援 `--experimental-strip-types` 執行 TypeScript。若你使用 JavaScript,程式碼大致相同,只需確保 Node.js 版本為 v22.6.0 或以上。詳情請參閱 Node.js 官方文件。 +::: + + + + +### 安裝 MCP SDK 與相依套件 \{#install-the-mcp-sdk-and-dependencies} + + + + +安裝所需相依套件: + +```bash +uv add "mcp[cli]" uvicorn starlette +``` + + + + +```bash +npm install @modelcontextprotocol/sdk express zod +``` + +或你偏好的其他套件管理工具,如 `pnpm` 或 `yarn`。 + + + + +### 建立 MCP 伺服器 \{#create-the-mcp-server} + +首先,讓我們建立一個包含工具定義的基本 MCP 伺服器: + + + + +建立名為 `server.py` 的檔案並加入以下程式碼: + +```python +# server.py + +import contextlib +from typing import Any +from mcp.server.fastmcp import FastMCP +from starlette.applications import Starlette +from starlette.routing import Mount + +# 初始化 FastMCP 伺服器 +mcp = FastMCP(name="Todo Manager", stateless_http=True, streamable_http_path='/') + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """建立新的待辦事項。需 'create:todos' 權限範圍。""" + return {"error": "Not implemented"} + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """列出待辦事項。具備 'read:todos' 權限範圍的使用者可檢視所有待辦事項。""" + return {"error": "Not implemented"} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """根據 id 刪除待辦事項。使用者可刪除自己的待辦事項。""" + return {"error": "Not implemented"} + +@contextlib.asynccontextmanager +async def lifespan(app: Starlette): + async with contextlib.AsyncExitStack() as stack: + await stack.enter_async_context(mcp.session_manager.run()) + yield + +# 建立 app +app = Starlette( + routes=[ + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + +以以下指令啟動伺服器: + +```bash +# 使用 uvicorn 啟動 Todo Manager 伺服器 +uvicorn server:app --host 127.0.0.1 --port 3001 + +# 或使用 uv: +# uv run uvicorn server:app --host 127.0.0.1 --port 3001 +``` + + + + +建立名為 `todo-manager.ts` 的檔案並加入以下程式碼: + +```ts +// todo-manager.ts + +import { z } from 'zod'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import express, { type Request, type Response } from 'express'; + +// 建立 MCP 伺服器 +const server = new McpServer({ + name: 'Todo Manager', + version: '0.0.0', +}); + +server.tool('create-todo', 'Create a new todo', { content: z.string() }, async ({ content }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('get-todos', 'List all todos', async () => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +server.tool('delete-todo', 'Delete a todo by id', { id: z.string() }, async ({ id }) => { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Not implemented' }) }], + }; +}); + +// 以下為 MCP SDK 文件範例樣板 +const PORT = 3001; +const app = express(); + +app.post('/', async (request: Request, response: Response) => { + // 在 stateless 模式下,每個請求都建立新的 transport 與 server 實例以確保完全隔離。 + // 單一實例會導致多用戶端同時連線時請求 ID 衝突。 + + try { + const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + }); + response.on('close', async () => { + console.log('Request closed'); + await transport.close(); + await server.close(); + }); + await server.connect(transport); + await transport.handleRequest(request, response, request.body); + } catch (error) { + console.error('Error handling MCP request:', error); + if (!response.headersSent) { + response.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32_603, + message: 'Internal server error', + }, + id: null, + }); + } + } +}); + +// stateless 模式下不支援 SSE 通知 +app.get('/', async (request: Request, response: Response) => { + console.log('Received GET MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +// stateless 模式下不需終止 session +app.delete('/', async (request: Request, response: Response) => { + console.log('Received DELETE MCP request'); + response.writeHead(405).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32_000, + message: 'Method not allowed.', + }, + id: null, + }) + ); +}); + +app.listen(PORT); +``` + +以以下指令啟動伺服器: + +```bash +npm start +``` + + + + +## 檢查 MCP 伺服器 \{#inspect-the-mcp-server} + +### 下載並執行 MCP inspector \{#clone-and-run-mcp-inspector} + +現在 MCP 伺服器已啟動,我們可以使用 MCP inspector 來檢查工具是否可用。 + +官方 MCP inspector v0.16.2 有些 bug 會影響驗證 (Authentication) 功能。為了解決這些問題,我們建立了 [修正版 MCP inspector](https://github.com/mcp-auth/inspector/tree/patch/0.16.2-fixes),已包含 OAuth / OIDC 驗證流程所需修正。我們也已向官方倉庫提交 PR。 + +執行 MCP inspector: + +```bash +git clone https://github.com/mcp-auth/inspector.git -b patch/0.16.2-fixes +cd inspector +npm install +npm run dev +``` + +MCP inspector 會自動在預設瀏覽器開啟,或你也可以手動點擊終端機輸出的連結(請務必點擊包含 `MCP_PROXY_AUTH_TOKEN` 參數的連結,如 `http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=458ae4a4...acab1907`)。 + +### 連接 MCP inspector 至 MCP 伺服器 \{#connect-mcp-inspector-to-the-mcp-server} + +繼續前請檢查 MCP inspector 的以下設定: + +- **Transport Type**:設為 `Streamable HTTP` +- **URL**:設為 MCP 伺服器的 URL,本例為 `http://localhost:3001` + +現在你可以點擊「Connect」按鈕,檢查 MCP inspector 是否能連線至 MCP 伺服器。若一切正常,MCP inspector 會顯示「Connected」狀態。 + +### 檢查點:執行 todo manager 工具 \{#checkpoint-run-todo-manager-tools} + +1. 在 MCP inspector 上方選單點選「Tools」分頁 +2. 點擊「List Tools」按鈕 +3. 你應該會看到 `create-todo`、`get-todos`、`delete-todo` 工具列在頁面上,點擊可檢視工具細節 +4. 右側會出現「Run Tool」按鈕,點擊並輸入必要參數執行工具 +5. 你會看到工具回傳的 JSON 結果 `{"error": "Not implemented"}` + +![MCP inspector 首次執行畫面](/docs-assets/images/tutorials/todo-manager/inspector-first-run.png) + +## 與授權伺服器整合 \{#integrate-with-your-authorization-server} + +完成本節需考慮以下幾點: + +
+**你的授權伺服器簽發者 (Issuer) URL** + +通常是你的授權伺服器基礎 URL,如 `https://auth.example.com`。有些簽發者可能為 `https://example.logto.app/oidc`,請參考你的簽發者文件。 + +
+ +
+**如何取得授權伺服器中繼資料** + +- 若你的授權伺服器符合 [OAuth 2.0 授權伺服器中繼資料](https://datatracker.ietf.org/doc/html/rfc8414) 或 [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html),可用 MCP Auth 內建工具自動取得中繼資料 +- 若不符合,需手動在 MCP 伺服器設定中指定中繼資料 URL 或端點,請查閱簽發者文件 + +
+ +
+**如何將 MCP inspector 註冊為授權伺服器用戶端** + +- 若授權伺服器支援 [動態用戶端註冊 (Dynamic Client Registration)](https://datatracker.ietf.org/doc/html/rfc7591),MCP inspector 會自動註冊 +- 若不支援,需手動將 MCP inspector 註冊為用戶端 + +
+ +
+**瞭解權杖請求參數** + +向不同授權伺服器請求存取權杖時,指定目標資源與權限的方式可能不同,主要有: + +- **資源標示符 (Resource indicator) 模式**: + + - 使用 `resource` 參數指定目標 API(參見 [RFC 8707: OAuth 2.0 資源標示符]) + - 現代 OAuth 2.0 常見 + - 範例請求: + ```json + { + "resource": "http://localhost:3001", + "scope": "create:todos read:todos" + } + ``` + - 伺服器會發出專屬於該資源的權杖 + +- **受眾 (Audience) 模式**: + + - 使用 `audience` 參數指定權杖目標 + - 與資源標示符類似但語意不同 + - 範例請求: + ```json + { + "audience": "todo-api", + "scope": "create:todos read:todos" + } + ``` + +- **純權限範圍 (Scope) 模式**: + - 僅依權限範圍,不帶 resource / audience 參數 + - 傳統 OAuth 2.0 作法 + - 範例請求: + ```json + { + "scope": "todo-api:create todo-api:read openid profile" + } + ``` + - 常以前綴命名空間權限範圍 + - 簡單 OAuth 2.0 實作常見 + +:::tip 最佳實踐 + +- 查閱簽發者文件以確認支援哪些參數 +- 有些簽發者同時支援多種方式 +- 資源標示符可提升安全性(限制受眾) +- 建議有支援時優先使用資源標示符以強化存取控制 + ::: + +
+ +每個簽發者可能有不同需求,以下步驟將引導你整合 MCP inspector 與 MCP 伺服器並進行專屬設定。 + +### 註冊 MCP inspector 為用戶端 \{#register-mcp-inspector-as-a-client} + + + + +將 todo manager 與 [Logto](https://logto.io) 整合非常簡單,因其為支援資源標示符與權限範圍的 OpenID Connect 簽發者,可用 `http://localhost:3001` 作為資源標示符保護 todo API。 + +由於 Logto 尚未支援動態用戶端註冊,你需手動將 MCP inspector 註冊為 Logto 租戶的用戶端: + +1. 開啟 MCP inspector,進入驗證 (Authentication) 設定並點擊「OAuth2.0 Flow」設定。複製 **Redirect URI**,如 `http://localhost:6274/oauth/callback` +2. 登入 [Logto Console](https://cloud.logto.io)(或你的自架 Logto Console) +3. 前往「應用程式」分頁,點擊「建立應用程式」。頁面底部點選「不使用框架建立應用程式」 +4. 填寫應用程式資訊後點擊「建立應用程式」: + - **選擇應用程式類型**:選「單頁應用程式」 + - **應用程式名稱**:如「MCP Inspector」 +5. 在「設定 / Redirect URIs」區塊貼上剛才複製的 **Redirect URI**,然後點擊底部「儲存變更」 +6. 頁面上方卡片會顯示「App ID」,請複製 +7. 回到 MCP inspector,將「App ID」貼到驗證 (Authentication) 設定的「OAuth2.0 Flow」下的「Client ID」欄位 +8. 在「Scope」欄位輸入:`create:todos read:todos delete:todos`,確保 Logto 回傳的存取權杖包含 todo manager 所需權限範圍 + + + + +:::note +這是通用 OAuth 2.0 / OpenID Connect 簽發者整合指引。兩者步驟類似,因 OIDC 建立於 OAuth 2.0 之上。請查閱你的簽發者文件以獲得細節。 +::: + +若你的簽發者支援動態用戶端註冊,可直接跳至第 8 步設定 MCP inspector;否則需手動註冊: + +1. 開啟 MCP inspector,進入驗證 (Authentication) 設定並點擊「OAuth2.0 Flow」設定。複製 **Redirect URI**,如 `http://localhost:6274/oauth/callback` + +2. 登入你的簽發者管理後台 + +3. 前往「應用程式」或「用戶端」區塊,建立新應用程式或用戶端 + +4. 若需選擇用戶端類型,請選「單頁應用程式」或「公開用戶端」 + +5. 建立應用程式後,需設定 redirect URI,貼上剛才複製的 **Redirect URI** + +6. 找到新應用程式的「Client ID」或「Application ID」並複製 + +7. 回到 MCP inspector,將「Client ID」貼到驗證 (Authentication) 設定的「OAuth2.0 Flow」下的「Client ID」欄位 + +8. 在「Scope」欄位輸入以下權限範圍以請求 todo 操作所需權限: + +```text +create:todos read:todos delete:todos +``` + + + + +### 設定 MCP Auth \{#set-up-mcp-auth} + +首先,在 MCP 伺服器專案中安裝 MCP Auth SDK。 + + + + +```bash +uv add mcpauth==0.2.0b1 +``` + + + + +```bash +npm install mcp-auth@0.2.0-beta.1 +``` + + + + +接下來需在 MCP 伺服器初始化 MCP Auth,主要分兩步: + +1. **取得授權伺服器中繼資料**:供 MCP Auth 驗證授權伺服器發出的存取權杖,並將簽發者 (Issuer) 識別資訊納入資源中繼資料 +2. **設定受保護資源中繼資料**:定義 MCP 伺服器的資源標示符與支援的權限範圍 + +#### 步驟 1:取得授權伺服器中繼資料 \{#step-1-fetch-authorization-server-metadata\} + +根據 OAuth / OIDC 規範,可根據授權伺服器簽發者 (Issuer) URL 取得中繼資料。 + + + + + +在 Logto,你可於 Logto Console 的應用程式詳細頁「Endpoints & Credentials / Issuer endpoint」區塊找到簽發者 (Issuer) URL,格式如 `https://my-project.logto.app/oidc`。 + + + + + +對於 OAuth 2.0 簽發者,請: + +1. 查閱簽發者文件取得授權伺服器 URL(常稱 issuer URL 或 base URL) +2. 有些簽發者會在 `https://{your-domain}/.well-known/oauth-authorization-server` 提供 +3. 於管理後台 OAuth / API 設定中查找 + + + + + +現在,使用 MCP Auth 工具函式取得授權伺服器中繼資料: + + + + +```python +from mcpauth import MCPAuth +from mcpauth.config import AuthServerType +from mcpauth.utils import fetch_server_config + +issuer_url = "" # 請替換為你的授權伺服器簽發者 (Issuer) URL + +# 取得授權伺服器設定 +auth_server_config = fetch_server_config(issuer_url, AuthServerType.OIDC) # 或 AuthServerType.OAUTH +``` + + + +```js +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; + +const issuerUrl = ''; // 請替換為你的授權伺服器簽發者 (Issuer) URL + +// 取得授權伺服器設定(OIDC Discovery) +const authServerConfig = await fetchServerConfig(issuerUrl, { type: 'oidc' }); // 或 { type: 'oauth' } +``` + + + + +若需其他方式取得授權伺服器中繼資料或自訂設定,請參考 [其他設定方式](/docs/configure-server/mcp-auth#other-ways)。 + +#### 步驟 2:設定受保護資源中繼資料 \{#step-2-configure-protected-resource-metadata} + +接著,在建立 MCP Auth 實例時設定受保護資源中繼資料。MCP 伺服器將透過 MCP Auth 對外公開這些資源中繼資料。 + + + + +```python +# server.py + +# 其他 import... +from mcpauth.types import ResourceServerConfig, ResourceServerMetadata + +# 定義本 MCP 伺服器的資源標示符 +resource_id = "http://localhost:3001" + +mcp_auth = MCPAuth( + protected_resources=ResourceServerConfig( + metadata=ResourceServerMetadata( + resource=resource_id, + # 上一步取得的授權伺服器中繼資料 + authorization_servers=[auth_server_config], + # 本 MCP 伺服器支援的權限範圍 + scopes_supported=[ + "create:todos", + "read:todos", + "delete:todos" + ] + ) + ) +) +``` + + + +```js +// todo-manager.ts + +// 定義本 MCP 伺服器的資源標示符 +const resourceId = 'http://localhost:3001'; + +// 設定 MCP Auth 受保護資源中繼資料 +const mcpAuth = new MCPAuth({ + protectedResources: { + metadata: { + resource: resourceId, + // 上一步取得的授權伺服器中繼資料 + authorizationServers: [authServerConfig], + // 本 MCP 伺服器支援的權限範圍 + scopesSupported: [ + "create:todos", + "read:todos", + "delete:todos" + ] + } + } +}); +``` + + + + +### 更新 MCP 伺服器 \{#update-mcp-server} + +快完成了!現在要更新 MCP 伺服器,套用 MCP Auth 路由與中介軟體 (middleware),並根據使用者權限範圍實作 todo manager 工具的權限控管。 + +首先,套用受保護資源中繼資料路由,讓 MCP 用戶端可從 MCP 伺服器取得資源中繼資料。 + + + +```python +# server.py + +# ..其他程式碼 + +app = Starlette( + routes=[ + # 設定受保護資源中繼資料路由 + # 讓 OAuth 用戶端可取得本資源伺服器的中繼資料 + *mcp_auth.resource_metadata_router().routes, + Mount("/", app=mcp.streamable_http_app()), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +// 設定受保護資源中繼資料路由 +// 讓 OAuth 用戶端可取得本資源伺服器的中繼資料 +app.use(mcpAuth.protectedResourceMetadataRouter()); + +``` + + + +接著,套用 MCP Auth 中介軟體至 MCP 伺服器。此中介軟體將處理所有進來請求的驗證 (Authentication) 與授權 (Authorization),確保只有授權使用者能存取 todo manager 工具。 + + + +```python +# server.py + +# 其他 import... +from starlette.middleware import Middleware + +# 其他程式碼... + +# 建立中介軟體 +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt', resource=resource_id, audience=resource_id)) + +app = Starlette( + routes=[ + *mcp_auth.resource_metadata_router().routes, + # 套用 MCP Auth 中介軟體 + Mount("/", app=mcp.streamable_http_app(), middleware=[bearer_auth]), + ], + lifespan=lifespan, +) +``` + + + +```ts +// todo-manager.ts + +app.use(mcpAuth.protectedResourceMetadataRouter()); + +// 套用 MCP Auth 中介軟體 +app.use( + mcpAuth.bearerAuth('jwt', { + resource: resourceId, + audience: resourceId, + }) +); +``` + + + +現在可以更新 todo manager 工具,讓其透過 MCP Auth 中介軟體進行驗證 (Authentication) 與授權 (Authorization)。 + +讓我們來更新工具實作。 + + + +```python +# server.py + +# 其他 import... + +from typing import Any, List, Optional +from mcpauth.exceptions import MCPAuthBearerAuthException, BearerAuthExceptionCode +from mcpauth.types import AuthInfo, ResourceServerConfig, ResourceServerMetadata + +# 下一節會提到 +from service import TodoService + +def assert_user_id(auth_info: Optional[AuthInfo]) -> str: + """確認 auth_info 包含有效 user ID 並回傳。""" + if not auth_info or not auth_info.subject: + raise Exception("Invalid auth info") + return auth_info.subject + +def has_required_scopes(user_scopes: List[str], required_scopes: List[str]) -> bool: + """檢查使用者是否具備所有必要權限範圍。""" + return all(scope in user_scopes for scope in required_scopes) + +# 建立 TodoService 實例 +todo_service = TodoService() + +@mcp.tool() +def create_todo(content: str) -> dict[str, Any]: + """建立新的待辦事項。需 'create:todos' 權限範圍。""" + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # 只有具備 'create:todos' 權限範圍的使用者可建立 + user_scopes = auth_info.scopes if auth_info else [] + if not has_required_scopes(user_scopes, ["create:todos"]): + raise MCPAuthBearerAuthException(BearerAuthExceptionCode.MISSING_REQUIRED_SCOPES) + + created_todo = todo_service.create_todo(content=content, owner_id=user_id) + return created_todo + +@mcp.tool() +def get_todos() -> dict[str, Any]: + """ + 列出待辦事項。具備 'read:todos' 權限範圍的使用者可檢視所有待辦事項, + 否則僅能檢視自己的。 + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + # 有 'read:todos' 權限範圍可存取所有,否則僅能存取自己的 + user_scopes = auth_info.scopes if auth_info else [] + todo_owner_id = None if has_required_scopes(user_scopes, ["read:todos"]) else user_id + + todos = todo_service.get_all_todos(todo_owner_id) + return {"todos": todos} + +@mcp.tool() +def delete_todo(id: str) -> dict[str, Any]: + """ + 根據 id 刪除待辦事項。使用者可刪除自己的, + 具備 'delete:todos' 權限範圍者可刪除任何待辦事項。 + """ + auth_info = mcp_auth.auth_info + user_id = assert_user_id(auth_info) + + todo = todo_service.get_todo_by_id(id) + + if not todo: + return {"error": "Failed to delete todo"} + + # 只有自己的可刪除,具備 'delete:todos' 權限範圍者可刪除任何 + user_scopes = auth_info.scopes if auth_info else [] + if todo.owner_id != user_id and not has_required_scopes(user_scopes, ["delete:todos"]): + return {"error": "Failed to delete todo"} + + deleted_todo = todo_service.delete_todo(id) + + if deleted_todo: + return { + "message": f"Todo {id} deleted", + "details": deleted_todo + } + else: + return {"error": "Failed to delete todo"} +``` + + + +```js +// todo-manager.ts + +// 其他 import... +import assert from 'node:assert'; +import { fetchServerConfig, MCPAuth, MCPAuthBearerAuthError } from 'mcp-auth'; +import { type AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js'; + +// 下一節會提到 +import { TodoService } from './todo-service.js'; + +const assertUserId = (authInfo?: AuthInfo) => { + const { subject } = authInfo ?? {}; + assert(subject, 'Invalid auth info'); + return subject; +}; + +const hasRequiredScopes = (userScopes: string[], requiredScopes: string[]): boolean => { + return requiredScopes.every((scope) => userScopes.includes(scope)); +}; + +const todoService = new TodoService(); + +server.tool( + 'create-todo', + 'Create a new todo', + { content: z.string() }, + ({ content }: { content: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * 只有具備 'create:todos' 權限範圍的使用者可建立 + */ + if (!hasRequiredScopes(authInfo?.scopes ?? [], ['create:todos'])) { + throw new MCPAuthBearerAuthError('missing_required_scopes'); + } + + const createdTodo = todoService.createTodo({ content, ownerId: userId }); + + return { + content: [{ type: 'text', text: JSON.stringify(createdTodo) }], + }; + } +); + +server.tool('get-todos', 'List all todos', ({ authInfo }) => { + const userId = assertUserId(authInfo); + + /** + * 有 'read:todos' 權限範圍可存取所有(todoOwnerId = undefined) + * 否則僅能存取自己的(todoOwnerId = userId) + */ + const todoOwnerId = hasRequiredScopes(authInfo?.scopes ?? [], ['read:todos']) + ? undefined + : userId; + + const todos = todoService.getAllTodos(todoOwnerId); + + return { + content: [{ type: 'text', text: JSON.stringify(todos) }], + }; +}); + +server.tool( + 'delete-todo', + 'Delete a todo by id', + { id: z.string() }, + ({ id }: { id: string }, { authInfo }) => { + const userId = assertUserId(authInfo); + + const todo = todoService.getTodoById(id); + + if (!todo) { + return { + content: [{ type: 'text', text: JSON.stringify({ error: 'Failed to delete todo' }) }], + }; + } + + /** + * 只有自己的可刪除,具備 'delete:todos' 權限範圍者可刪除任何 + */ + if (todo.ownerId !== userId && !hasRequiredScopes(authInfo?.scopes ?? [], ['delete:todos'])) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ error: 'Failed to delete todo' }), + }, + ], + }; + } + + const deletedTodo = todoService.deleteTodo(id); + + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + message: `Todo ${id} deleted`, + details: deletedTodo, + }), + }, + ], + }; + } +); +``` + + + +現在,建立上述程式碼所用的「Todo service」以實作相關功能: + + + + +建立 `service.py` 作為 Todo service: + +```python +""" +簡易 Todo 服務,僅供示範用途。 +以記憶體列表儲存 todos。 +""" + +from datetime import datetime +from typing import List, Optional, Dict, Any +import random +import string + +class Todo: + """代表一個待辦事項。""" + + def __init__(self, id: str, content: str, owner_id: str, created_at: str): + self.id = id + self.content = content + self.owner_id = owner_id + self.created_at = created_at + + def to_dict(self) -> Dict[str, Any]: + """轉換為 dict 以供 JSON 序列化。""" + return { + "id": self.id, + "content": self.content, + "ownerId": self.owner_id, + "createdAt": self.created_at + } + + +class TodoService: + """簡易 Todo 服務,僅供示範用途。""" + + def __init__(self): + self._todos: List[Todo] = [] + + def get_all_todos(self, owner_id: Optional[str] = None) -> List[Dict[str, Any]]: + """ + 取得所有 todos,可選擇依 owner_id 過濾。 + + Args: + owner_id: 若提供,僅回傳該使用者的 todos + + Returns: + todo 字典列表 + """ + if owner_id: + filtered_todos = [todo for todo in self._todos if todo.owner_id == owner_id] + return [todo.to_dict() for todo in filtered_todos] + return [todo.to_dict() for todo in self._todos] + + def get_todo_by_id(self, todo_id: str) -> Optional[Todo]: + """ + 依 ID 取得 todo。 + + Args: + todo_id: 欲取得的 todo ID + + Returns: + 找到則回傳 Todo 物件,否則 None + """ + for todo in self._todos: + if todo.id == todo_id: + return todo + return None + + def create_todo(self, content: str, owner_id: str) -> Dict[str, Any]: + """ + 建立新 todo。 + + Args: + content: todo 內容 + owner_id: 擁有者 ID + + Returns: + 建立的 todo 字典 + """ + todo = Todo( + id=self._generate_id(), + content=content, + owner_id=owner_id, + created_at=datetime.now().isoformat() + ) + self._todos.append(todo) + return todo.to_dict() + + def delete_todo(self, todo_id: str) -> Optional[Dict[str, Any]]: + """ + 依 ID 刪除 todo。 + + Args: + todo_id: 欲刪除的 todo ID + + Returns: + 刪除的 todo 字典,若未找到則 None + """ + for i, todo in enumerate(self._todos): + if todo.id == todo_id: + deleted_todo = self._todos.pop(i) + return deleted_todo.to_dict() + return None + + def _generate_id(self) -> str: + """產生隨機 todo ID。""" + return ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)) +``` + + + + +建立 `todo-service.ts` 作為 Todo service: + +```ts +// todo-service.ts + +type Todo = { + id: string; + content: string; + ownerId: string; + createdAt: string; +}; + +/** + * 簡易 Todo 服務,僅供示範用途。 + * 以記憶體陣列儲存 todos + */ +export class TodoService { + private readonly todos: Todo[] = []; + + getAllTodos(ownerId?: string): Todo[] { + if (ownerId) { + return this.todos.filter((todo) => todo.ownerId === ownerId); + } + return this.todos; + } + + getTodoById(id: string): Todo | undefined { + return this.todos.find((todo) => todo.id === id); + } + + createTodo({ content, ownerId }: { content: string; ownerId: string }): Todo { + const todo: Todo = { + id: this.genId(), + content, + ownerId, + createdAt: new Date().toISOString(), + }; + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + this.todos.push(todo); + return todo; + } + + deleteTodo(id: string): Todo | undefined { + const index = this.todos.findIndex((todo) => todo.id === id); + + if (index === -1) { + return undefined; + } + + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + const [deleted] = this.todos.splice(index, 1); + return deleted; + } + + private genId(): string { + return Math.random().toString(36).slice(2, 10); + } +} +``` + + + + +🎉 恭喜!我們已成功實作一個具備驗證 (Authentication) 與授權 (Authorization) 的完整 MCP 伺服器! + +你也可以參考我們的範例程式碼: + + + + +:::info +完整 MCP 伺服器(OIDC 版本)程式碼請參考 [MCP Auth Python SDK repository](https://github.com/mcp-auth/python/tree/master/samples/current/todo-manager)。 +::: + + + + +:::info +完整 MCP 伺服器(OIDC 版本)程式碼請參考 [MCP Auth Node.js SDK repository](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src)。 +::: + + + + +## 檢查點:執行 `todo-manager` 工具 \{#checkpoint-run-the-todo-manager-tools} + +重新啟動 MCP 伺服器並於瀏覽器開啟 MCP inspector。點擊「Connect」按鈕時,你應會被導向授權伺服器的登入頁面。 + +登入並返回 MCP inspector 後,重複前述步驟執行 todo manager 工具。這次你將以已驗證 (Authentication) 的使用者身分使用這些工具。工具行為會根據你帳號的角色與權限而異: + +- 若以 **User**(僅有 `create:todos` 權限範圍)登入: + + - 可用 `create-todo` 工具建立新待辦事項 + - 僅能檢視與刪除自己的待辦事項 + - 無法檢視或刪除其他使用者的待辦事項 + +- 若以 **Admin**(具備所有權限範圍:`create:todos`、`read:todos`、`delete:todos`)登入: + - 可建立新待辦事項 + - 可用 `get-todos` 工具檢視系統所有待辦事項 + - 可用 `delete-todo` 工具刪除任何待辦事項,不論擁有者 + +你可以透過以下方式測試不同權限層級: + +1. 登出目前 session(於 MCP inspector 點擊「Disconnect」) +2. 以不同權限的帳號登入 +3. 重複執行相同工具,觀察行為如何隨使用者權限變化 + +這展現了角色型存取控制 (RBAC) 的實際運作,不同使用者對系統功能有不同存取層級。 + +![MCP inspector todo manager 工具結果](/docs-assets/images/tutorials/todo-manager/result.png) + + + + +:::info +完整 MCP 伺服器(OIDC 版本)程式碼請參考 [MCP Auth Python SDK repository](https://github.com/mcp-auth/python)。 +::: + + + + +:::info +完整 MCP 伺服器(OIDC 版本)程式碼請參考 [MCP Auth Node.js SDK repository](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src)。 +::: + + + + +## 結語 \{#closing-notes} + +🎊 恭喜!你已順利完成本教學。讓我們回顧一下: + +- 建立具備 todo 管理工具(`create-todo`、`get-todos`、`delete-todo`)的基本 MCP 伺服器 +- 實作不同使用者與管理員權限層級的角色型存取控制 (RBAC) +- 透過 MCP Auth 將 MCP 伺服器與授權伺服器整合 +- 設定 MCP Inspector 以驗證 (Authentication) 使用者並使用帶有權限範圍的存取權杖呼叫工具 + +歡迎參閱其他教學與文件,充分發揮 MCP Auth 的強大功能。 diff --git a/translate.mjs b/translate.mjs index 92f080e..6b989f0 100644 --- a/translate.mjs +++ b/translate.mjs @@ -19,7 +19,8 @@ import { docsBaseDir, i18nBaseDir, validExtensions, - translateDir, + versionedDocsBaseDir, + getTranslatePath, filterFiles, } from './translate.shared.mjs'; @@ -32,6 +33,7 @@ const args = arg({ '--check': Boolean, '--locale': String, '--silent': Boolean, + '--version': String, }); /** @@ -89,6 +91,14 @@ const locale = args['--locale']; */ const silent = args['--silent']; +/** + * The specific version to translate. If provided, only files from that version will be processed. + * Use "current" to translate only the current version (docs/ directory). + * + * @type {string} + */ +const version = args['--version']; + if (sync && check) { exit('Cannot use --sync and --check together.'); } @@ -109,7 +119,12 @@ const getFiles = async () => { if (inputFiles?.length) { const result = await Promise.all( inputFiles.map(async (file) => { - const filePath = path.join(docsBaseDir, file); + // Support both docs/ and versioned_docs/ paths + const filePath = + file.startsWith('versioned_docs/') || file.startsWith('docs/') + ? file + : path.join(docsBaseDir, file); + const stats = await fs.stat(filePath); if (stats.isDirectory()) { @@ -127,7 +142,47 @@ const getFiles = async () => { } if (all) { - return walk(docsBaseDir); + const files = []; + + if (version === 'current') { + // Only translate current version + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + files.push(...(await walk(docsBaseDir))); + } else if (version) { + // Translate specific version + const versionDir = path.join(versionedDocsBaseDir, `version-${version}`); + try { + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + files.push(...(await walk(versionDir))); + } catch { + exit( + `Version ${version} not found. Available versions: current, ${( + await fs.readdir(versionedDocsBaseDir) + ) + // eslint-disable-next-line unicorn/no-await-expression-member + .filter((f) => f.startsWith('version-')) + .map((f) => f.replace('version-', '')) + .join(', ')}` + ); + } + } else { + // Translate all versions (current + all versioned) + // eslint-disable-next-line @silverhand/fp/no-mutating-methods + files.push(...(await walk(docsBaseDir))); + + try { + const versions = await fs.readdir(versionedDocsBaseDir); + const versionDirs = versions.filter((f) => f.startsWith('version-')); + for (const versionDir of versionDirs) { + // eslint-disable-next-line @silverhand/fp/no-mutating-methods, no-await-in-loop + files.push(...(await walk(path.join(versionedDocsBaseDir, versionDir)))); + } + } catch { + // Skip, `versioned_docs` directory doesn't exist. + } + } + + return files; } return []; @@ -185,7 +240,14 @@ const translate = async (locale, files) => { task.title = `Translating ${file}...`; const content = await fs.readFile(file, 'utf8'); const translated = await openAiTranslate.translate(content, locale, task); - const targetFile = file.replace(docsBaseDir, path.join(i18nBaseDir, locale, translateDir)); + const translatePath = getTranslatePath(file); + const sourceBaseDir = file.startsWith(versionedDocsBaseDir) + ? versionedDocsBaseDir + : docsBaseDir; + const targetFile = file.replace( + sourceBaseDir, + path.join(i18nBaseDir, locale, translatePath) + ); await fs.mkdir(path.dirname(targetFile), { recursive: true }); await fs.writeFile(targetFile, translated, 'utf8'); // eslint-disable-next-line @silverhand/fp/no-mutation diff --git a/translate.shared.mjs b/translate.shared.mjs index fd8a3b9..0d964d4 100644 --- a/translate.shared.mjs +++ b/translate.shared.mjs @@ -19,7 +19,23 @@ export const exit = (message) => { export const validExtensions = new Set(['.mdx', '.md']); export const docsBaseDir = 'docs'; export const i18nBaseDir = 'i18n'; -export const translateDir = 'docusaurus-plugin-content-docs/current'; +export const versionedDocsBaseDir = 'versioned_docs'; + +/** + * Get the correct translation path based on the source file path. + * @param {string} sourceFilePath - The source file path + * @returns {string} The translation directory path + */ +export const getTranslatePath = (sourceFilePath) => { + // Check if this is a versioned document + const versionMatch = sourceFilePath.match(/versioned_docs\/version-([\d.]+)\//); + if (versionMatch) { + return `docusaurus-plugin-content-docs/version-${versionMatch[1]}`; + } + + // Default to current version + return 'docusaurus-plugin-content-docs/current'; +}; // Recursively get all files in the docs directory. /** @type {(dir: string) => Promise} */ @@ -57,7 +73,11 @@ export const filterFiles = async (files, locale, sync, check) => { log('Checking for files that need to be translated by comparing timestamps in Git...'); const result = await Promise.all( files.map(async (file) => { - const targetFile = file.replace(docsBaseDir, path.join(i18nBaseDir, locale, translateDir)); + const translatePath = getTranslatePath(file); + const targetFile = file.replace( + file.startsWith(versionedDocsBaseDir) ? versionedDocsBaseDir : docsBaseDir, + path.join(i18nBaseDir, locale, translatePath) + ); const [sourceTimestamp, targetTimestamp] = await Promise.all([ execa`git log -1 --format=%cd --date=unix -- ${file}`, execa`git log -1 --format=%cd --date=unix -- ${targetFile}`,