flock-core 0.4.2__py3-none-any.whl → 0.4.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of flock-core might be problematic. Click here for more details.

Files changed (38) hide show
  1. flock/core/__init__.py +11 -0
  2. flock/core/flock.py +144 -42
  3. flock/core/flock_agent.py +117 -4
  4. flock/core/flock_evaluator.py +1 -1
  5. flock/core/flock_factory.py +290 -2
  6. flock/core/flock_module.py +101 -0
  7. flock/core/flock_registry.py +39 -2
  8. flock/core/flock_server_manager.py +136 -0
  9. flock/core/logging/telemetry.py +1 -1
  10. flock/core/mcp/__init__.py +1 -0
  11. flock/core/mcp/flock_mcp_server.py +614 -0
  12. flock/core/mcp/flock_mcp_tool_base.py +201 -0
  13. flock/core/mcp/mcp_client.py +658 -0
  14. flock/core/mcp/mcp_client_manager.py +201 -0
  15. flock/core/mcp/mcp_config.py +237 -0
  16. flock/core/mcp/types/__init__.py +1 -0
  17. flock/core/mcp/types/callbacks.py +86 -0
  18. flock/core/mcp/types/factories.py +111 -0
  19. flock/core/mcp/types/handlers.py +240 -0
  20. flock/core/mcp/types/types.py +157 -0
  21. flock/core/mcp/util/__init__.py +0 -0
  22. flock/core/mcp/util/helpers.py +23 -0
  23. flock/core/mixin/dspy_integration.py +45 -12
  24. flock/core/serialization/flock_serializer.py +52 -1
  25. flock/core/util/spliter.py +4 -0
  26. flock/evaluators/declarative/declarative_evaluator.py +4 -3
  27. flock/mcp/servers/sse/__init__.py +1 -0
  28. flock/mcp/servers/sse/flock_sse_server.py +139 -0
  29. flock/mcp/servers/stdio/__init__.py +1 -0
  30. flock/mcp/servers/stdio/flock_stdio_server.py +138 -0
  31. flock/mcp/servers/websockets/__init__.py +1 -0
  32. flock/mcp/servers/websockets/flock_websocket_server.py +119 -0
  33. flock/modules/performance/metrics_module.py +159 -1
  34. {flock_core-0.4.2.dist-info → flock_core-0.4.5.dist-info}/METADATA +278 -64
  35. {flock_core-0.4.2.dist-info → flock_core-0.4.5.dist-info}/RECORD +38 -18
  36. {flock_core-0.4.2.dist-info → flock_core-0.4.5.dist-info}/WHEEL +0 -0
  37. {flock_core-0.4.2.dist-info → flock_core-0.4.5.dist-info}/entry_points.txt +0 -0
  38. {flock_core-0.4.2.dist-info → flock_core-0.4.5.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,614 @@
1
+ """FlockMCPServer is the core, declarative base class for all types of MCP-Servers in the Flock framework."""
2
+
3
+ import asyncio
4
+ import importlib
5
+ import inspect
6
+ import os
7
+ from abc import ABC, abstractmethod
8
+ from typing import Any, Literal, TypeVar
9
+
10
+ from dspy import Tool as DSPyTool
11
+ from opentelemetry import trace
12
+ from pydantic import (
13
+ BaseModel,
14
+ ConfigDict,
15
+ Field,
16
+ )
17
+
18
+ from flock.core.flock_module import FlockModule
19
+ from flock.core.logging.logging import get_logger
20
+ from flock.core.mcp.flock_mcp_tool_base import FlockMCPToolBase
21
+ from flock.core.mcp.mcp_client_manager import FlockMCPClientManagerBase
22
+ from flock.core.mcp.mcp_config import FlockMCPConfigurationBase
23
+ from flock.core.serialization.serializable import Serializable
24
+ from flock.core.serialization.serialization_utils import (
25
+ deserialize_component,
26
+ serialize_item,
27
+ )
28
+
29
+ logger = get_logger("core.mcp.server_base")
30
+ tracer = trace.get_tracer(__name__)
31
+ T = TypeVar("T", bound="FlockMCPServerBase")
32
+
33
+ LoggingLevel = Literal[
34
+ "debug",
35
+ "info",
36
+ "notice",
37
+ "warning",
38
+ "error",
39
+ "critical",
40
+ "alert",
41
+ "emergency",
42
+ ]
43
+
44
+
45
+ class FlockMCPServerBase(BaseModel, Serializable, ABC):
46
+ """Base class for all Flock MCP Server Types.
47
+
48
+ Servers serve as an abstraction-layer between the underlying MCPClientSession
49
+ which is the actual connection between Flock and a (remote) MCP-Server.
50
+
51
+ Servers hook into the lifecycle of their assigned agents and take care
52
+ of establishing sessions, getting and converting tools and other functions
53
+ without agents having to worry about the details.
54
+
55
+ Tools (if provided) will be injected into the list of tools of any attached
56
+ agent automatically.
57
+
58
+ Servers provide lifecycle-hooks (`initialize`, `get_tools`, `get_prompts`, `list_resources`, `get_resource_contents`, `set_roots`, etc)
59
+ which allow modules to hook into them. This can be used to modify data or
60
+ pass headers from authentication-flows to a server.
61
+
62
+ Each Server should define its configuration requirements either by:
63
+ 1. Creating a subclass of FlockMCPServerConfig
64
+ 2. Using FlockMCPServerConfig.with_fields() to create a config class.
65
+ """
66
+
67
+ config: FlockMCPConfigurationBase = Field(
68
+ ..., description="Config for clients connecting to the server."
69
+ )
70
+
71
+ initialized: bool = Field(
72
+ default=False,
73
+ exclude=True,
74
+ description="Whether or not this Server has already initialized.",
75
+ )
76
+
77
+ modules: dict[str, FlockModule] = Field(
78
+ default={},
79
+ description="Dictionary of FlockModules attached to this Server.",
80
+ )
81
+
82
+ # --- Underlying ConnectionManager ---
83
+ # (Manages a pool of ClientConnections and does the actual talking to the MCP Server)
84
+ # (Excluded from Serialization)
85
+ client_manager: FlockMCPClientManagerBase | None = Field(
86
+ default=None,
87
+ exclude=True,
88
+ description="Underlying Connection Manager. Handles the actual underlying connections to the server.",
89
+ )
90
+
91
+ condition: asyncio.Condition = Field(
92
+ default_factory=asyncio.Condition,
93
+ exclude=True,
94
+ description="Condition for asynchronous operations.",
95
+ )
96
+
97
+ model_config = ConfigDict(
98
+ arbitrary_types_allowed=True,
99
+ )
100
+
101
+ def add_module(self, module: FlockModule) -> None:
102
+ """Add a module to this server."""
103
+ if not module.name:
104
+ logger.error("Module must have a name to be added.")
105
+ return
106
+ if self.modules and module.name in self.modules:
107
+ logger.warning(f"Overwriting existing module: {module.name}")
108
+
109
+ self.modules[module.name] = module
110
+ logger.debug(
111
+ f"Added module '{module.name}' to server {self.config.name}"
112
+ )
113
+ return
114
+
115
+ def remove_module(self, module_name: str) -> None:
116
+ """Remove a module from this server."""
117
+ if module_name in self.modules:
118
+ del self.modules[module_name]
119
+ logger.debug(
120
+ f"Removed module '{module_name}' from server '{self.config.name}'"
121
+ )
122
+ else:
123
+ logger.warning(
124
+ f"Module '{module_name}' not found on server '{self.config.name}'"
125
+ )
126
+ return
127
+
128
+ def get_module(self, module_name: str) -> FlockModule | None:
129
+ """Get a module by name."""
130
+ return self.modules.get(module_name)
131
+
132
+ def get_enabled_modules(self) -> list[FlockModule]:
133
+ """Get a list of currently enabled modules attached to this server."""
134
+ return [m for m in self.modules.values() if m.config.enabled]
135
+
136
+ @abstractmethod
137
+ async def initialize(self) -> FlockMCPClientManagerBase:
138
+ """Called when initializing the server."""
139
+ pass
140
+
141
+ async def call_tool(
142
+ self, agent_id: str, run_id: str, name: str, arguments: dict[str, Any]
143
+ ) -> Any:
144
+ """Call a tool via the MCP Protocol on the client's server."""
145
+ with tracer.start_as_current_span("server.call_tool") as span:
146
+ span.set_attribute("agent_id", agent_id)
147
+ span.set_attribute("run_id", run_id)
148
+ span.set_attribute("tool.name", name)
149
+ span.set_attribute("arguments", str(arguments))
150
+ if not self.initialized or not self.client_manager:
151
+ async with self.condition:
152
+ await self.pre_init()
153
+ self.client_manager = await self.initialize()
154
+ self.initialized = True
155
+ await self.post_init()
156
+ async with self.condition:
157
+ try:
158
+ additional_params: dict[str, Any] = {
159
+ "refresh_client": False,
160
+ "override_headers": False,
161
+ } # initialize the additional params as an empty dict.
162
+
163
+ await self.before_connect(
164
+ additional_params=additional_params
165
+ )
166
+ pre_call_args = {
167
+ "agent_id": agent_id,
168
+ "run_id": run_id,
169
+ "tool_name": name,
170
+ "arguments": arguments,
171
+ }
172
+ pre_call_args.update(additional_params)
173
+ await self.pre_mcp_call(pre_call_args)
174
+ result = await self.client_manager.call_tool(
175
+ agent_id=agent_id,
176
+ run_id=run_id,
177
+ name=name,
178
+ arguments=arguments,
179
+ additional_params=additional_params,
180
+ )
181
+ # re-set addtional-params, just to be sure.
182
+ await self.post_mcp_call(result=result)
183
+ return result
184
+ except Exception as mcp_error:
185
+ logger.error(
186
+ "Error during server.call_tool",
187
+ server=self.config.name,
188
+ error=str(mcp_error),
189
+ )
190
+ span.record_exception(mcp_error)
191
+ return None
192
+
193
+ async def get_tools(self, agent_id: str, run_id: str) -> list[DSPyTool]:
194
+ """Retrieves a list of available tools from this server."""
195
+ with tracer.start_as_current_span("server.get_tools") as span:
196
+ span.set_attribute("server.name", self.config.name)
197
+ span.set_attribute("agent_id", agent_id)
198
+ span.set_attribute("run_id", run_id)
199
+ if not self.initialized or not self.client_manager:
200
+ async with self.condition:
201
+ await self.pre_init()
202
+ self.client_manager = await self.initialize()
203
+ self.initialized = True
204
+ await self.post_init()
205
+
206
+ async with self.condition:
207
+ try:
208
+ await self.pre_mcp_call()
209
+ # TODO: inject additional params here.
210
+ additional_params: dict[str, Any] = {}
211
+ additional_params = await self.before_connect(
212
+ additional_params=additional_params
213
+ )
214
+ result: list[
215
+ FlockMCPToolBase
216
+ ] = await self.client_manager.get_tools(
217
+ agent_id=agent_id,
218
+ run_id=run_id,
219
+ additional_params=additional_params,
220
+ )
221
+ converted_tools = [
222
+ t.as_dspy_tool(server=self) for t in result
223
+ ]
224
+ await self.post_mcp_call(result=converted_tools)
225
+ return converted_tools
226
+ except Exception as e:
227
+ logger.error(
228
+ f"Unexpected Exception ocurred while trying to get tools from server '{self.config.name}': {e}"
229
+ )
230
+ await self.on_error(error=e)
231
+ span.record_exception(e)
232
+ return []
233
+ finally:
234
+ self.condition.notify()
235
+
236
+ async def before_connect(
237
+ self, additional_params: dict[str, Any]
238
+ ) -> dict[str, Any]:
239
+ """Run before_connect hooks on modules."""
240
+ logger.debug(
241
+ f"Running before_connect hooks for modules in server '{self.config.name}'."
242
+ )
243
+ with tracer.start_as_current_span("server.before_connect") as span:
244
+ span.set_attribute("server.name", self.config.name)
245
+ try:
246
+ if not additional_params:
247
+ additional_params = {}
248
+ for module in self.get_enabled_modules():
249
+ additional_params = await module.on_connect(
250
+ server=self, additional_params=additional_params
251
+ )
252
+ except Exception as module_error:
253
+ logger.error(
254
+ "Error during before_connect",
255
+ server=self.config.name,
256
+ error=str(module_error),
257
+ )
258
+ span.record_exception(module_error)
259
+
260
+ async def pre_init(self) -> None:
261
+ """Run pre-init hooks on modules."""
262
+ logger.debug(
263
+ f"Running pre-init hooks for modules in server '{self.config.name}'"
264
+ )
265
+ with tracer.start_as_current_span("server.pre_init") as span:
266
+ span.set_attribute("server.name", self.config.name)
267
+ try:
268
+ for module in self.get_enabled_modules():
269
+ await module.on_pre_server_init(self)
270
+ except Exception as module_error:
271
+ logger.error(
272
+ "Error during pre_init",
273
+ server=self.config.name,
274
+ error=str(module_error),
275
+ )
276
+ span.record_exception(module_error)
277
+
278
+ async def post_init(self) -> None:
279
+ """Run post-init hooks on modules."""
280
+ logger.debug(
281
+ f"Running post_init hooks for modules in server '{self.config.name}'"
282
+ )
283
+ with tracer.start_as_current_span("server.post_init") as span:
284
+ span.set_attribute("server.name", self.config.name)
285
+ try:
286
+ for module in self.get_enabled_modules():
287
+ await module.on_post_server_init(self)
288
+ except Exception as module_error:
289
+ logger.error(
290
+ "Error during post_init",
291
+ server=self.config.name,
292
+ error=str(module_error),
293
+ )
294
+ span.record_exception(module_error)
295
+
296
+ async def pre_terminate(self) -> None:
297
+ """Run pre-terminate hooks on modules."""
298
+ logger.debug(
299
+ f"Running post_init hooks for modules in server: '{self.config.name}'"
300
+ )
301
+ with tracer.start_as_current_span("server.pre_terminate") as span:
302
+ span.set_attribute("server.name", self.config.name)
303
+ try:
304
+ for module in self.get_enabled_modules():
305
+ await module.on_pre_server_terminate(self)
306
+ except Exception as module_error:
307
+ logger.error(
308
+ "Error during pre_terminate",
309
+ server=self.config.name,
310
+ error=str(module_error),
311
+ )
312
+ span.record_exception(module_error)
313
+
314
+ async def post_terminate(self) -> None:
315
+ """Run post-terminate hooks on modules."""
316
+ logger.debug(
317
+ f"Running post_terminat hooks for modules in server: '{self.config.name}'"
318
+ )
319
+ with tracer.start_as_current_span("server.post_terminate") as span:
320
+ span.set_attribute("server.name", self.config.name)
321
+ try:
322
+ for module in self.get_enabled_modules():
323
+ await module.on_post_server_terminate(server=self)
324
+ except Exception as module_error:
325
+ logger.error(
326
+ "Error during post_terminate",
327
+ server=self.config.name,
328
+ error=str(module_error),
329
+ )
330
+ span.record_exception(module_error)
331
+
332
+ async def on_error(self, error: Exception) -> None:
333
+ """Run on_error hooks on modules."""
334
+ logger.debug(
335
+ f"Running on_error hooks for modules in server '{self.config.name}'"
336
+ )
337
+ with tracer.start_as_current_span("server.on_error") as span:
338
+ span.set_attribute("server.name", self.config.name)
339
+ try:
340
+ for module in self.get_enabled_modules():
341
+ await module.on_server_error(server=self, error=error)
342
+ except Exception as module_error:
343
+ logger.error(
344
+ "Error during on_error",
345
+ server=self.config.name,
346
+ error=str(module_error),
347
+ )
348
+ span.record_exception(module_error)
349
+
350
+ async def pre_mcp_call(self, arguments: Any | None = None) -> None:
351
+ """Run pre_mcp_call-hooks on modules."""
352
+ logger.debug(
353
+ f"Running pre_mcp_call hooks for modules in server '{self.config.name}'"
354
+ )
355
+ with tracer.start_as_current_span("server.pre_mcp_call") as span:
356
+ span.set_attribute("server.name", self.config.name)
357
+ try:
358
+ for module in self.get_enabled_modules():
359
+ await module.on_pre_mcp_call(
360
+ server=self, arguments=arguments
361
+ )
362
+ except Exception as module_error:
363
+ logger.error(
364
+ f"Error during pre_mcp_call: {module_error}",
365
+ server=self.config.name,
366
+ error=str(module_error),
367
+ )
368
+ span.record_exception(module_error)
369
+
370
+ async def post_mcp_call(self, result: Any) -> None:
371
+ """Run Post MCP_call hooks on modules."""
372
+ logger.debug(
373
+ f"Running post_mcp_call hooks for modules in server '{self.config.name}'"
374
+ )
375
+ with tracer.start_as_current_span("server.post_mcp_call") as span:
376
+ span.set_attribute("server.name", self.config.name)
377
+ try:
378
+ for module in self.get_enabled_modules():
379
+ await module.on_post_mcp_call(server=self, result=result)
380
+ except Exception as module_error:
381
+ logger.error(
382
+ "Error during post_mcp_call",
383
+ server=self.config.name,
384
+ error=str(module_error),
385
+ )
386
+ span.record_exception(module_error)
387
+
388
+ # --- Async Methods ---
389
+ async def __aenter__(self) -> "FlockMCPServerBase":
390
+ """Enter the asynchronous context for the server."""
391
+ # Spin up the client-manager
392
+ with tracer.start_as_current_span("server.__aenter__") as span:
393
+ span.set_attribute("server.name", self.config.name)
394
+ logger.info(f"server.__aenter__", server=self.config.name)
395
+ try:
396
+ await self.pre_init()
397
+ self.client_manager = await self.initialize()
398
+ await self.post_init()
399
+ self.initialized = True
400
+ except Exception as server_error:
401
+ logger.error(
402
+ f"Error during __aenter__ for server '{self.config.name}'",
403
+ server=self.config.name,
404
+ error=server_error,
405
+ )
406
+ span.record_exception(server_error)
407
+
408
+ async def __aexit__(self, exc_type, exc, tb) -> None:
409
+ """Exit the asynchronous context for the server."""
410
+ # tell the underlying client-manager to terminate connections
411
+ # and unwind the clients.
412
+ with tracer.start_as_current_span("server.__aexit__") as span:
413
+ span.set_attribute("server.name", self.config.name)
414
+ try:
415
+ await self.pre_terminate()
416
+ if self.initialized and self.client_manager:
417
+ # means we ran through the initialize()-method
418
+ # and the client manager is present
419
+ await self.client_manager.close_all()
420
+ self.client_manager = None
421
+ self.initialized = False
422
+ await self.post_terminate()
423
+ return
424
+ except Exception as server_error:
425
+ logger.error(
426
+ f"Error during __aexit__ for server '{self.config.name}'",
427
+ server=self.config.name,
428
+ error=server_error,
429
+ )
430
+ await self.on_error(error=server_error)
431
+ span.record_exception(server_error)
432
+
433
+ # --- Serialization Implementation ---
434
+ def to_dict(self, path_type: str = "relative") -> dict[str, Any]:
435
+ """Convert instance to dictionary representation suitable for serialization."""
436
+ from flock.core.flock_registry import get_registry
437
+
438
+ FlockRegistry = get_registry()
439
+
440
+ exclude = ["modules"]
441
+
442
+ logger.debug(f"Serializing server '{self.config.name}' to dict.")
443
+ # Use Pydantic's dump, exclued manually handled fields.
444
+ data = self.model_dump(
445
+ exclude=exclude,
446
+ mode="json", # Use json mode for better handling of standard types by Pydantic
447
+ exclude_none=True, # Exclude None values for cleaner output
448
+ )
449
+
450
+ builtin_by_transport = {}
451
+
452
+ try:
453
+ from flock.mcp.servers.sse.flock_sse_server import FlockSSEServer
454
+ from flock.mcp.servers.stdio.flock_stdio_server import (
455
+ FlockMCPStdioServer,
456
+ )
457
+ from flock.mcp.servers.websockets.flock_websocket_server import (
458
+ FlockWSServer,
459
+ )
460
+
461
+ builtin_by_transport = {
462
+ "stdio": FlockMCPStdioServer,
463
+ "sse": FlockSSEServer,
464
+ "websockets": FlockWSServer,
465
+ }
466
+ except ImportError:
467
+ builtin_by_transport = {}
468
+
469
+ # --- Only emit full impl for non-builtins ---
470
+ transport = getattr(
471
+ self.config.connection_config, "transport_type", None
472
+ )
473
+ builtin_cls = builtin_by_transport.get(transport)
474
+
475
+ if type(self) is not builtin_cls:
476
+ file_path = inspect.getsourcefile(type(self))
477
+ if path_type == "relative":
478
+ file_path = os.path.relpath(file_path)
479
+ data["implementation"] = {
480
+ "class_name": type(self).__name__,
481
+ "module_path": type(self).__module__,
482
+ "file_path": file_path,
483
+ }
484
+
485
+ logger.debug(
486
+ f"Base server data for '{self.config.name}': {list(data.keys())}"
487
+ )
488
+ serialized_modules = {}
489
+
490
+ def add_serialized_component(component: Any, field_name: str):
491
+ if component:
492
+ comp_type = type(component)
493
+ type_name = FlockRegistry.get_component_type_name(
494
+ comp_type
495
+ ) # Get registered name
496
+
497
+ if type_name:
498
+ try:
499
+ serialized_component_data = serialize_item(component)
500
+
501
+ if not isinstance(serialized_component_data, dict):
502
+ logger.error(
503
+ f"Serialization of component {type_name} for field '{field_name}' did not result in a dictionary. Got: {type(serialized_component_data)}"
504
+ )
505
+ serialized_modules[field_name] = {
506
+ "type": type_name,
507
+ "name": getattr(component, "name", "unknown"),
508
+ "error": "serialization_failed_non_dict",
509
+ }
510
+ else:
511
+ serialized_component_data["type"] = type_name
512
+ serialized_modules[field_name] = (
513
+ serialized_component_data
514
+ )
515
+ logger.debug(
516
+ f"Successfully serialized component for field '{field_name}' (type: {type_name})"
517
+ )
518
+ except Exception as e:
519
+ logger.error(
520
+ f"Failed to serialize component {type_name} for field '{field_name}': {e}",
521
+ exc_info=True,
522
+ )
523
+
524
+ else:
525
+ logger.warning(
526
+ f"Cannot serialize unregistered component {comp_type.__name__} for field '{field_name}'"
527
+ )
528
+
529
+ serialized_modules = {}
530
+ for module in self.modules.values():
531
+ add_serialized_component(module, module.name)
532
+
533
+ if serialized_modules:
534
+ data["modules"] = serialized_modules
535
+ logger.debug(
536
+ f"Added {len(serialized_modules)} modules to server '{self.config.name}'"
537
+ )
538
+
539
+ def _clean(obj: Any) -> Any:
540
+ if isinstance(obj, dict):
541
+ return {
542
+ k: _clean(v)
543
+ for k, v in obj.items()
544
+ if v is not None
545
+ and not (isinstance(v, list | dict) and len(v) == 0)
546
+ }
547
+ if isinstance(obj, list):
548
+ return [
549
+ _clean(v)
550
+ for v in obj
551
+ if v is not None
552
+ and not (isinstance(v, dict | list) and len(v) == 0)
553
+ ]
554
+ return obj
555
+
556
+ data = _clean(data)
557
+ return data
558
+
559
+ @classmethod
560
+ def from_dict(cls: type[T], data: dict[str, Any]) -> T:
561
+ """Deserialize the server from a dictionary, including components."""
562
+ logger.debug(
563
+ f"Deserializing server from dict. Keys: {list(data.keys())}"
564
+ )
565
+
566
+ builtin_by_transport = {}
567
+
568
+ try:
569
+ from flock.mcp.servers.sse.flock_sse_server import FlockSSEServer
570
+ from flock.mcp.servers.stdio.flock_stdio_server import (
571
+ FlockMCPStdioServer,
572
+ )
573
+ from flock.mcp.servers.websockets.flock_websocket_server import (
574
+ FlockWSServer,
575
+ )
576
+
577
+ builtin_by_transport = {
578
+ "stdio": FlockMCPStdioServer,
579
+ "sse": FlockSSEServer,
580
+ "websockets": FlockWSServer,
581
+ }
582
+ except ImportError:
583
+ builtin_by_transport = {}
584
+
585
+ # find custom impl or built-in
586
+ impl = data.pop("implementation", None)
587
+ if impl:
588
+ mod = importlib.import_module(impl["module_path"])
589
+ real_cls = getattr(mod, impl["class_name"])
590
+ else:
591
+ # built-in: inspect transport_type in data["config"]
592
+ transport = data["config"]["connection_config"]["transport_type"]
593
+ real_cls = builtin_by_transport.get(transport, cls)
594
+
595
+ # now construct
596
+ server = real_cls(**{k: v for k, v in data.items() if k != "modules"})
597
+
598
+ # re-hydrate modules
599
+ for mname, mdata in data.get("modules", {}).items():
600
+ server.add_module(deserialize_component(mdata, FlockModule))
601
+
602
+ # --- Separate Data ---
603
+ component_configs = {}
604
+ server_data = {}
605
+ component_keys = ["modules"]
606
+
607
+ for key, value in data.items():
608
+ if key in component_keys and value is not None:
609
+ component_configs[key] = value
610
+ else:
611
+ server_data[key] = value
612
+
613
+ logger.info(f"Successfully deserialized server '{server.config.name}'")
614
+ return server