Skip to content

Commit caa7ca9

Browse files
committed
style: ASCII-only docstrings/comments in v2 dispatcher files
Replace double-backticks with single, em-dashes with hyphens, and the one fat-arrow with => across files this branch touches. Also drop the unused TransportBuilder type alias (stale after the request_id arg was removed from the builder signature).
1 parent b87060d commit caa7ca9

18 files changed

Lines changed: 160 additions & 165 deletions

src/mcp/server/_typed_request.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
"""Typed ``send_request`` for server-to-client requests.
1+
"""Typed `send_request` for server-to-client requests.
22
33
`TypedServerRequestMixin` provides a typed `send_request(req) -> Result` over
44
the host's raw `Outbound.send_raw_request`. Spec server-to-client request types
55
have their result type inferred via per-type overloads; custom requests pass
6-
``result_type=`` explicitly.
6+
`result_type=` explicitly.
77
88
If the spec's request set grows substantially, consider declaring the result
9-
mapping on the request types themselves (a ``__mcp_result__`` ClassVar read via
9+
mapping on the request types themselves (a `__mcp_result__` ClassVar read via
1010
a structural protocol) so this overload ladder doesn't need maintaining
1111
per-host-class.
1212
"""
@@ -42,10 +42,10 @@
4242

4343

4444
class TypedServerRequestMixin:
45-
"""Typed ``send_request`` for the server-to-client request set.
45+
"""Typed `send_request` for the server-to-client request set.
4646
4747
Mixed into `Connection` and the server `Context`. Each method constrains
48-
``self`` to `Outbound` so any host with ``send_raw_request`` works.
48+
`self` to `Outbound` so any host with `send_raw_request` works.
4949
"""
5050

5151
@overload
@@ -74,12 +74,12 @@ async def send_request(
7474
"""Send a typed server-to-client request and return its typed result.
7575
7676
For spec request types the result type is inferred. For custom requests
77-
pass ``result_type=`` explicitly.
77+
pass `result_type=` explicitly.
7878
7979
Raises:
8080
MCPError: The peer responded with an error.
8181
NoBackChannelError: No back-channel for server-initiated requests.
82-
KeyError: ``result_type`` omitted for a non-spec request type.
82+
KeyError: `result_type` omitted for a non-spec request type.
8383
"""
8484
raw = await self.send_raw_request(req.method, dump_params(req.params), opts)
8585
cls = result_type if result_type is not None else _RESULT_FOR[type(req)]

src/mcp/server/connection.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
"""`Connection` per-client connection state and the standalone outbound channel.
1+
"""`Connection` - per-client connection state and the standalone outbound channel.
22
3-
Always present on `Context` (never ``None``), even in stateless deployments.
4-
Holds peer info populated at ``initialize`` time, per-connection scratch
5-
``state`` and an ``exit_stack`` for teardown, and an `Outbound` for the
3+
Always present on `Context` (never `None`), even in stateless deployments.
4+
Holds peer info populated at `initialize` time, per-connection scratch
5+
`state` and an `exit_stack` for teardown, and an `Outbound` for the
66
standalone stream (the SSE GET stream in streamable HTTP, or the single duplex
77
stream in stdio).
88
99
`notify` is best-effort: it never raises. If there's no standalone channel
1010
(stateless HTTP) or the stream has been dropped, the notification is
11-
debug-logged and silently discarded server-initiated notifications are
11+
debug-logged and silently discarded - server-initiated notifications are
1212
inherently advisory. `send_raw_request` *does* raise `NoBackChannelError` when
1313
there's no channel; `ping` is the only spec-sanctioned standalone request.
1414
"""
@@ -43,7 +43,7 @@ class Connection(TypedServerRequestMixin):
4343
"""Per-client connection state and standalone-stream `Outbound`.
4444
4545
Constructed by `ServerRunner` once per connection. The peer-info fields are
46-
``None`` until ``initialize`` completes; ``initialized`` is set then.
46+
`None` until `initialize` completes; `initialized` is set then.
4747
"""
4848

4949
def __init__(self, outbound: Outbound, *, has_standalone_channel: bool, session_id: str | None = None) -> None:
@@ -63,8 +63,8 @@ def __init__(self, outbound: Outbound, *, has_standalone_channel: bool, session_
6363
self.exit_stack: AsyncExitStack = AsyncExitStack()
6464
"""Cleanup stack unwound by `ServerRunner` when the connection closes.
6565
66-
Push context managers (``await exit_stack.enter_async_context(...)``)
67-
or callbacks (``exit_stack.push_async_callback(...)``) from handlers or
66+
Push context managers (`await exit_stack.enter_async_context(...)`)
67+
or callbacks (`exit_stack.push_async_callback(...)`) from handlers or
6868
middleware to register per-connection teardown. Unwound LIFO after
6969
`dispatcher.run()` returns, shielded from cancellation."""
7070

@@ -76,13 +76,13 @@ async def send_raw_request(
7676
) -> dict[str, Any]:
7777
"""Send a raw request on the standalone stream.
7878
79-
Low-level `Outbound` channel. Prefer the typed ``send_request`` (from
79+
Low-level `Outbound` channel. Prefer the typed `send_request` (from
8080
`TypedServerRequestMixin`) or the convenience methods below; use this
8181
directly only for off-spec messages.
8282
8383
Raises:
8484
MCPError: The peer responded with an error.
85-
NoBackChannelError: ``has_standalone_channel`` is ``False``.
85+
NoBackChannelError: `has_standalone_channel` is `False`.
8686
"""
8787
if not self.has_standalone_channel:
8888
raise NoBackChannelError(method)
@@ -103,16 +103,16 @@ async def notify(self, method: str, params: Mapping[str, Any] | None) -> None:
103103
logger.debug("dropped %s: standalone stream closed", method)
104104

105105
async def ping(self, *, meta: Meta | None = None, opts: CallOptions | None = None) -> None:
106-
"""Send a ``ping`` request on the standalone stream.
106+
"""Send a `ping` request on the standalone stream.
107107
108108
Raises:
109109
MCPError: The peer responded with an error.
110-
NoBackChannelError: ``has_standalone_channel`` is ``False``.
110+
NoBackChannelError: `has_standalone_channel` is `False`.
111111
"""
112112
await self.send_raw_request("ping", dump_params(None, meta), opts)
113113

114114
async def log(self, level: LoggingLevel, data: Any, logger: str | None = None, *, meta: Meta | None = None) -> None:
115-
"""Send a ``notifications/message`` log entry on the standalone stream. Best-effort."""
115+
"""Send a `notifications/message` log entry on the standalone stream. Best-effort."""
116116
params: dict[str, Any] = {"level": level, "data": data}
117117
if logger is not None:
118118
params["logger"] = logger
@@ -133,9 +133,9 @@ async def send_resource_updated(self, uri: str, *, meta: Meta | None = None) ->
133133
def check_capability(self, capability: ClientCapabilities) -> bool:
134134
"""Return whether the connected client declared the given capability.
135135
136-
Returns ``False`` if ``initialize`` hasn't completed yet.
136+
Returns `False` if `initialize` hasn't completed yet.
137137
"""
138-
# TODO: redesign mirrors v1 ServerSession.check_client_capability
138+
# TODO: redesign - mirrors v1 ServerSession.check_client_capability
139139
# verbatim for parity.
140140
if self.client_capabilities is None:
141141
return False

src/mcp/server/context.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,9 @@ class Context(BaseContext[TransportContext], PeerMixin, TypedServerRequestMixin,
3939
"""Server-side per-request context.
4040
4141
Composes `BaseContext` (forwards to `DispatchContext`, satisfies `Outbound`),
42-
`PeerMixin` (kwarg-style ``sample``/``elicit_*``/``list_roots``/``ping``),
43-
and `TypedServerRequestMixin` (typed ``send_request(req) -> Result``). Adds
44-
``lifespan`` and ``connection``.
42+
`PeerMixin` (kwarg-style `sample`/`elicit_*`/`list_roots`/`ping`),
43+
and `TypedServerRequestMixin` (typed `send_request(req) -> Result`). Adds
44+
`lifespan` and `connection`.
4545
4646
Constructed by `ServerRunner` per inbound request and handed to the user's
4747
handler.
@@ -73,7 +73,7 @@ def connection(self) -> Connection:
7373
def session_id(self) -> str | None:
7474
"""The transport's session id for this connection, when one exists.
7575
76-
Convenience for ``ctx.connection.session_id``. ``None`` on stdio and
76+
Convenience for `ctx.connection.session_id`. `None` on stdio and
7777
stateless HTTP.
7878
"""
7979
return self._connection.session_id
@@ -82,16 +82,16 @@ def session_id(self) -> str | None:
8282
def headers(self) -> Mapping[str, str] | None:
8383
"""Request headers carried by this message, when the transport has them.
8484
85-
Convenience for ``ctx.transport.headers``. ``None`` on stdio.
85+
Convenience for `ctx.transport.headers`. `None` on stdio.
8686
"""
8787
return self.transport.headers
8888

8989
async def log(self, level: LoggingLevel, data: Any, logger: str | None = None, *, meta: Meta | None = None) -> None:
90-
"""Send a request-scoped ``notifications/message`` log entry.
90+
"""Send a request-scoped `notifications/message` log entry.
9191
9292
Uses this request's back-channel (so the entry rides the request's SSE
93-
stream in streamable HTTP), not the standalone stream use
94-
``ctx.connection.log(...)`` for that.
93+
stream in streamable HTTP), not the standalone stream - use
94+
`ctx.connection.log(...)` for that.
9595
"""
9696
params: dict[str, Any] = {"level": level, "data": data}
9797
if logger is not None:
@@ -111,16 +111,16 @@ async def log(self, level: LoggingLevel, data: Any, logger: str | None = None, *
111111

112112

113113
class ServerMiddleware(Protocol[_MwLifespanT]):
114-
"""Context-tier middleware: ``(ctx, method, typed_params, call_next) -> result``.
114+
"""Context-tier middleware: `(ctx, method, typed_params, call_next) -> result`.
115115
116116
Runs *inside* `ServerRunner._on_request` after params validation and
117-
`Context` construction. Wraps registered handlers (including ``ping``) but
118-
not ``initialize``, ``METHOD_NOT_FOUND``, or validation failures. Listed
117+
`Context` construction. Wraps registered handlers (including `ping`) but
118+
not `initialize`, `METHOD_NOT_FOUND`, or validation failures. Listed
119119
outermost-first on `Server.middleware`.
120120
121121
`Server[L].middleware` holds `ServerMiddleware[L]`, so an app-specific
122122
middleware sees `ctx.lifespan: L`. A reusable middleware can be typed
123-
`ServerMiddleware[object]` `Context` is covariant in `LifespanT`, so it
123+
`ServerMiddleware[object]` - `Context` is covariant in `LifespanT`, so it
124124
registers on any `Server[L]`.
125125
"""
126126

src/mcp/server/lowlevel/server.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,10 @@ async def main():
8181
_ParamsT = TypeVar("_ParamsT", bound=BaseModel, default=BaseModel)
8282

8383
RequestHandler = Callable[[ServerRequestContext[LifespanResultT], _ParamsT], Awaitable[HandlerResult]]
84-
"""A registered request handler: ``(ctx, params) -> result``."""
84+
"""A registered request handler: `(ctx, params) -> result`."""
8585

8686
NotificationHandler = Callable[[ServerRequestContext[LifespanResultT], _ParamsT], Awaitable[None]]
87-
"""A registered notification handler: ``(ctx, params) -> None``."""
87+
"""A registered notification handler: `(ctx, params) -> None`."""
8888

8989

9090
@dataclass(frozen=True, slots=True)
@@ -93,7 +93,7 @@ class HandlerEntry(Generic[LifespanResultT]):
9393
9494
Stored in `Server._request_handlers` / `_notification_handlers` and consumed
9595
by `ServerRunner` to validate, build `Context`, and invoke. The handler's
96-
second-argument type is erased to ``Any`` in storage (each entry has a
96+
second-argument type is erased to `Any` in storage (each entry has a
9797
different concrete params type and `Callable` parameters are contravariant);
9898
the precise type is recoverable via `params_type`. The correlation is
9999
enforced at registration time by `Server.add_request_handler`.
@@ -262,11 +262,11 @@ def add_request_handler(
262262
params_type: type[_ParamsT],
263263
handler: RequestHandler[LifespanResultT, _ParamsT],
264264
) -> None:
265-
"""Register a request handler for ``method``.
265+
"""Register a request handler for `method`.
266266
267-
``params_type`` is the model incoming params are validated against
267+
`params_type` is the model incoming params are validated against
268268
before the handler is invoked. It should subclass `RequestParams` so
269-
``_meta`` parses uniformly. Replaces any existing handler for the same
269+
`_meta` parses uniformly. Replaces any existing handler for the same
270270
method (no collision guard against spec methods).
271271
"""
272272
self._request_handlers[method] = HandlerEntry(params_type, handler)
@@ -277,9 +277,9 @@ def add_notification_handler(
277277
params_type: type[_ParamsT],
278278
handler: NotificationHandler[LifespanResultT, _ParamsT],
279279
) -> None:
280-
"""Register a notification handler for ``method``.
280+
"""Register a notification handler for `method`.
281281
282-
``params_type`` should subclass `NotificationParams` so ``_meta``
282+
`params_type` should subclass `NotificationParams` so `_meta`
283283
parses uniformly. Replaces any existing handler.
284284
"""
285285
self._notification_handlers[method] = HandlerEntry(params_type, handler)
@@ -300,11 +300,11 @@ def _has_handler(self, method: str) -> bool:
300300
# --- ServerRegistry protocol (consumed by ServerRunner) ------------------
301301

302302
def get_request_handler(self, method: str) -> HandlerEntry[LifespanResultT] | None:
303-
"""Return the registered entry for a request method, or ``None``."""
303+
"""Return the registered entry for a request method, or `None`."""
304304
return self._request_handlers.get(method)
305305

306306
def get_notification_handler(self, method: str) -> HandlerEntry[LifespanResultT] | None:
307-
"""Return the registered entry for a notification method, or ``None``."""
307+
"""Return the registered entry for a notification method, or `None`."""
308308
return self._notification_handlers.get(method)
309309

310310
def capabilities(self) -> types.ServerCapabilities:

src/mcp/server/runner.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
"""`ServerRunner` per-connection orchestrator over a `Dispatcher`.
1+
"""`ServerRunner` - per-connection orchestrator over a `Dispatcher`.
22
33
`ServerRunner` is the bridge between the dispatcher layer (`on_request` /
44
`on_notify`, untyped dicts) and the user's handler layer (typed `Context`,
55
typed params). One instance per client connection. It:
66
7-
* handles the ``initialize`` handshake and populates `Connection`
8-
* gates requests until initialized (``ping`` exempt)
7+
* handles the `initialize` handshake and populates `Connection`
8+
* gates requests until initialized (`ping` exempt)
99
* looks up the handler in the server's registry, validates params, builds
1010
`Context`, runs the middleware chain, returns the result dict
11-
* drives ``dispatcher.run()`` and the per-connection lifespan
11+
* drives `dispatcher.run()` and the per-connection lifespan
1212
13-
`ServerRunner` holds a `Server` directly `Server` is the registry.
13+
`ServerRunner` holds a `Server` directly - `Server` is the registry.
1414
"""
1515

1616
from __future__ import annotations
@@ -56,8 +56,8 @@ def otel_middleware(next_on_request: OnRequest) -> OnRequest:
5656
"""Dispatch-tier middleware that wraps each request in an OpenTelemetry span.
5757
5858
Mirrors the span shape of the existing `Server._handle_request`: span name
59-
``"MCP handle <method> [<target>]"``, ``mcp.method.name`` attribute, W3C
60-
trace context extracted from ``params._meta`` (SEP-414), and an ERROR
59+
`"MCP handle <method> [<target>]"`, `mcp.method.name` attribute, W3C
60+
trace context extracted from `params._meta` (SEP-414), and an ERROR
6161
status if the handler raises.
6262
"""
6363

@@ -133,8 +133,8 @@ async def run(self, *, task_status: anyio.abc.TaskStatus[None] = anyio.TASK_STAT
133133
"""Drive the dispatcher until the underlying channel closes.
134134
135135
Composes `dispatch_middleware` over `_on_request` and hands the result
136-
to `dispatcher.run()`. ``task_status.started()`` is forwarded so callers
137-
can ``await tg.start(runner.run)`` and resume once the dispatcher is
136+
to `dispatcher.run()`. `task_status.started()` is forwarded so callers
137+
can `await tg.start(runner.run)` and resume once the dispatcher is
138138
ready to accept requests. Once the dispatcher exits,
139139
`connection.exit_stack` is unwound (shielded) so any per-connection
140140
cleanup registered by handlers or middleware runs to completion.
@@ -148,8 +148,8 @@ async def run(self, *, task_status: anyio.abc.TaskStatus[None] = anyio.TASK_STAT
148148
def _compose_on_request(self) -> OnRequest:
149149
"""Wrap `_on_request` in `dispatch_middleware`, outermost-first.
150150
151-
Dispatch-tier middleware sees raw ``(dctx, method, params) -> dict``
152-
and wraps everything initialize, METHOD_NOT_FOUND, validation
151+
Dispatch-tier middleware sees raw `(dctx, method, params) -> dict`
152+
and wraps everything - initialize, METHOD_NOT_FOUND, validation
153153
failures included. `run()` calls this once and hands the result to
154154
`dispatcher.run()`.
155155
"""
@@ -212,7 +212,7 @@ def _handle_initialize(self, params: Mapping[str, Any] | None) -> dict[str, Any]
212212
self.connection.client_info = init.client_info
213213
self.connection.client_capabilities = init.capabilities
214214
# TODO: real version negotiation. This always responds with LATEST,
215-
# which is wrong the server should pick the highest version both
215+
# which is wrong - the server should pick the highest version both
216216
# sides support and compute a per-connection feature set from it.
217217
# See FOLLOWUPS: "Consolidate per-connection mode/negotiation".
218218
self.connection.protocol_version = (

src/mcp/shared/context.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""`BaseContext` the user-facing per-request context.
1+
"""`BaseContext` - the user-facing per-request context.
22
33
Composition over a `DispatchContext`: forwards the transport metadata, the
44
back-channel (`send_raw_request`/`notify`), progress reporting, and the cancel
@@ -43,7 +43,7 @@ def transport(self) -> TransportT:
4343

4444
@property
4545
def cancel_requested(self) -> anyio.Event:
46-
"""Set when the peer sends ``notifications/cancelled`` for this request."""
46+
"""Set when the peer sends `notifications/cancelled` for this request."""
4747
return self._dctx.cancel_requested
4848

4949
@property
@@ -53,7 +53,7 @@ def can_send_request(self) -> bool:
5353

5454
@property
5555
def meta(self) -> RequestParamsMeta | None:
56-
"""The inbound request's ``_meta`` field, if present."""
56+
"""The inbound request's `_meta` field, if present."""
5757
return self._meta
5858

5959
async def send_raw_request(
@@ -66,7 +66,7 @@ async def send_raw_request(
6666
6767
Raises:
6868
MCPError: The peer responded with an error.
69-
NoBackChannelError: ``can_send_request`` is ``False``.
69+
NoBackChannelError: `can_send_request` is `False`.
7070
"""
7171
return await self._dctx.send_raw_request(method, params, opts)
7272

0 commit comments

Comments
 (0)