xjb!ddlZddlmZmZmZddlmZddlmZm Z m Z ddl m Z m Z mZddlmZddlmZmZddlmZmZdd lmZdd lmZdd lmZdd lmZdd lm Z ddl!m"Z"ddl#m$Z$ejJe&Z'e'Z(ede)e*efZ+edeZ,edGdde e+e,fZ-ededZ.Gddee$e e.Z/ee)e*efzdzZ0 edgee0fZ1 edZ2Gdde e2Z3y)N) AwaitableCallableMapping) dataclass)AnyGenericProtocol) LoggingLevel RequestIdRequestParamsMeta) BaseModel)TypeVar deprecated) Connectionallowed_log_levels) ServerSession) BaseContext)DispatchContext)MCPDeprecationWarning)CloseSSEStreamCallback)Meta)TransportContextLifespanContextT)defaultRequestTT)kw_onlyceZdZUdZeed<eed<eed<eed<dZe ee fdzed<dZ e dzed<dZ edzed <dZedzed <dZedzed <dZedzed <y) ServerRequestContextarPer-request context handed to lowlevel request and notification handlers. Built by `ServerRunner._make_context` for each inbound message. Carries the connection-scoped `ServerSession` (server-to-client requests and notifications), per-request metadata, and any per-message data the transport attached (the HTTP request, SSE stream-close callbacks). sessionlifespan_contextprotocol_versionmethodNparams request_idmetarequestclose_sse_streamclose_standalone_sse_stream)__name__ __module__ __qualname____doc__r__annotations__rstrr#rrr$r r%r r&rr'rr(f/mnt/ssd/data/Dropbox/adrian/sandbox/mcp-query/venv/lib/python3.12/site-packages/mcp/server/context.pyrrs&& K'+FGCH  $+#'J D '%)D d ")#GX_#6:,t3:AE!7$!>Er0r LifespanT_co)r covariantc eZdZdZdddeededededzddf fd Z e defd Z e defd Z e de dzfd Ze dee e fdzfd Zededdddedede dzdedzddf dZxZS)Contexta)Server-side per-request context. Extends `BaseContext` (transport metadata, the raw back-channel, progress reporting) with `lifespan`, `connection`, and request-scoped `log`. Not currently constructed by `ServerRunner`, which hands handlers a `ServerRequestContext` instead. Nr%dctxlifespan connectionr%returnczt|||||_||_t |j ||_y)Nr6)super__init__ _lifespan _connectionrr!_allowed_log_levels)selfr7r8r9r% __class__s r1r=zContext.__init__Bs> D)!%$6j6Q6QSW#X r0c|jS)zKThe server-wide lifespan output (what `Server(..., lifespan=...)` yielded).)r>rAs r1r8zContext.lifespanQs~~r0c|jS)z:The per-client `Connection` for this request's connection.)r?rDs r1r9zContext.connectionVsr0c.|jjS)zThe transport's session id for this connection, when one exists. Convenience for `ctx.connection.session_id`. `None` on stdio and stateless HTTP. )r? session_idrDs r1rGzContext.session_id[s***r0c.|jjS)zRequest headers carried by this message, when the transport has them. Convenience for `ctx.transport.headers`. `None` on stdio. ) transportheadersrDs r1rJzContext.headersds ~~%%%r0zAThe logging capability is deprecated as of 2026-07-28 (SEP-2577).)categoryleveldataloggercK||jvrtjd|y||d}|||d<|r||d<|jd|d{y7w)aSend a request-scoped `notifications/message` log entry. Uses this request's back-channel (so the entry rides the request's SSE stream in streamable HTTP), not the standalone stream - use `ctx.connection.log(...)` for that. On 2026-07-28+ delivery is a per-request opt-in: nothing is sent unless this request's `_meta` carried the reserved log-level key, and entries below the requested level are dropped (debug-logged). Handshake versions send unconditionally, as before. zOdropped notifications/message at %r: not opted in at that level on this requestN)rLrMrN_metaznotifications/message)r@_loggerdebugnotify)rArLrMrNr%r#s r1logz Context.loglsd 00 0 MMkmr s +0$!?  %F8  "F7Okk16:::sAAAAN)r)r*r+r,rrr2rr r=propertyr8r9r.rGrrJrrr rrrT __classcell__)rBs@r1r5r58s&*. Y./ Y Y  Y  $& Y  Y, J  +C$J++&c*T1&&S^st;jn;|;3;d ;\`cg\g;sw;u;r0r5zServerRequestContext[Any, Any] _MwLifespanTc.eZdZdZdeeefdedefdZ y)ServerMiddlewareaiContext-tier middleware: `(ctx, call_next) -> result`. Runs at the top of `ServerRunner._on_request` / `_on_notify` after `ctx` is built but before any validation, lookup, or handshake. Wraps every inbound request and notification: `initialize`, the pre-init gate, `METHOD_NOT_FOUND`, params validation, the handler call, and `notifications/initialized` all run inside `call_next(ctx)`. `notifications/cancelled` is observed too; the dispatcher applies the cancellation itself, then forwards the notification. A request-side failure reaches the middleware as a raised `MCPError` (or `ValidationError` for malformed params) so observation/logging middleware can record it. Listed outermost-first on `Server.middleware`. The method and the raw inbound params are `ctx.method` and `ctx.params` (no model validation has happened yet). To rewrite either before the handler runs, pass an adjusted context: `await call_next(replace(ctx, params=...))`. `ctx.request_id is None` distinguishes a notification from a request. For notifications `call_next(ctx)` returns `None` (a dropped or unhandled notification also returns `None`) and the middleware's own return value is discarded. !!! warning `initialize` is handled inline - the dispatcher does not read further inbound messages until the middleware chain returns. Awaiting a server-to-client request (`ctx.session.send_request`, `send_ping`, ...) while handling `initialize` therefore deadlocks the connection: the response can never be dequeued. Send-and-forget notifications are safe. `initialize` is observed but not rewritable: the post-chain handshake commit reads the wire params, so to veto the handshake raise *before* `call_next()`. `Server[L].middleware` holds `ServerMiddleware[L]`, so an app-specific middleware sees `ctx.lifespan_context: L`. While the context is the mutable `ServerRequestContext` dataclass it is invariant in `L`, so a reusable middleware should be typed `ServerMiddleware[Any]` to register on any `Server[L]`. ctx call_nextr:c KywrUr/)rAr[r\s r1__call__zServerMiddleware.__call__s sN) r)r*r+r,rrXrCallNext HandlerResultr^r/r0r1rZrZs3$V !,"3 4  r0rZ)4loggingcollections.abcrrr dataclassesrtypingrrr mcp_typesr r r pydanticr typing_extensionsrrmcp.server.connectionrrmcp.server.sessionrmcp.shared.contextrmcp.shared.dispatcherrmcp.shared.exceptionsrmcp.shared.messagermcp.shared.peerrmcp.shared.transport_contextr getLoggerr)rNrQdictr.rrrr2r5r`r_rXrZr/r0r1rrs,88!))@@1@,*175 9   8 $ -tCH~F :s + 4F7#3X#=>FF,~sdC I;k*+W\-BI;XDcN*T1  56 -8PP Q< ~& 0x -0r0