chore: add ast-grep rule to convert Optional[T] to T | None (#25560)

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
-LAN-
2025-09-15 13:06:33 +08:00
committed by GitHub
parent 2e44ebe98d
commit bab4975809
394 changed files with 2555 additions and 2792 deletions

View File

@ -4,7 +4,6 @@ import json
import os
import secrets
import urllib.parse
from typing import Optional
from urllib.parse import urljoin, urlparse
import httpx
@ -122,7 +121,7 @@ def check_support_resource_discovery(server_url: str) -> tuple[bool, str]:
return False, ""
def discover_oauth_metadata(server_url: str, protocol_version: Optional[str] = None) -> Optional[OAuthMetadata]:
def discover_oauth_metadata(server_url: str, protocol_version: str | None = None) -> OAuthMetadata | None:
"""Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata."""
# First check if the server supports OAuth 2.0 Resource Discovery
support_resource_discovery, oauth_discovery_url = check_support_resource_discovery(server_url)
@ -152,7 +151,7 @@ def discover_oauth_metadata(server_url: str, protocol_version: Optional[str] = N
def start_authorization(
server_url: str,
metadata: Optional[OAuthMetadata],
metadata: OAuthMetadata | None,
client_information: OAuthClientInformation,
redirect_url: str,
provider_id: str,
@ -207,7 +206,7 @@ def start_authorization(
def exchange_authorization(
server_url: str,
metadata: Optional[OAuthMetadata],
metadata: OAuthMetadata | None,
client_information: OAuthClientInformation,
authorization_code: str,
code_verifier: str,
@ -242,7 +241,7 @@ def exchange_authorization(
def refresh_authorization(
server_url: str,
metadata: Optional[OAuthMetadata],
metadata: OAuthMetadata | None,
client_information: OAuthClientInformation,
refresh_token: str,
) -> OAuthTokens:
@ -273,7 +272,7 @@ def refresh_authorization(
def register_client(
server_url: str,
metadata: Optional[OAuthMetadata],
metadata: OAuthMetadata | None,
client_metadata: OAuthClientMetadata,
) -> OAuthClientInformationFull:
"""Performs OAuth 2.0 Dynamic Client Registration."""
@ -297,8 +296,8 @@ def register_client(
def auth(
provider: OAuthClientProvider,
server_url: str,
authorization_code: Optional[str] = None,
state_param: Optional[str] = None,
authorization_code: str | None = None,
state_param: str | None = None,
for_list: bool = False,
) -> dict[str, str]:
"""Orchestrates the full auth flow with a server using secure Redis state storage."""

View File

@ -1,5 +1,3 @@
from typing import Optional
from configs import dify_config
from core.mcp.types import (
OAuthClientInformation,
@ -37,7 +35,7 @@ class OAuthClientProvider:
client_uri="https://github.com/langgenius/dify",
)
def client_information(self) -> Optional[OAuthClientInformation]:
def client_information(self) -> OAuthClientInformation | None:
"""Loads information about this OAuth client."""
client_information = self.mcp_provider.decrypted_credentials.get("client_information", {})
if not client_information:
@ -51,7 +49,7 @@ class OAuthClientProvider:
{"client_information": client_information.model_dump()},
)
def tokens(self) -> Optional[OAuthTokens]:
def tokens(self) -> OAuthTokens | None:
"""Loads any existing OAuth tokens for the current session."""
credentials = self.mcp_provider.decrypted_credentials
if not credentials:

View File

@ -2,7 +2,7 @@ import logging
from collections.abc import Callable
from contextlib import AbstractContextManager, ExitStack
from types import TracebackType
from typing import Any, Optional
from typing import Any
from urllib.parse import urlparse
from core.mcp.client.sse_client import sse_client
@ -21,11 +21,11 @@ class MCPClient:
provider_id: str,
tenant_id: str,
authed: bool = True,
authorization_code: Optional[str] = None,
authorization_code: str | None = None,
for_list: bool = False,
headers: Optional[dict[str, str]] = None,
timeout: Optional[float] = None,
sse_read_timeout: Optional[float] = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
sse_read_timeout: float | None = None,
):
# Initialize info
self.provider_id = provider_id
@ -46,9 +46,9 @@ class MCPClient:
self.token = self.provider.tokens()
# Initialize session and client objects
self._session: Optional[ClientSession] = None
self._streams_context: Optional[AbstractContextManager[Any]] = None
self._session_context: Optional[ClientSession] = None
self._session: ClientSession | None = None
self._streams_context: AbstractContextManager[Any] | None = None
self._session_context: ClientSession | None = None
self._exit_stack = ExitStack()
# Whether the client has been initialized
@ -59,9 +59,7 @@ class MCPClient:
self._initialized = True
return self
def __exit__(
self, exc_type: Optional[type], exc_value: Optional[BaseException], traceback: Optional[TracebackType]
):
def __exit__(self, exc_type: type | None, exc_value: BaseException | None, traceback: TracebackType | None):
self.cleanup()
def _initialize(

View File

@ -4,7 +4,7 @@ from collections.abc import Callable
from concurrent.futures import Future, ThreadPoolExecutor, TimeoutError
from datetime import timedelta
from types import TracebackType
from typing import Any, Generic, Optional, Self, TypeVar
from typing import Any, Generic, Self, TypeVar
from httpx import HTTPStatusError
from pydantic import BaseModel
@ -212,7 +212,7 @@ class BaseSession(
request: SendRequestT,
result_type: type[ReceiveResultT],
request_read_timeout_seconds: timedelta | None = None,
metadata: Optional[MessageMetadata] = None,
metadata: MessageMetadata | None = None,
) -> ReceiveResultT:
"""
Sends a request and wait for a response. Raises an McpError if the

View File

@ -5,7 +5,6 @@ from typing import (
Any,
Generic,
Literal,
Optional,
TypeAlias,
TypeVar,
)
@ -1173,45 +1172,45 @@ class SessionMessage:
"""A message with specific metadata for transport-specific features."""
message: JSONRPCMessage
metadata: Optional[MessageMetadata] = None
metadata: MessageMetadata | None = None
class OAuthClientMetadata(BaseModel):
client_name: str
redirect_uris: list[str]
grant_types: Optional[list[str]] = None
response_types: Optional[list[str]] = None
token_endpoint_auth_method: Optional[str] = None
client_uri: Optional[str] = None
scope: Optional[str] = None
grant_types: list[str] | None = None
response_types: list[str] | None = None
token_endpoint_auth_method: str | None = None
client_uri: str | None = None
scope: str | None = None
class OAuthClientInformation(BaseModel):
client_id: str
client_secret: Optional[str] = None
client_secret: str | None = None
class OAuthClientInformationFull(OAuthClientInformation):
client_name: str | None = None
redirect_uris: list[str]
scope: Optional[str] = None
grant_types: Optional[list[str]] = None
response_types: Optional[list[str]] = None
token_endpoint_auth_method: Optional[str] = None
scope: str | None = None
grant_types: list[str] | None = None
response_types: list[str] | None = None
token_endpoint_auth_method: str | None = None
class OAuthTokens(BaseModel):
access_token: str
token_type: str
expires_in: Optional[int] = None
refresh_token: Optional[str] = None
scope: Optional[str] = None
expires_in: int | None = None
refresh_token: str | None = None
scope: str | None = None
class OAuthMetadata(BaseModel):
authorization_endpoint: str
token_endpoint: str
registration_endpoint: Optional[str] = None
registration_endpoint: str | None = None
response_types_supported: list[str]
grant_types_supported: Optional[list[str]] = None
code_challenge_methods_supported: Optional[list[str]] = None
grant_types_supported: list[str] | None = None
code_challenge_methods_supported: list[str] | None = None