refactor: use __future__.annotations (#1832)

This commit is contained in:
Marcelo Trylesinski 2026-01-06 20:03:13 +01:00 • committed by GitHub
commit 201de920a0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 17 additions and 37 deletions

View file

@ -126,7 +126,7 @@ plugins:
group_by_category: false group_by_category: false
# 3 because docs are in pages with an H2 just above them # 3 because docs are in pages with an H2 just above them
heading_level: 3 heading_level: 3
import: inventories:
- url: https://docs.python.org/3/objects.inv - url: https://docs.python.org/3/objects.inv
- url: https://docs.pydantic.dev/latest/objects.inv - url: https://docs.pydantic.dev/latest/objects.inv
- url: https://typing-extensions.readthedocs.io/en/latest/objects.inv - url: https://typing-extensions.readthedocs.io/en/latest/objects.inv

View file

@ -62,9 +62,7 @@ from .types import (
ToolUseContent, ToolUseContent,
UnsubscribeRequest, UnsubscribeRequest,
) )
from .types import ( from .types import Role as SamplingRole
Role as SamplingRole,
)
__all__ = [ __all__ = [
"CallToolRequest", "CallToolRequest",

View file

@ -206,7 +206,8 @@ class ClientSession(
def experimental(self) -> ExperimentalClientFeatures: def experimental(self) -> ExperimentalClientFeatures:
"""Experimental APIs for tasks and other features. """Experimental APIs for tasks and other features.
WARNING: These APIs are experimental and may change without notice. !!! warning
These APIs are experimental and may change without notice.
Example: Example:
status = await session.experimental.get_task(task_id) status = await session.experimental.get_task(task_id)

View file

@ -1,3 +1,5 @@
from __future__ import annotations as _annotations
import logging import logging
from collections.abc import Callable from collections.abc import Callable
from contextlib import AsyncExitStack from contextlib import AsyncExitStack
@ -72,14 +74,8 @@ class RequestResponder(Generic[ReceiveRequestT, SendResultT]):
request_id: RequestId, request_id: RequestId,
request_meta: RequestParams.Meta | None, request_meta: RequestParams.Meta | None,
request: ReceiveRequestT, request: ReceiveRequestT,
session: """BaseSession[ session: BaseSession[SendRequestT, SendNotificationT, SendResultT, ReceiveRequestT, ReceiveNotificationT],
SendRequestT, on_complete: Callable[[RequestResponder[ReceiveRequestT, SendResultT]], Any],
SendNotificationT,
SendResultT,
ReceiveRequestT,
ReceiveNotificationT
]""",
on_complete: Callable[["RequestResponder[ReceiveRequestT, SendResultT]"], Any],
message_metadata: MessageMetadata = None, message_metadata: MessageMetadata = None,
) -> None: ) -> None:
self.request_id = request_id self.request_id = request_id
@ -92,7 +88,7 @@ class RequestResponder(Generic[ReceiveRequestT, SendResultT]):
self._on_complete = on_complete self._on_complete = on_complete
self._entered = False # Track if we're in a context manager self._entered = False # Track if we're in a context manager
def __enter__(self) -> "RequestResponder[ReceiveRequestT, SendResultT]": def __enter__(self) -> RequestResponder[ReceiveRequestT, SendResultT]:
"""Enter the context manager, enabling request cancellation tracking.""" """Enter the context manager, enabling request cancellation tracking."""
self._entered = True self._entered = True
self._cancel_scope = anyio.CancelScope() self._cancel_scope = anyio.CancelScope()
@ -179,7 +175,7 @@ class BaseSession(
_request_id: int _request_id: int
_in_flight: dict[RequestId, RequestResponder[ReceiveRequestT, SendResultT]] _in_flight: dict[RequestId, RequestResponder[ReceiveRequestT, SendResultT]]
_progress_callbacks: dict[RequestId, ProgressFnT] _progress_callbacks: dict[RequestId, ProgressFnT]
_response_routers: list["ResponseRouter"] _response_routers: list[ResponseRouter]
def __init__( def __init__(
self, self,
@ -210,7 +206,8 @@ class BaseSession(
response stream mechanism. This is used by TaskResultHandler to route response stream mechanism. This is used by TaskResultHandler to route
responses for queued task requests back to their resolvers. responses for queued task requests back to their resolvers.
WARNING: This is an experimental API that may change without notice. !!! warning
This is an experimental API that may change without notice.
Args: Args:
router: A ResponseRouter implementation router: A ResponseRouter implementation

View file

@ -1,3 +1,5 @@
from __future__ import annotations as _annotations
from collections.abc import Callable from collections.abc import Callable
from datetime import datetime from datetime import datetime
from typing import Annotated, Any, Final, Generic, Literal, TypeAlias, TypeVar from typing import Annotated, Any, Final, Generic, Literal, TypeAlias, TypeVar
@ -6,24 +8,6 @@ from pydantic import BaseModel, ConfigDict, Field, FileUrl, RootModel
from pydantic.networks import AnyUrl, UrlConstraints from pydantic.networks import AnyUrl, UrlConstraints
from typing_extensions import deprecated from typing_extensions import deprecated
"""
Model Context Protocol bindings for Python
These bindings were generated from https://github.com/modelcontextprotocol/specification,
using Claude, with a prompt something like the following:
Generate idiomatic Python bindings for this schema for MCP, or the "Model Context
Protocol." The schema is defined in TypeScript, but there's also a JSON Schema version
for reference.
* For the bindings, let's use Pydantic V2 models.
* Each model should allow extra fields everywhere, by specifying `model_config =
ConfigDict(extra='allow')`. Do this in every case, instead of a custom base class.
* Union types should be represented with a Pydantic `RootModel`.
* Define additional model classes instead of using dictionaries. Do this even if they're
not separate types in the schema.
"""
LATEST_PROTOCOL_VERSION = "2025-11-25" LATEST_PROTOCOL_VERSION = "2025-11-25"
""" """
@ -557,7 +541,7 @@ class Task(BaseModel):
"""Current task state.""" """Current task state."""
statusMessage: str | None = None statusMessage: str | None = None
""" """
Optional human-readable message describing the current task state. Optional human-readable message describing the current task state.
This can provide context for any status, including: This can provide context for any status, including:
- Reasons for "cancelled" status - Reasons for "cancelled" status
@ -1121,7 +1105,7 @@ class ToolResultContent(BaseModel):
toolUseId: str toolUseId: str
"""The unique identifier that corresponds to the tool call's id field.""" """The unique identifier that corresponds to the tool call's id field."""
content: list["ContentBlock"] = [] content: list[ContentBlock] = []
""" """
A list of content objects representing the tool result. A list of content objects representing the tool result.
Defaults to empty list if not provided. Defaults to empty list if not provided.
@ -1523,7 +1507,7 @@ class CreateMessageRequestParams(RequestParams):
stopSequences: list[str] | None = None stopSequences: list[str] | None = None
metadata: dict[str, Any] | None = None metadata: dict[str, Any] | None = None
"""Optional metadata to pass through to the LLM provider.""" """Optional metadata to pass through to the LLM provider."""
tools: list["Tool"] | None = None tools: list[Tool] | None = None
""" """
Tool definitions for the LLM to use during sampling. Tool definitions for the LLM to use during sampling.
Requires clientCapabilities.sampling.tools to be present. Requires clientCapabilities.sampling.tools to be present.