-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
1319 lines (1097 loc) · 46.4 KB
/
server.py
File metadata and controls
1319 lines (1097 loc) · 46.4 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import functools
import httpx
import inspect
import logging
import mcp.types
import pickle
from dataclasses import dataclass
from log.log import get_logger, set_log_level
from mcp.server import fastmcp
from mcp.server.elicitation import (
AcceptedElicitation,
CancelledElicitation,
DeclinedElicitation,
ElicitationResult,
ElicitSchemaModelT,
_validate_elicitation_schema,
)
from mcp.server.session import ServerSession
from mcp.server.streamable_http import (
MCP_SESSION_ID_HEADER,
StreamableHTTPServerTransport,
)
from mcp.shared.message import ServerMessageMetadata
from rbt.mcp.v1.session_rbt import Session
from rbt.v1alpha1.errors_pb2 import StateNotConstructed
from reboot.aio.applications import Application
from rebootdev.aio.servicers import Servicer
from reboot.aio.contexts import EffectValidation, WorkflowContext
from reboot.aio.external import ExternalContext, InitializeContext
from reboot.aio.types import StateRef
from reboot.aio.workflows import at_least_once
from reboot.mcp.event_store import (
DurableEventStore,
replay,
qualified_stream_id,
)
from reboot.mcp.servicers.session import (
SessionServicer,
_servers,
_context,
)
from reboot.mcp.servicers.stream import StreamServicer
from reboot.std.collections.v1 import sorted_map
from rebootdev.aio.headers import SERVER_ID_HEADER, STATE_REF_HEADER
from rebootdev.aio.backoff import Backoff
from rebootdev.memoize.v1.memoize_rbt import Memoize
from rebootdev.settings import DOCS_BASE_URL
from starlette.applications import Starlette
from starlette.datastructures import MutableHeaders
from starlette.requests import Request
from starlette.responses import Response, StreamingResponse
from starlette.routing import Route
from starlette.types import Receive, Scope, Send
from types import MethodType
from typing import Any, Awaitable, Callable, Literal, Protocol, TypeAlias, cast
from uuid import uuid4, uuid5
from uuid7 import create as uuid7 # type: ignore[import-untyped]
logger = get_logger(__name__)
class DurableSession:
_session: ServerSession
_context: WorkflowContext
_event_aliases: set[str]
def __init__(self, session: ServerSession, context: WorkflowContext):
self._session = session
self._context = context
self._event_aliases = set()
def _event_id(self, function_name: str, why: str):
event_alias = f"{function_name}: {why}"
assert self._context is not None
if self._context.within_loop():
event_alias += f" #{self._context.task.iteration}"
if event_alias in self._event_aliases:
raise TypeError(
f"Looks like you're calling `{function_name}()` "
"more than once with the same `why`"
)
self._event_aliases.add(event_alias)
workflow_id = self._context.workflow_id
assert workflow_id is not None
# Generate a unique but deterministic ID for this event based
# on the alias and this workflow (which is unique per
# request).
return uuid5(workflow_id, event_alias).hex
async def send_resource_list_changed(self, why: str) -> None:
"""
Send a resource list changed notification.
Args:
why: Description of why the resource list changed,
used to durably differentiate resource list
changed events that are sent to client
"""
event_id = self._event_id("send_resource_list_changed", why)
await self._session.send_notification(
mcp.types.ServerNotification(
mcp.types.ResourceListChangedNotification(
# TODO: figure out why `mypy` requires
# passing `method` which has a default.
method="notifications/resources/list_changed",
params=mcp.types.NotificationParams(
_meta=mcp.types.NotificationParams.Meta(
rebootEventId=str(event_id),
),
),
),
),
)
async def send_tool_list_changed(self, why: str) -> None:
"""
Send a tool list changed notification.
Args:
why: Description of why the resource list changed,
used to durably differentiate resource list
changed events that are sent to client
"""
event_id = self._event_id("send_tool_list_changed", why)
await self._session.send_notification(
mcp.types.ServerNotification(
mcp.types.ToolListChangedNotification(
# TODO: figure out why `mypy` requires
# passing `method` which has a default.
method="notifications/tools/list_changed",
params=mcp.types.NotificationParams(
_meta=mcp.types.NotificationParams.Meta(
rebootEventId=str(event_id),
),
),
),
),
)
async def send_prompt_list_changed(self, why: str) -> None:
"""
Send a prompt list changed notification.
Args:
why: Description of why the resource list changed,
used to durably differentiate resource list
changed events that are sent to client
"""
event_id = self._event_id("send_prompt_list_changed", why)
await self._session.send_notification(
mcp.types.ServerNotification(
mcp.types.PromptListChangedNotification(
# TODO: figure out why `mypy` requires
# passing `method` which has a default.
method="notifications/prompts/list_changed",
params=mcp.types.NotificationParams(
_meta=mcp.types.NotificationParams.Meta(
rebootEventId=str(event_id),
),
),
),
),
)
class DurableContextProtocol(Protocol):
_event_aliases: set[str]
session: DurableSession
async def report_progress(
self,
progress: float,
total: float | None = None,
message: str | None = None,
) -> None:
"""Report progress for the current operation.
Args:
progress: Current progress value e.g. 24
total: Optional total value e.g. 100
message: Optional message e.g. Starting render...
"""
...
async def log(
self,
level: Literal["debug", "info", "warning", "error"],
message: str,
*,
logger_name: str | None = None,
) -> None:
"""Send a log message to the client.
Args:
level: Log level (debug, info, warning, error)
message: Log message
logger_name: Optional logger name
**data: Additional structured data to include
"""
...
async def debug(self, message: str) -> None:
"""Send a debug log message."""
...
async def info(self, message: str) -> None:
"""Send an info log message."""
...
async def warning(self, message: str) -> None:
"""Send a warning log message."""
...
async def error(self, message: str) -> None:
"""Send an error log message."""
...
async def elicit(
self,
message: str,
schema: type[ElicitSchemaModelT],
) -> ElicitationResult:
"""
Elicit information from the client/user.
This method can be used to interactively ask for additional
information from the client within a tool's execution. The
client might display the message to the user and collect a
response according to the provided schema. Or in case a client
is an agent, it might decide how to handle the elicitation --
either by asking the user or automatically generating a
response.
Args:
schema: A Pydantic model class defining the expected
response structure, according to the
specification, only primive types are allowed.
message: Optional message to present to the user. If not
provided, will use a default message based on the
schema
Returns:
An ElicitationResult containing the action taken and the
data if accepted
Note:
Check the result.action to determine if the user accepted,
declined, or cancelled. The result.data will only be
populated if action is "accept" and validation succeeded.
"""
...
class DurableContext(WorkflowContext, DurableContextProtocol):
pass
@dataclass(kw_only=True, frozen=True)
class Resource:
fn: mcp.types.AnyFunction
uri: str
name: str | None
title: str | None
description: str | None
mime_type: str | None
@dataclass(kw_only=True, frozen=True)
class Prompt:
func: mcp.types.AnyFunction
name: str | None
title: str | None
description: str | None
@dataclass(kw_only=True, frozen=True)
class Tool:
fn: mcp.types.AnyFunction
name: str | None
title: str | None
description: str | None
annotations: mcp.types.ToolAnnotations | None
structured_output: bool | None
LogLevel: TypeAlias = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
class DurableMCP:
"""
Proxy for `fastmcp.FastMCP`, but wrapping tools, prompts, and
resources appropriately to make them durable.
NOTE: this class explicitly does NOT extend from `fastmcp.FastMCP`
so that we don't mislead users into thinking some features are
implemented that are not.
"""
_log_level: LogLevel
_resources: list[Resource]
_prompts: list[Prompt]
_tools: list[Tool]
def __init__(
self,
*,
path: str,
log_level: LogLevel = "WARNING",
):
self._log_level = log_level
self._path = path
self._resources = []
self._prompts = []
self._tools = []
set_log_level(logging.getLevelNamesMapping()[log_level])
@property
def path(self):
return self._path
def servicers(self):
return [SessionServicer, StreamServicer] + sorted_map.servicers()
def resource(
self,
uri: str,
*,
name: str | None = None,
title: str | None = None,
description: str | None = None,
mime_type: str | None = None,
) -> Callable[[mcp.types.AnyFunction], mcp.types.AnyFunction]:
"""Decorator to register a function as a resource.
The function will be called when the resource is read to generate its content.
The function can return:
- str for text content
- bytes for binary content
- other types will be converted to JSON
If the URI contains parameters (e.g. "resource://{param}") or the function
has parameters, it will be registered as a template resource.
Args:
uri: URI for the resource (e.g. "resource://my-resource" or "resource://{param}")
name: Optional name for the resource
title: Optional human-readable title for the resource
description: Optional description of the resource
mime_type: Optional MIME type for the resource
Example:
@server.resource("resource://my-resource")
def get_data() -> str:
return "Hello, world!"
@server.resource("resource://my-resource")
async get_data() -> str:
data = await fetch_data()
return f"Hello, world! {data}"
@server.resource("resource://{city}/weather")
def get_weather(city: str) -> str:
return f"Weather for {city}"
@server.resource("resource://{city}/weather")
async def get_weather(city: str) -> str:
data = await fetch_weather(city)
return f"Weather for {city}: {data}"
"""
# Check if user passed function directly instead of calling decorator.
if callable(uri):
raise TypeError(
"The @resource decorator was used incorrectly. "
"Did you forget to call it? Use @resource('uri') instead of @resource"
)
def decorator(fn: mcp.types.AnyFunction) -> mcp.types.AnyFunction:
self._resources.append(
Resource(
fn=fn,
uri=uri,
name=name,
title=title,
description=description,
mime_type=mime_type,
)
)
return fn
return decorator
def add_resource(self, resource: fastmcp.resources.Resource) -> None:
# Where as `add_tool()` is a great insertion point,
# `add_resource` gives us an already modified function which
# does not pickle to the child process by default. This
# probably isn't an issue as mostly folks will just use the
# decorator, but if it is, we can try extracting everything
# from `resource`? We also have to override the `resource()`
# decorator anyway to get templates.
raise NotImplementedError("Use `resource()` decorator instead")
def prompt(
self,
name: str | None = None,
title: str | None = None,
description: str | None = None,
) -> Callable[[mcp.types.AnyFunction], mcp.types.AnyFunction]:
"""Decorator to register a prompt.
Args:
name: Optional name for the prompt (defaults to function name)
title: Optional human-readable title for the prompt
description: Optional description of what the prompt does
Example:
@server.prompt()
def analyze_table(table_name: str) -> list[Message]:
schema = read_table_schema(table_name)
return [
{
"role": "user",
"content": f"Analyze this schema:\n{schema}"
}
]
@server.prompt()
async def analyze_file(path: str) -> list[Message]:
content = await read_file(path)
return [
{
"role": "user",
"content": {
"type": "resource",
"resource": {
"uri": f"file://{path}",
"text": content
}
}
}
]
"""
# Check if user passed function directly instead of calling decorator.
if callable(name):
raise TypeError(
"The @prompt decorator was used incorrectly. "
"Did you forget to call it? Use @prompt() instead of @prompt"
)
def decorator(func: mcp.types.AnyFunction) -> mcp.types.AnyFunction:
self._prompts.append(
Prompt(
func=func,
name=name,
title=title,
description=description,
),
)
return func
return decorator
def add_prompt(self, prompt: fastmcp.prompts.Prompt) -> None:
# Where as `add_tool()` is a great insertion point,
# `add_prompt` gives us an already modified function which
# does not pickle to the child process by default. This
# probably isn't an issue as mostly folks will just use the
# decorator, but if it is, we can try extracting everything
# from `prompt`?
raise NotImplementedError("Use `prompt()` decorator instead")
def tool(
self,
name: str | None = None,
title: str | None = None,
description: str | None = None,
annotations: mcp.types.ToolAnnotations | None = None,
structured_output: bool | None = None,
) -> Callable[[mcp.types.AnyFunction], mcp.types.AnyFunction]:
"""Decorator to register a tool.
Tools can optionally request a Context object by adding a parameter with the
Context type annotation. The context provides access to MCP capabilities like
logging, progress reporting, and resource access.
Args:
name: Optional name for the tool (defaults to function name)
title: Optional human-readable title for the tool
description: Optional description of what the tool does
annotations: Optional ToolAnnotations providing additional tool information
structured_output: Controls whether the tool's output is structured or unstructured
- If None, auto-detects based on the function's return type annotation
- If True, unconditionally creates a structured tool (return type annotation permitting)
- If False, unconditionally creates an unstructured tool
Example:
@server.tool()
def my_tool(x: int) -> str:
return str(x)
@server.tool()
def tool_with_context(x: int, ctx: Context) -> str:
ctx.info(f"Processing {x}")
return str(x)
@server.tool()
async def async_tool(x: int, context: Context) -> str:
await context.report_progress(50, 100)
return str(x)
"""
# Check if user passed function directly instead of calling decorator
if callable(name):
raise TypeError(
"The @tool decorator was used incorrectly. Did you forget to call it? Use @tool() instead of @tool"
)
def decorator(fn: mcp.types.AnyFunction) -> mcp.types.AnyFunction:
self.add_tool(
fn,
name=name,
title=title,
description=description,
annotations=annotations,
structured_output=structured_output,
)
return fn
return decorator
def add_tool(
self,
fn: mcp.types.AnyFunction,
name: str | None = None,
title: str | None = None,
description: str | None = None,
annotations: mcp.types.ToolAnnotations | None = None,
structured_output: bool | None = None,
) -> None:
self._tools.append(
Tool(
fn=fn,
name=name,
title=title,
description=description,
annotations=annotations,
structured_output=structured_output,
)
)
def application(
self,
*,
servicers: list[type[Servicer]] | None = None,
initialize: Callable[[InitializeContext], Awaitable[None]]
| None = None,
) -> Application:
"""
:param servicers: (optional) the types of Reboot-powered servicers that
this Application will serve.
:param initialize: (optional) will be called after the Application's
servicers have started for the first time, so that
it can perform initialization logic (e.g.,
constructing some well-known durable data structures,
loading some data, etc. It must do so in the context
of the given InitializeContext.
Returns a Reboot `Application` for running the MCP tools,
resources, prompts, etc that were defined.
"""
async def default_initialize(context: InitializeContext) -> None:
# Do any app internal initialization here.
if initialize is not None:
await initialize(context)
application = Application(
servicers=(servicers or []) + self.servicers(),
initialize=default_initialize,
)
application.http.mount(
self._path,
factory=self.streamable_http_app_factory,
)
return application
@property
def streamable_http_app_factory(self):
return functools.partial(
_streamable_http_app,
self._log_level,
self._path,
self._resources,
self._prompts,
self._tools,
)
def _streamable_http_app(
log_level: LogLevel,
path: str,
resources: list[Resource],
prompts: list[Prompt],
tools: list[Tool],
external_context_from_request: Callable[[Request], ExternalContext],
):
mcp = fastmcp.FastMCP(log_level=log_level)
for resource in resources:
mcp.resource(
resource.uri,
name=resource.name,
title=resource.title,
description=resource.description,
mime_type=resource.mime_type,
)(resource.fn)
for prompt in prompts:
mcp.prompt(
name=prompt.name,
title=prompt.title,
description=prompt.description,
)(prompt.func)
for tool in tools:
mcp.add_tool(
_wrap_tool(tool.fn),
name=tool.name,
title=tool.title,
description=tool.description,
annotations=tool.annotations,
structured_output=tool.structured_output,
)
_servers[path] = mcp._mcp_server
return Starlette(
routes=[
Route(
"/{path:path}",
endpoint=StreamableHTTPASGIApp(
path,
external_context_from_request,
),
),
],
)
def _wrap_tool(fn: mcp.types.AnyFunction) -> mcp.types.AnyFunction:
signature = inspect.signature(fn)
wrapper_parameters = [
# Always include the `context` parameter so we can access
# session specific things.
inspect.Parameter(
"ctx",
kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=fastmcp.Context,
)
]
context_parameter_names = []
for parameter_name, parameter in signature.parameters.items():
annotation = parameter.annotation
if (
isinstance(annotation, type) and
issubclass(annotation, fastmcp.Context)
):
raise TypeError(
"`DurableMCP` only injects `DurableContext` not `Context`")
if (
isinstance(annotation, type) and
issubclass(annotation, DurableContext)
):
context_parameter_names.append(parameter_name)
else:
wrapper_parameters.append(parameter)
wrapper_signature = signature.replace(parameters=wrapper_parameters)
async def wrapper(
ctx: fastmcp.Context,
context: WorkflowContext,
*args,
**kwargs,
):
# To account for the lack of "intersection" types in
# Python (which is actively being worked on), we instead
# create a new dynamic `DurableContext` instance that
# inherits from the instance of `WorkflowContext` that we
# already have.
context.__class__ = DurableContext
context = cast(DurableContext, context)
# Now we add the `DurableContextProtocol` properties.
context._event_aliases = set()
context.session = DurableSession(ctx.session, context)
async def report_progress(
self,
progress: float,
total: float | None = None,
message: str | None = None,
) -> None:
progress_token = (
ctx.request_context.meta.progressToken
if ctx.request_context.meta else None
)
if progress_token is None:
return
# TODO: consider tracking all reported progress and if
# it has gone "backwards" provide a nice error so
# developers can fix their bug (presumably they don't
# ever want the progress to go "backwards").
event_alias = (
f"report_progress(progress={progress}, total={total}, "
f"message={message})"
)
assert context is not None
if context.within_loop():
event_alias += f" #{context.task.iteration}"
if event_alias in self._event_aliases:
raise TypeError(
f"Looks like you're calling `report_progress()` "
"more than once with the same arguments"
)
self._event_aliases.add(event_alias)
workflow_id = context.workflow_id
assert workflow_id is not None
# Generate a unique but deterministic ID for this
# event based on the alias and this workflow (which is
# unique per request).
event_id = uuid5(workflow_id, event_alias).hex
await ctx.session.send_notification(
mcp.types.ServerNotification(
mcp.types.ProgressNotification(
# TODO: figure out why `mypy` requires
# passing `method` which has a default.
method="notifications/progress",
params=mcp.types.ProgressNotificationParams(
progressToken=progress_token,
progress=progress,
total=total,
message=message,
_meta=mcp.types.NotificationParams.Meta(
rebootEventId=str(event_id),
),
),
),
),
related_request_id=ctx.request_id,
)
context.report_progress = MethodType(report_progress, context) # type: ignore[method-assign]
async def log(
self,
level: Literal["debug", "info", "warning", "error"],
message: str,
*,
logger_name: str | None = None,
) -> None:
event_alias = (
f"log(level='{level}', message='{message}', logger_name={logger_name})"
)
assert context is not None
if context.within_loop():
event_alias += f" #{context.task.iteration}"
if event_alias in self._event_aliases:
raise TypeError(
"Looks like you're trying to `log()` "
"more than once with the same arguments"
)
self._event_aliases.add(event_alias)
workflow_id = context.workflow_id
assert workflow_id is not None
# Generate a unique but deterministic ID for this
# event based on the alias and this workflow (which is
# unique per request).
event_id = uuid5(workflow_id, event_alias).hex
await ctx.session.send_notification(
mcp.types.ServerNotification(
mcp.types.LoggingMessageNotification(
# TODO: figure out why `mypy` requires
# passing `method` which has a default.
method="notifications/message",
params=mcp.types.LoggingMessageNotificationParams(
level=level,
data=message,
logger=logger_name,
_meta=mcp.types.NotificationParams.Meta(
rebootEventId=str(event_id),
),
),
)
),
related_request_id=ctx.request_id,
)
context.log = MethodType(log, context) # type: ignore[method-assign]
async def debug(self, message: str) -> None:
await self.log("debug", message)
context.debug = MethodType(debug, context) # type: ignore[method-assign]
async def info(self, message: str) -> None:
await self.log("info", message)
context.info = MethodType(info, context) # type: ignore[method-assign]
async def warning(self, message: str) -> None:
await self.log("warning", message)
context.warning = MethodType(warning, context) # type: ignore[method-assign]
async def error(self, message: str) -> None:
await self.log("error", message)
context.error = MethodType(error, context) # type: ignore[method-assign]
async def elicit(
self,
message: str,
schema: type[ElicitSchemaModelT],
) -> ElicitationResult:
event_alias = (
f"elicit(message='{message}', schema={type(schema).__name__})"
)
assert context is not None
if context.within_loop():
event_alias += f" #{context.task.iteration}"
if event_alias in self._event_aliases:
raise TypeError(
"Looks like you're trying to `elicit()` "
"more than once with the same arguments"
)
self._event_aliases.add(event_alias)
workflow_id = context.workflow_id
assert workflow_id is not None
memoize = Memoize.ref(uuid5(workflow_id, event_alias).hex)
# Initial reset, only done once per workflow, we've
# already accounted for a possible loop iteration in
# the `event_alias` above.
await memoize.per_workflow(event_alias).Reset(context)
status = await memoize.always().Status(context)
if not status.started:
await memoize.always().Start(context)
else:
message = (
f"Sorry, we got disconnected and need to try again: {message}"
)
async def send_request_and_wait_for_result():
# Generate a unique and _random_ ID for this event because
# we want to send it _everytime_ since the client is not
# also durable.
event_id = uuid4().hex
# THIS CODE IS MORE OR LESS COPIED FROM
# `mcp.server.elicitation.elicit_with_validation()`
# because there was not a good way to override that
# functionality.
#
# Validate that schema only contains primitive types and
# fail loudly if not.
_validate_elicitation_schema(schema)
json_schema = schema.model_json_schema()
return await ctx.session.send_request(
mcp.types.ServerRequest(
mcp.types.ElicitRequest(
method="elicitation/create",
params=mcp.types.ElicitRequestParams(
message=message,
requestedSchema=json_schema,
_meta=mcp.types.RequestParams.Meta(
rebootEventId=str(event_id),
),
),
)
),
mcp.types.ElicitResult,
metadata=ServerMessageMetadata(
related_request_id=ctx.request_id,
),
)
result = await at_least_once(
"Send request, wait for result",
context,
send_request_and_wait_for_result,
type=mcp.types.ElicitResult,
)
if result.action == "accept" and result.content:
# Validate and parse the content using the schema.
validated_data = schema.model_validate(result.content)
return AcceptedElicitation(data=validated_data)
elif result.action == "decline":
return DeclinedElicitation()
elif result.action == "cancel":
return CancelledElicitation()
else:
# This should never happen, but handle it just in case.
raise ValueError(
f"Unexpected elicitation action: {result.action}"
)
context.elicit = MethodType(elicit, context) # type: ignore[method-assign]
for context_parameter_name in context_parameter_names:
kwargs[context_parameter_name] = context
bound = signature.bind(*args, **kwargs)
bound.apply_defaults()
try:
if fastmcp.tools.base._is_async_callable(fn):
return await fn(**dict(bound.arguments))
return fn(**dict(bound.arguments))
except:
import traceback
traceback.print_exc()
raise
async def wrapper_validating_effects(
ctx: fastmcp.Context,
*args,
**kwargs,
):
context: WorkflowContext | None = _context.get()
assert context is not None
# Checkpoint the context since it is the `IdempotencyManager`.
checkpoint = context.checkpoint()
result = await wrapper(ctx, context, *args, **kwargs)
if context._effect_validation == EffectValidation.DISABLED:
return result
# Effect validation is enabled.
logger.info(
f"Re-running tool '{fn.__name__}' "