FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
python-sdk/src/mcp/shared/session.py at main · PawitRoy/python-sdk · GitHub
PawitRoy
/
python-sdk
Public
forked from
modelcontextprotocol/python-sdk
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
python-sdk
/
src
/
mcp
/
shared
/
session.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
394 lines (343 loc) · 14.2 KB
Breadcrumbs
python-sdk
/
src
/
mcp
/
shared
/
session.py
Copy path
File metadata and controls
394 lines (343 loc) · 14.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import
logging
from
collections
.
abc
import
Callable
from
contextlib
import
AsyncExitStack
from
datetime
import
timedelta
from
types
import
TracebackType
from
typing
import
Any
,
Generic
,
TypeVar
import
anyio
import
anyio
.
lowlevel
import
httpx
from
anyio
.
streams
.
memory
import
MemoryObjectReceiveStream
,
MemoryObjectSendStream
from
pydantic
import
BaseModel
from
typing_extensions
import
Self
from
mcp
.
shared
.
exceptions
import
McpError
from
mcp
.
types
import
(
CancelledNotification
,
ClientNotification
,
ClientRequest
,
ClientResult
,
ErrorData
,
JSONRPCError
,
JSONRPCMessage
,
JSONRPCNotification
,
JSONRPCRequest
,
JSONRPCResponse
,
RequestParams
,
ServerNotification
,
ServerRequest
,
ServerResult
,
)
SendRequestT
=
TypeVar
(
"SendRequestT"
,
ClientRequest
,
ServerRequest
)
SendResultT
=
TypeVar
(
"SendResultT"
,
ClientResult
,
ServerResult
)
SendNotificationT
=
TypeVar
(
"SendNotificationT"
,
ClientNotification
,
ServerNotification
)
ReceiveRequestT
=
TypeVar
(
"ReceiveRequestT"
,
ClientRequest
,
ServerRequest
)
ReceiveResultT
=
TypeVar
(
"ReceiveResultT"
,
bound
=
BaseModel
)
ReceiveNotificationT
=
TypeVar
(
"ReceiveNotificationT"
,
ClientNotification
,
ServerNotification
)
RequestId
=
str
|
int
class
RequestResponder
(
Generic
[
ReceiveRequestT
,
SendResultT
]):
"""Handles responding to MCP requests and manages request lifecycle.
This class MUST be used as a context manager to ensure proper cleanup and
cancellation handling:
Example:
with request_responder as resp:
await resp.respond(result)
The context manager ensures:
1. Proper cancellation scope setup and cleanup
2. Request completion tracking
3. Cleanup of in-flight requests
"""
def
__init__
(
self
,
request_id
:
RequestId
,
request_meta
:
RequestParams
.
Meta
|
None
,
request
:
ReceiveRequestT
,
session
:
"""BaseSession[
SendRequestT,
SendNotificationT,
SendResultT,
ReceiveRequestT,
ReceiveNotificationT
]"""
,
on_complete
:
Callable
[[
"RequestResponder[ReceiveRequestT, SendResultT]"
],
Any
],
)
->
None
:
self
.
request_id
=
request_id
self
.
request_meta
=
request_meta
self
.
request
=
request
self
.
_session
=
session
self
.
_completed
=
False
self
.
_cancel_scope
=
anyio
.
CancelScope
()
self
.
_on_complete
=
on_complete
self
.
_entered
=
False
# Track if we're in a context manager
def
__enter__
(
self
)
->
"RequestResponder[ReceiveRequestT, SendResultT]"
:
"""Enter the context manager, enabling request cancellation tracking."""
self
.
_entered
=
True
self
.
_cancel_scope
=
anyio
.
CancelScope
()
self
.
_cancel_scope
.
__enter__
()
return
self
def
__exit__
(
self
,
exc_type
:
type
[
BaseException
]
|
None
,
exc_val
:
BaseException
|
None
,
exc_tb
:
TracebackType
|
None
,
)
->
None
:
"""Exit the context manager, performing cleanup and notifying completion."""
try
:
if
self
.
_completed
:
self
.
_on_complete
(
self
)
finally
:
self
.
_entered
=
False
if
not
self
.
_cancel_scope
:
raise
RuntimeError
(
"No active cancel scope"
)
self
.
_cancel_scope
.
__exit__
(
exc_type
,
exc_val
,
exc_tb
)
async
def
respond
(
self
,
response
:
SendResultT
|
ErrorData
)
->
None
:
"""Send a response for this request.
Must be called within a context manager block.
Raises:
RuntimeError: If not used within a context manager
AssertionError: If request was already responded to
"""
if
not
self
.
_entered
:
raise
RuntimeError
(
"RequestResponder must be used as a context manager"
)
assert
not
self
.
_completed
,
"Request already responded to"
if
not
self
.
cancelled
:
self
.
_completed
=
True
await
self
.
_session
.
_send_response
(
# type: ignore[reportPrivateUsage]
request_id
=
self
.
request_id
,
response
=
response
)
async
def
cancel
(
self
)
->
None
:
"""Cancel this request and mark it as completed."""
if
not
self
.
_entered
:
raise
RuntimeError
(
"RequestResponder must be used as a context manager"
)
if
not
self
.
_cancel_scope
:
raise
RuntimeError
(
"No active cancel scope"
)
self
.
_cancel_scope
.
cancel
()
self
.
_completed
=
True
# Mark as completed so it's removed from in_flight
# Send an error response to indicate cancellation
await
self
.
_session
.
_send_response
(
# type: ignore[reportPrivateUsage]
request_id
=
self
.
request_id
,
response
=
ErrorData
(
code
=
0
,
message
=
"Request cancelled"
,
data
=
None
),
)
@
property
def
in_flight
(
self
)
->
bool
:
return
not
self
.
_completed
and
not
self
.
cancelled
@
property
def
cancelled
(
self
)
->
bool
:
return
self
.
_cancel_scope
.
cancel_called
class
BaseSession
(
Generic
[
SendRequestT
,
SendNotificationT
,
SendResultT
,
ReceiveRequestT
,
ReceiveNotificationT
,
],
):
"""
Implements an MCP "session" on top of read/write streams, including features
like request/response linking, notifications, and progress.
This class is an async context manager that automatically starts processing
messages when entered.
"""
_response_streams
:
dict
[
RequestId
,
MemoryObjectSendStream
[
JSONRPCResponse
|
JSONRPCError
]
]
_request_id
:
int
_in_flight
:
dict
[
RequestId
,
RequestResponder
[
ReceiveRequestT
,
SendResultT
]]
def
__init__
(
self
,
read_stream
:
MemoryObjectReceiveStream
[
JSONRPCMessage
|
Exception
],
write_stream
:
MemoryObjectSendStream
[
JSONRPCMessage
],
receive_request_type
:
type
[
ReceiveRequestT
],
receive_notification_type
:
type
[
ReceiveNotificationT
],
# If none, reading will never time out
read_timeout_seconds
:
timedelta
|
None
=
None
,
)
->
None
:
self
.
_read_stream
=
read_stream
self
.
_write_stream
=
write_stream
self
.
_response_streams
=
{}
self
.
_request_id
=
0
self
.
_receive_request_type
=
receive_request_type
self
.
_receive_notification_type
=
receive_notification_type
self
.
_read_timeout_seconds
=
read_timeout_seconds
self
.
_in_flight
=
{}
self
.
_exit_stack
=
AsyncExitStack
()
async
def
__aenter__
(
self
)
->
Self
:
self
.
_task_group
=
anyio
.
create_task_group
()
await
self
.
_task_group
.
__aenter__
()
self
.
_task_group
.
start_soon
(
self
.
_receive_loop
)
return
self
async
def
__aexit__
(
self
,
exc_type
:
type
[
BaseException
]
|
None
,
exc_val
:
BaseException
|
None
,
exc_tb
:
TracebackType
|
None
,
)
->
bool
|
None
:
await
self
.
_exit_stack
.
aclose
()
# Using BaseSession as a context manager should not block on exit (this
# would be very surprising behavior), so make sure to cancel the tasks
# in the task group.
self
.
_task_group
.
cancel_scope
.
cancel
()
return
await
self
.
_task_group
.
__aexit__
(
exc_type
,
exc_val
,
exc_tb
)
async
def
send_request
(
self
,
request
:
SendRequestT
,
result_type
:
type
[
ReceiveResultT
],
)
->
ReceiveResultT
:
"""
Sends a request and wait for a response. Raises an McpError if the
response contains an error.
Do not use this method to emit notifications! Use send_notification()
instead.
"""
request_id
=
self
.
_request_id
self
.
_request_id
=
request_id
+
1
response_stream
,
response_stream_reader
=
anyio
.
create_memory_object_stream
[
JSONRPCResponse
|
JSONRPCError
](
1
)
self
.
_response_streams
[
request_id
]
=
response_stream
self
.
_exit_stack
.
push_async_callback
(
lambda
:
response_stream
.
aclose
())
self
.
_exit_stack
.
push_async_callback
(
lambda
:
response_stream_reader
.
aclose
())
jsonrpc_request
=
JSONRPCRequest
(
jsonrpc
=
"2.0"
,
id
=
request_id
,
**
request
.
model_dump
(
by_alias
=
True
,
mode
=
"json"
,
exclude_none
=
True
),
)
# TODO: Support progress callbacks
await
self
.
_write_stream
.
send
(
JSONRPCMessage
(
jsonrpc_request
))
try
:
with
anyio
.
fail_after
(
None
if
self
.
_read_timeout_seconds
is
None
else
self
.
_read_timeout_seconds
.
total_seconds
()
):
response_or_error
=
await
response_stream_reader
.
receive
()
except
TimeoutError
:
raise
McpError
(
ErrorData
(
code
=
httpx
.
codes
.
REQUEST_TIMEOUT
,
message
=
(
f"Timed out while waiting for response to "
f"
{
request
.
__class__
.
__name__
}
. Waited "
f"
{
self
.
_read_timeout_seconds
}
seconds."
),
)
)
if
isinstance
(
response_or_error
,
JSONRPCError
):
raise
McpError
(
response_or_error
.
error
)
else
:
return
result_type
.
model_validate
(
response_or_error
.
result
)
async
def
send_notification
(
self
,
notification
:
SendNotificationT
)
->
None
:
"""
Emits a notification, which is a one-way message that does not expect
a response.
"""
jsonrpc_notification
=
JSONRPCNotification
(
jsonrpc
=
"2.0"
,
**
notification
.
model_dump
(
by_alias
=
True
,
mode
=
"json"
,
exclude_none
=
True
),
)
await
self
.
_write_stream
.
send
(
JSONRPCMessage
(
jsonrpc_notification
))
async
def
_send_response
(
self
,
request_id
:
RequestId
,
response
:
SendResultT
|
ErrorData
)
->
None
:
if
isinstance
(
response
,
ErrorData
):
jsonrpc_error
=
JSONRPCError
(
jsonrpc
=
"2.0"
,
id
=
request_id
,
error
=
response
)
await
self
.
_write_stream
.
send
(
JSONRPCMessage
(
jsonrpc_error
))
else
:
jsonrpc_response
=
JSONRPCResponse
(
jsonrpc
=
"2.0"
,
id
=
request_id
,
result
=
response
.
model_dump
(
by_alias
=
True
,
mode
=
"json"
,
exclude_none
=
True
),
)
await
self
.
_write_stream
.
send
(
JSONRPCMessage
(
jsonrpc_response
))
async
def
_receive_loop
(
self
)
->
None
:
async
with
(
self
.
_read_stream
,
self
.
_write_stream
,
):
async
for
message
in
self
.
_read_stream
:
if
isinstance
(
message
,
Exception
):
await
self
.
_handle_incoming
(
message
)
elif
isinstance
(
message
.
root
,
JSONRPCRequest
):
validated_request
=
self
.
_receive_request_type
.
model_validate
(
message
.
root
.
model_dump
(
by_alias
=
True
,
mode
=
"json"
,
exclude_none
=
True
)
)
responder
=
RequestResponder
(
request_id
=
message
.
root
.
id
,
request_meta
=
validated_request
.
root
.
params
.
meta
if
validated_request
.
root
.
params
else
None
,
request
=
validated_request
,
session
=
self
,
on_complete
=
lambda
r
:
self
.
_in_flight
.
pop
(
r
.
request_id
,
None
),
)
self
.
_in_flight
[
responder
.
request_id
]
=
responder
await
self
.
_received_request
(
responder
)
if
not
responder
.
_completed
:
# type: ignore[reportPrivateUsage]
await
self
.
_handle_incoming
(
responder
)
elif
isinstance
(
message
.
root
,
JSONRPCNotification
):
try
:
notification
=
self
.
_receive_notification_type
.
model_validate
(
message
.
root
.
model_dump
(
by_alias
=
True
,
mode
=
"json"
,
exclude_none
=
True
)
)
# Handle cancellation notifications
if
isinstance
(
notification
.
root
,
CancelledNotification
):
cancelled_id
=
notification
.
root
.
params
.
requestId
if
cancelled_id
in
self
.
_in_flight
:
await
self
.
_in_flight
[
cancelled_id
].
cancel
()
else
:
await
self
.
_received_notification
(
notification
)
await
self
.
_handle_incoming
(
notification
)
except
Exception
as
e
:
# For other validation errors, log and continue
logging
.
warning
(
f"Failed to validate notification:
{
e
}
. "
f"Message was:
{
message
.
root
}
"
)
else
:
# Response or error
stream
=
self
.
_response_streams
.
pop
(
message
.
root
.
id
,
None
)
if
stream
:
await
stream
.
send
(
message
.
root
)
else
:
await
self
.
_handle_incoming
(
RuntimeError
(
"Received response with an unknown "
f"request ID:
{
message
}
"
)
)
async
def
_received_request
(
self
,
responder
:
RequestResponder
[
ReceiveRequestT
,
SendResultT
]
)
->
None
:
"""
Can be overridden by subclasses to handle a request without needing to
listen on the message stream.
If the request is responded to within this method, it will not be
forwarded on to the message stream.
"""
async
def
_received_notification
(
self
,
notification
:
ReceiveNotificationT
)
->
None
:
"""
Can be overridden by subclasses to handle a notification without needing
to listen on the message stream.
"""
async
def
send_progress_notification
(
self
,
progress_token
:
str
|
int
,
progress
:
float
,
total
:
float
|
None
=
None
)
->
None
:
"""
Sends a progress notification for a request that is currently being
processed.
"""
async
def
_handle_incoming
(
self
,
req
:
RequestResponder
[
ReceiveRequestT
,
SendResultT
]
|
ReceiveNotificationT
|
Exception
,
)
->
None
:
"""A generic handler for incoming messages. Overwritten by subclasses."""
pass
Back
|
FazBrowse Home
|
New Git URL