forked from lastmile-ai/mcp-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_aggregator.py
More file actions
1444 lines (1258 loc) · 57.7 KB
/
Copy pathmcp_aggregator.py
File metadata and controls
1444 lines (1258 loc) · 57.7 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
from typing import List, Literal, Dict, Optional, TypeVar, TYPE_CHECKING
from opentelemetry import trace
from pydantic import BaseModel
from mcp.client.session import ClientSession
from mcp.server.lowlevel.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import (
CallToolResult,
GetPromptResult,
ListPromptsResult,
ListToolsResult,
ListResourcesResult,
ReadResourceResult,
ServerCapabilities,
Prompt,
Tool,
TextContent,
Resource,
)
from mcp_agent.logging.event_progress import ProgressAction
from mcp_agent.logging.logger import get_logger
from mcp_agent.tracing.semconv import GEN_AI_AGENT_NAME, GEN_AI_TOOL_NAME
from mcp_agent.tracing.telemetry import get_tracer, record_attributes
from mcp_agent.mcp.gen_client import gen_client
from mcp_agent.core.context_dependent import ContextDependent
from mcp_agent.mcp.mcp_agent_client_session import MCPAgentClientSession
from mcp_agent.mcp.mcp_connection_manager import MCPConnectionManager
if TYPE_CHECKING:
from mcp_agent.core.context import Context
logger = get_logger(
__name__
) # This will be replaced per-instance when agent_name is available
SEP = "_"
# Define type variables for the generalized method
T = TypeVar("T")
R = TypeVar("R")
class NamespacedTool(BaseModel):
"""
A tool that is namespaced by server name.
"""
tool: Tool
server_name: str
namespaced_tool_name: str
class NamespacedPrompt(BaseModel):
"""
A prompt that is namespaced by server name.
"""
prompt: Prompt
server_name: str
namespaced_prompt_name: str
class NamespacedResource(BaseModel):
"""
A resource that is namespaced by server name.
"""
resource: Resource
server_name: str
namespaced_resource_name: str
class MCPAggregator(ContextDependent):
"""
Aggregates multiple MCP servers. When a developer calls, e.g. call_tool(...),
the aggregator searches all servers in its list for a server that provides that tool.
"""
initialized: bool = False
"""Whether the aggregator has been initialized with tools and resources from all servers."""
connection_persistence: bool = False
"""Whether to maintain a persistent connection to the server."""
server_names: List[str]
"""A list of server names to connect to."""
async def __aenter__(self):
await self.initialize()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()
def __init__(
self,
server_names: List[str],
connection_persistence: bool = True, # Default to True for better stability
context: Optional["Context"] = None,
name: str = None,
**kwargs,
):
"""
:param server_names: A list of server names to connect to.
:param connection_persistence: Whether to maintain persistent connections to servers (default: True).
Note: The server names must be resolvable by the gen_client function, and specified in the server registry.
"""
super().__init__(
context=context,
**kwargs,
)
self.server_names = server_names
self.connection_persistence = connection_persistence
self.agent_name = name
self._persistent_connection_manager: MCPConnectionManager = None
# Set up logger with agent name in namespace if available
global logger
logger_name = f"{__name__}.{name}" if name else __name__
logger = get_logger(logger_name)
# Maps namespaced_tool_name -> namespaced tool info
self._namespaced_tool_map: Dict[str, NamespacedTool] = {}
# Maps server_name -> list of tools
self._server_to_tool_map: Dict[str, List[NamespacedTool]] = {}
self._tool_map_lock = asyncio.Lock()
# Maps namespaced_prompt_name -> namespaced prompt info
self._namespaced_prompt_map: Dict[str, NamespacedPrompt] = {}
# Cache for prompt objects, maps server_name -> list of prompt objects
self._server_to_prompt_map: Dict[str, List[NamespacedPrompt]] = {}
self._prompt_map_lock = asyncio.Lock()
# Maps namespaced_resource_name -> namespaced resource info
self._namespaced_resource_map: Dict[str, NamespacedResource] = {}
# Cache for resource objects, maps server_name -> list of resource objects
self._server_to_resource_map: Dict[str, List[NamespacedResource]] = {}
self._resource_map_lock = asyncio.Lock()
async def initialize(self, force: bool = False):
"""Initialize the application."""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(
f"{self.__class__.__name__}.initialize"
) as span:
span.set_attribute("server_names", self.server_names)
span.set_attribute("force", force)
span.set_attribute("connection_persistence", self.connection_persistence)
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
span.set_attribute("initialized", self.initialized)
if self.initialized and not force:
return
# Keep a connection manager to manage persistent connections for this aggregator
if self.connection_persistence:
# Try to get existing connection manager from context
# TODO: saqadri (FA1) - verify
# Initialize connection manager tracking on the context if not present
# These are placed on the context since it's shared across aggregators
connection_manager: MCPConnectionManager | None = None
if not hasattr(self.context, "_mcp_connection_manager_lock"):
self.context._mcp_connection_manager_lock = asyncio.Lock()
if not hasattr(self.context, "_mcp_connection_manager_ref_count"):
self.context._mcp_connection_manager_ref_count = int(0)
async with self.context._mcp_connection_manager_lock:
self.context._mcp_connection_manager_ref_count += 1
if hasattr(self.context, "_mcp_connection_manager"):
connection_manager = self.context._mcp_connection_manager
else:
connection_manager = MCPConnectionManager(
self.context.server_registry
)
await connection_manager.__aenter__()
self.context._mcp_connection_manager = connection_manager
self._persistent_connection_manager = connection_manager
await self.load_servers()
span.add_event("initialized")
self.initialized = True
async def close(self):
"""
Close all persistent connections when the aggregator is deleted.
"""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(f"{self.__class__.__name__}.close") as span:
span.set_attribute("server_names", self.server_names)
span.set_attribute("connection_persistence", self.connection_persistence)
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
# TODO: saqadri (FA1) - Verify implementation
if (
not self.connection_persistence
or not self._persistent_connection_manager
):
self.initialized = False
return
try:
# We only need to manage reference counting if we're using connection persistence
if hasattr(self.context, "_mcp_connection_manager_lock") and hasattr(
self.context, "_mcp_connection_manager_ref_count"
):
async with self.context._mcp_connection_manager_lock:
# Decrement the reference count
self.context._mcp_connection_manager_ref_count -= 1
current_count = self.context._mcp_connection_manager_ref_count
logger.debug(
f"Decremented connection ref count to {current_count}"
)
# Only proceed with cleanup if we're the last user
if current_count == 0:
logger.info(
"Last aggregator closing, shutting down all persistent connections..."
)
if (
hasattr(self.context, "_mcp_connection_manager")
and self.context._mcp_connection_manager
== self._persistent_connection_manager
):
# Add timeout protection for the disconnect operation
try:
await asyncio.wait_for(
self._persistent_connection_manager.disconnect_all(),
timeout=5.0,
)
except asyncio.TimeoutError:
logger.warning(
"Timeout during disconnect_all(), forcing shutdown"
)
# Ensure the exit method is called regardless
try:
await self._persistent_connection_manager.__aexit__(
None, None, None
)
except Exception as e:
logger.warning(
f"Error during connection manager cleanup: {e}"
)
# Clean up the connection manager from the context
delattr(self.context, "_mcp_connection_manager")
logger.info(
"Connection manager successfully closed and removed from context"
)
else:
logger.debug(
f"Aggregator closing with ref count {current_count}, "
"connection manager will remain active"
)
except Exception as e:
logger.error(
f"Error during connection manager cleanup: {e}", exc_info=True
)
span.set_status(trace.Status(trace.StatusCode.ERROR))
span.record_exception(e)
finally:
# Always mark as uninitialized regardless of errors
self.initialized = False
@classmethod
async def create(
cls,
server_names: List[str],
connection_persistence: bool = False,
) -> "MCPAggregator":
"""
Factory method to create and initialize an MCPAggregator.
Use this instead of constructor since we need async initialization.
If connection_persistence is True, the aggregator will maintain a
persistent connection to the servers for as long as this aggregator is around.
By default we do not maintain a persistent connection.
"""
logger.info(f"Creating MCPAggregator with servers: {server_names}")
instance = cls(
server_names=server_names,
connection_persistence=connection_persistence,
)
tracer = get_tracer(instance.context)
with tracer.start_as_current_span(f"{cls.__name__}.create") as span:
span.set_attribute("server_names", server_names)
span.set_attribute("connection_persistence", connection_persistence)
try:
await instance.__aenter__()
logger.debug("Loading servers...")
await instance.load_servers()
logger.debug("MCPAggregator created and initialized.")
return instance
except Exception as e:
logger.error(f"Error creating MCPAggregator: {e}")
span.set_status(trace.Status(trace.StatusCode.ERROR))
span.record_exception(e)
try:
await instance.__aexit__(None, None, None)
except Exception as cleanup_error:
logger.warning(
f"Error during MCPAggregator cleanup: {cleanup_error}"
)
async def load_server(self, server_name: str):
"""
Load tools and prompts from a single server and update the index of namespaced tool/prompt names for that server.
"""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(
f"{self.__class__.__name__}.load_server"
) as span:
span.set_attribute("server_name", server_name)
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
if server_name not in self.server_names:
raise ValueError(f"Server '{server_name}' not found in server list")
_, tools, prompts, resources = await self._fetch_capabilities(server_name)
# Process tools
async with self._tool_map_lock:
self._server_to_tool_map[server_name] = []
for tool in tools:
namespaced_tool_name = f"{server_name}{SEP}{tool.name}"
namespaced_tool = NamespacedTool(
tool=tool,
server_name=server_name,
namespaced_tool_name=namespaced_tool_name,
)
self._namespaced_tool_map[namespaced_tool_name] = namespaced_tool
self._server_to_tool_map[server_name].append(namespaced_tool)
# Process prompts
async with self._prompt_map_lock:
self._server_to_prompt_map[server_name] = []
for prompt in prompts:
namespaced_prompt_name = f"{server_name}{SEP}{prompt.name}"
namespaced_prompt = NamespacedPrompt(
prompt=prompt,
server_name=server_name,
namespaced_prompt_name=namespaced_prompt_name,
)
self._namespaced_prompt_map[namespaced_prompt_name] = (
namespaced_prompt
)
self._server_to_prompt_map[server_name].append(namespaced_prompt)
# Process resources
async with self._resource_map_lock:
self._server_to_resource_map[server_name] = []
for resource in resources:
namespaced_resource_name = f"{server_name}{SEP}{resource.name}"
namespaced_resource = NamespacedResource(
resource=resource,
server_name=server_name,
namespaced_resource_name=namespaced_resource_name,
)
self._namespaced_resource_map[namespaced_resource_name] = (
namespaced_resource
)
self._server_to_resource_map[server_name].append(
namespaced_resource
)
event_metadata = {
"server_name": server_name,
"agent_name": self.agent_name,
"tool_count": len(tools),
"prompt_count": len(prompts),
"resource_count": len(resources),
}
logger.debug(
f"MCP Aggregator initialized for server '{server_name}'",
data={"progress_action": ProgressAction.INITIALIZED, **event_metadata},
)
if self.context.tracing_enabled:
span.add_event(
"load_server_complete",
event_metadata,
)
for tool in tools:
span.set_attribute(
f"tool.{tool.name}", tool.description or "No description"
)
for prompt in prompts:
span.set_attribute(
f"prompt.{prompt.name}", prompt.description or "No description"
)
for resource in resources:
span.set_attribute(
f"resource.{resource.name}",
resource.description or "No description",
)
return tools, prompts, resources
async def load_servers(self, force: bool = False):
"""
Discover tools and prompts from each server in parallel and build an index of namespaced tool/prompt names.
"""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(
f"{self.__class__.__name__}.load_servers"
) as span:
span.set_attribute("server_names", self.server_names)
span.set_attribute("force", force)
span.set_attribute("connection_persistence", self.connection_persistence)
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
span.set_attribute("initialized", self.initialized)
if self.initialized and not force:
logger.debug("MCPAggregator already initialized. Skipping reload.")
return
async with self._tool_map_lock:
self._namespaced_tool_map.clear()
self._server_to_tool_map.clear()
async with self._prompt_map_lock:
self._namespaced_prompt_map.clear()
self._server_to_prompt_map.clear()
async with self._resource_map_lock:
self._namespaced_resource_map.clear()
self._server_to_resource_map.clear()
# TODO: saqadri (FA1) - Verify that this can be removed
# if self.connection_persistence:
# # Start all the servers
# await asyncio.gather(
# *(self._start_server(server_name) for server_name in self.server_names),
# return_exceptions=True,
# )
# Load tools, prompts and resources from all servers concurrently
results = await asyncio.gather(
*(self.load_server(server_name) for server_name in self.server_names),
return_exceptions=True,
)
for server_name, result in zip(self.server_names, results):
if isinstance(result, BaseException):
logger.error(
f"Error loading server data: {result}. Attempting to continue"
)
span.record_exception(result, {"server_name": server_name})
continue
else:
span.add_event(
"server_load_success",
{
"server_name": server_name,
},
)
self.initialized = True
async def get_server(self, server_name: str) -> Optional[ClientSession]:
"""Get a server connection if available."""
if self.connection_persistence:
try:
server_conn = await self._persistent_connection_manager.get_server(
server_name, client_session_factory=MCPAgentClientSession
)
return server_conn.session
except Exception as e:
logger.warning(
f"Error getting server connection for '{server_name}': {e}"
)
return None
else:
logger.debug(
f"Creating temporary connection to server: {server_name}",
data={
"progress_action": ProgressAction.STARTING,
"server_name": server_name,
"agent_name": self.agent_name,
},
)
async with gen_client(
server_name, server_registry=self.context.server_registry
) as client:
return client
async def get_capabilities(self, server_name: str):
"""Get server capabilities if available."""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(
f"{self.__class__.__name__}.get_capabilitites"
) as span:
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
span.set_attribute("server_names", self.server_names)
span.set_attribute("connection_persistence", self.connection_persistence)
span.set_attribute("server_name", server_name)
def _annotate_span_for_capabilities(capabilities: ServerCapabilities):
if not self.context.tracing_enabled:
return
for attr in [
"experimental",
"logging",
"prompts",
"resources",
"tools",
]:
value = getattr(capabilities, attr, None)
span.set_attribute(
f"{server_name}.capabilities.{attr}", value is not None
)
if self.connection_persistence:
try:
server_conn = await self._persistent_connection_manager.get_server(
server_name, client_session_factory=MCPAgentClientSession
)
# TODO: saqadri (FA1) - verify
# server_capabilities is a property, not a coroutine
res = server_conn.server_capabilities
_annotate_span_for_capabilities(res)
return res
except Exception as e:
logger.warning(
f"Error getting capabilities for server '{server_name}': {e}"
)
span.set_status(trace.Status(trace.StatusCode.ERROR))
span.record_exception(e)
return None
else:
logger.debug(
f"Creating temporary connection to server: {server_name}",
data={
"progress_action": ProgressAction.STARTING,
"server_name": server_name,
"agent_name": self.agent_name,
},
)
async with self.context.server_registry.start_server(
server_name, client_session_factory=MCPAgentClientSession
) as session:
try:
initialize_result = await session.initialize()
res = initialize_result.capabilities
_annotate_span_for_capabilities(res)
return res
except Exception as e:
logger.warning(
f"Error getting capabilities for server '{server_name}': {e}"
)
span.set_status(trace.Status(trace.StatusCode.ERROR))
span.record_exception(e)
return None
async def refresh(self, server_name: str | None = None):
"""
Refresh the tools and prompts from the specified server or all servers.
"""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(f"{self.__class__.__name__}.refresh") as span:
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
if server_name:
span.set_attribute("server_name", server_name)
await self.load_server(server_name)
else:
await self.load_servers(force=True)
async def list_servers(self) -> List[str]:
"""Return the list of server names aggregated by this agent."""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(
f"{self.__class__.__name__}.list_servers"
) as span:
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
span.set_attribute("initialized", self.initialized)
if not self.initialized:
await self.load_servers()
span.set_attribute("server_names", self.server_names)
return self.server_names
async def list_tools(self, server_name: str | None = None) -> ListToolsResult:
"""
:return: Tools from all servers aggregated, and renamed to be dot-namespaced by server name.
"""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(
f"{self.__class__.__name__}.list_tools"
) as span:
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
span.set_attribute("initialized", self.initialized)
if not self.initialized:
await self.load_servers()
if server_name:
span.set_attribute("server_name", server_name)
result = ListToolsResult(
tools=[
namespaced_tool.tool.model_copy(
update={"name": namespaced_tool.namespaced_tool_name}
)
for namespaced_tool in self._server_to_tool_map.get(
server_name, []
)
]
)
else:
async with self._tool_map_lock:
result = ListToolsResult(
tools=[
namespaced_tool.tool.model_copy(
update={"name": namespaced_tool_name}
)
for namespaced_tool_name, namespaced_tool in self._namespaced_tool_map.items()
]
)
if self.context.tracing_enabled:
span.set_attribute("tool_count", len(result.tools))
for tool in result.tools:
span.set_attribute(
f"tool.{tool.name}", tool.description or "No description"
)
return result
async def list_resources(self, server_name: str | None = None):
"""
:return: Resources from all servers aggregated, and renamed to be dot-namespaced by server name.
"""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(
f"{self.__class__.__name__}.list_resources"
) as span:
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
span.set_attribute("initialized", self.initialized)
if not self.initialized:
await self.load_servers()
if server_name:
span.set_attribute("server_name", server_name)
result = ListResourcesResult(
resources=[
namespaced_resource.resource.model_copy(
update={
"name": namespaced_resource.namespaced_resource_name
}
)
for namespaced_resource in self._server_to_resource_map.get(
server_name, []
)
]
)
else:
async with self._resource_map_lock:
result = ListResourcesResult(
resources=[
namespaced_resource.resource.model_copy(
update={"name": namespaced_resource_name}
)
for namespaced_resource_name, namespaced_resource in self._namespaced_resource_map.items()
]
)
if self.context.tracing_enabled:
span.set_attribute("resource_count", len(result.resources))
for resource in result.resources:
span.set_attribute(
f"resource.{resource.name}",
resource.description or "No description",
)
return result
async def read_resource(
self, uri: str, server_name: str | None = None
) -> ReadResourceResult:
"""
Read a resource from a server by its URI.
Args:
uri: The URI of the resource to read.
server_name: Optionally restrict search to a specific server.
Returns:
Resource object, or None if not found
"""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(
f"{self.__class__.__name__}.read_resource"
) as span:
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
span.set_attribute("initialized", self.initialized)
if not self.initialized:
await self.load_servers()
span.set_attribute("uri", uri)
# If server_name is provided, use that server
if server_name:
span.set_attribute("server_name", server_name)
else:
# Use the URI to find the server name
server_name, _ = await self._parse_capability_name(uri, "resource")
span.set_attribute("parsed_server_name", server_name)
if server_name is None:
logger.error(f"Resource with uri '{uri}' not found in any server")
span.set_status(trace.Status(trace.StatusCode.ERROR))
span.record_exception(
ValueError(f"Resource with uri '{uri}' not found in any server")
)
return ReadResourceResult(contents=[])
async def try_read_resource(client: ClientSession):
try:
res = await client.read_resource(uri=uri)
return res
except Exception as e:
logger.error(
f"Error reading resource with uri '{uri}'"
+ (f" from server '{server_name}'" if server_name else "")
+ f": {e}"
)
span.set_status(trace.Status(trace.StatusCode.ERROR))
span.record_exception(e)
return ReadResourceResult(contents=[])
if self.connection_persistence:
server_conn = await self._persistent_connection_manager.get_server(
server_name, client_session_factory=MCPAgentClientSession
)
res = await try_read_resource(server_conn.session)
# TODO: jerron - annotate span for result
return res
else:
logger.debug(
f"Creating temporary connection to server: {server_name}",
data={
"progress_action": ProgressAction.STARTING,
"server_name": server_name,
"agent_name": self.agent_name,
},
)
span.add_event(
"temporary_connection_created",
{
"server_name": server_name,
GEN_AI_AGENT_NAME: self.agent_name,
},
)
async with gen_client(
server_name, server_registry=self.context.server_registry
) as client:
result = await try_read_resource(client)
logger.debug(
f"Closing temporary connection to server: {server_name}",
data={
"progress_action": ProgressAction.SHUTDOWN,
"server_name": server_name,
"agent_name": self.agent_name,
},
)
span.add_event(
"temporary_connection_closed",
{
"server_name": server_name,
GEN_AI_AGENT_NAME: self.agent_name,
},
)
# TODO: jerron - annotate span for result
return result
async def call_tool(
self, name: str, arguments: dict | None = None, server_name: str | None = None
) -> CallToolResult:
"""
Call a namespaced tool, e.g., 'server_name.tool_name'.
"""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(
f"{self.__class__.__name__}.call_tool"
) as span:
if self.context.tracing_enabled:
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
span.set_attribute(GEN_AI_TOOL_NAME, name)
if arguments is not None:
record_attributes(span, arguments, "arguments")
if not self.initialized:
await self.load_servers()
server_name: str = None
local_tool_name: str = None
if server_name:
span.set_attribute("server_name", server_name)
local_tool_name = name
else:
server_name, local_tool_name = await self._parse_capability_name(
name, "tool"
)
span.set_attribute("parsed_server_name", server_name)
span.set_attribute("parsed_tool_name", local_tool_name)
if server_name is None or local_tool_name is None:
logger.error(f"Error: Tool '{name}' not found")
span.set_status(trace.Status(trace.StatusCode.ERROR))
span.record_exception(ValueError(f"Tool '{name}' not found"))
return CallToolResult(
isError=True,
content=[TextContent(type="text", text=f"Tool '{name}' not found")],
)
logger.info(
"Requesting tool call",
data={
"progress_action": ProgressAction.CALLING_TOOL,
"tool_name": local_tool_name,
"server_name": server_name,
"agent_name": self.agent_name,
},
)
span.add_event(
"request_tool_call",
{
GEN_AI_AGENT_NAME: self.agent_name,
GEN_AI_TOOL_NAME: local_tool_name,
"server_name": server_name,
},
)
def _annotate_span_for_result(result: CallToolResult):
if not self.context.tracing_enabled:
return
span.set_attribute("result.isError", result.isError)
if result.isError:
span.set_status(trace.Status(trace.StatusCode.ERROR))
error_message = (
result.content[0].text
if len(result.content) > 0 and result.content[0].type == "text"
else "Error calling tool"
)
span.record_exception(Exception(error_message))
else:
for idx, content in enumerate(result.content):
span.set_attribute(f"result.content.{idx}.type", content.type)
if content.type == "text":
span.set_attribute(
f"result.content.{idx}.text", result.content[idx].text
)
async def try_call_tool(client: ClientSession):
try:
res = await client.call_tool(
name=local_tool_name, arguments=arguments
)
_annotate_span_for_result(res)
return res
except Exception as e:
span.set_status(trace.Status(trace.StatusCode.ERROR))
span.record_exception(e)
return CallToolResult(
isError=True,
content=[
TextContent(
type="text",
text=f"Failed to call tool '{local_tool_name}' on server '{server_name}': {str(e)}",
)
],
)
if self.connection_persistence:
server_connection = (
await self._persistent_connection_manager.get_server(
server_name, client_session_factory=MCPAgentClientSession
)
)
res = await try_call_tool(server_connection.session)
_annotate_span_for_result(res)
return res
else:
logger.debug(
f"Creating temporary connection to server: {server_name}",
data={
"progress_action": ProgressAction.STARTING,
"server_name": server_name,
"agent_name": self.agent_name,
},
)
span.add_event(
"temporary_connection_created",
{"server_name": server_name, GEN_AI_AGENT_NAME: self.agent_name},
)
async with gen_client(
server_name, server_registry=self.context.server_registry
) as client:
result = await try_call_tool(client)
logger.debug(
f"Closing temporary connection to server: {server_name}",
data={
"progress_action": ProgressAction.SHUTDOWN,
"server_name": server_name,
"agent_name": self.agent_name,
},
)
span.add_event(
"temporary_connection_closed",
{
"server_name": server_name,
GEN_AI_AGENT_NAME: self.agent_name,
},
)
_annotate_span_for_result(result)
return result
async def list_prompts(self, server_name: str | None = None) -> ListPromptsResult:
"""
:return: Prompts from all servers aggregated, and renamed to be dot-namespaced by server name.
"""
tracer = get_tracer(self.context)
with tracer.start_as_current_span(
f"{self.__class__.__name__}.list_prompts"
) as span:
span.set_attribute(GEN_AI_AGENT_NAME, self.agent_name)
span.set_attribute("initialized", self.initialized)
if not self.initialized:
await self.load_servers()
if server_name:
span.set_attribute("server_name", server_name)
res = ListPromptsResult(
prompts=[
namespaced_prompt.prompt.model_copy(
update={"name": namespaced_prompt.namespaced_prompt_name}
)
for namespaced_prompt in self._server_to_prompt_map.get(
server_name, []
)
]
)
else:
async with self._prompt_map_lock:
res = ListPromptsResult(
prompts=[
namespaced_prompt.prompt.model_copy(
update={"name": namespaced_prompt_name}
)
for namespaced_prompt_name, namespaced_prompt in self._namespaced_prompt_map.items()
]
)
if self.context.tracing_enabled:
span.set_attribute("prompts", [prompt.name for prompt in res.prompts])
for prompt in res.prompts:
if prompt.description:
span.set_attribute(
f"prompt.{prompt.name}.description", prompt.description
)
if prompt.arguments:
for arg in prompt.arguments:
for attr in [
"description",
"required",
]:
value = getattr(arg, attr, None)
if value is not None:
span.set_attribute(
f"prompt.{prompt.name}.arguments.{arg.name}.{attr}",
value,
)