nvidia-nat 1.3.0a20250910__py3-none-any.whl → 1.4.0a20251112__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.
Files changed (213) hide show
  1. nat/agent/base.py +13 -8
  2. nat/agent/prompt_optimizer/prompt.py +68 -0
  3. nat/agent/prompt_optimizer/register.py +149 -0
  4. nat/agent/react_agent/agent.py +6 -5
  5. nat/agent/react_agent/register.py +49 -39
  6. nat/agent/reasoning_agent/reasoning_agent.py +17 -15
  7. nat/agent/register.py +2 -0
  8. nat/agent/responses_api_agent/__init__.py +14 -0
  9. nat/agent/responses_api_agent/register.py +126 -0
  10. nat/agent/rewoo_agent/agent.py +304 -117
  11. nat/agent/rewoo_agent/prompt.py +19 -22
  12. nat/agent/rewoo_agent/register.py +51 -38
  13. nat/agent/tool_calling_agent/agent.py +75 -17
  14. nat/agent/tool_calling_agent/register.py +46 -23
  15. nat/authentication/api_key/api_key_auth_provider.py +6 -11
  16. nat/authentication/api_key/api_key_auth_provider_config.py +8 -5
  17. nat/authentication/credential_validator/__init__.py +14 -0
  18. nat/authentication/credential_validator/bearer_token_validator.py +557 -0
  19. nat/authentication/http_basic_auth/http_basic_auth_provider.py +1 -1
  20. nat/authentication/interfaces.py +5 -2
  21. nat/authentication/oauth2/oauth2_auth_code_flow_provider.py +69 -36
  22. nat/authentication/oauth2/oauth2_auth_code_flow_provider_config.py +2 -1
  23. nat/authentication/oauth2/oauth2_resource_server_config.py +125 -0
  24. nat/builder/builder.py +55 -23
  25. nat/builder/component_utils.py +9 -5
  26. nat/builder/context.py +54 -15
  27. nat/builder/eval_builder.py +14 -9
  28. nat/builder/framework_enum.py +1 -0
  29. nat/builder/front_end.py +1 -1
  30. nat/builder/function.py +370 -0
  31. nat/builder/function_info.py +1 -1
  32. nat/builder/intermediate_step_manager.py +38 -2
  33. nat/builder/workflow.py +5 -0
  34. nat/builder/workflow_builder.py +306 -54
  35. nat/cli/cli_utils/config_override.py +1 -1
  36. nat/cli/commands/info/info.py +16 -6
  37. nat/cli/commands/mcp/__init__.py +14 -0
  38. nat/cli/commands/mcp/mcp.py +986 -0
  39. nat/cli/commands/optimize.py +90 -0
  40. nat/cli/commands/start.py +1 -1
  41. nat/cli/commands/workflow/templates/config.yml.j2 +14 -13
  42. nat/cli/commands/workflow/templates/register.py.j2 +2 -2
  43. nat/cli/commands/workflow/templates/workflow.py.j2 +35 -21
  44. nat/cli/commands/workflow/workflow_commands.py +60 -18
  45. nat/cli/entrypoint.py +15 -11
  46. nat/cli/main.py +3 -0
  47. nat/cli/register_workflow.py +38 -4
  48. nat/cli/type_registry.py +72 -1
  49. nat/control_flow/__init__.py +0 -0
  50. nat/control_flow/register.py +20 -0
  51. nat/control_flow/router_agent/__init__.py +0 -0
  52. nat/control_flow/router_agent/agent.py +329 -0
  53. nat/control_flow/router_agent/prompt.py +48 -0
  54. nat/control_flow/router_agent/register.py +91 -0
  55. nat/control_flow/sequential_executor.py +166 -0
  56. nat/data_models/agent.py +34 -0
  57. nat/data_models/api_server.py +199 -69
  58. nat/data_models/authentication.py +23 -9
  59. nat/data_models/common.py +47 -0
  60. nat/data_models/component.py +2 -0
  61. nat/data_models/component_ref.py +11 -0
  62. nat/data_models/config.py +41 -17
  63. nat/data_models/dataset_handler.py +4 -3
  64. nat/data_models/function.py +34 -0
  65. nat/data_models/function_dependencies.py +8 -0
  66. nat/data_models/intermediate_step.py +9 -1
  67. nat/data_models/llm.py +15 -1
  68. nat/data_models/openai_mcp.py +46 -0
  69. nat/data_models/optimizable.py +208 -0
  70. nat/data_models/optimizer.py +161 -0
  71. nat/data_models/span.py +41 -3
  72. nat/data_models/thinking_mixin.py +2 -2
  73. nat/embedder/azure_openai_embedder.py +2 -1
  74. nat/embedder/nim_embedder.py +3 -2
  75. nat/embedder/openai_embedder.py +3 -2
  76. nat/eval/config.py +1 -1
  77. nat/eval/dataset_handler/dataset_downloader.py +3 -2
  78. nat/eval/dataset_handler/dataset_filter.py +34 -2
  79. nat/eval/evaluate.py +10 -3
  80. nat/eval/evaluator/base_evaluator.py +1 -1
  81. nat/eval/rag_evaluator/evaluate.py +7 -4
  82. nat/eval/register.py +4 -0
  83. nat/eval/runtime_evaluator/__init__.py +14 -0
  84. nat/eval/runtime_evaluator/evaluate.py +123 -0
  85. nat/eval/runtime_evaluator/register.py +100 -0
  86. nat/eval/swe_bench_evaluator/evaluate.py +1 -1
  87. nat/eval/trajectory_evaluator/register.py +1 -1
  88. nat/eval/tunable_rag_evaluator/evaluate.py +1 -1
  89. nat/eval/usage_stats.py +2 -0
  90. nat/eval/utils/output_uploader.py +3 -2
  91. nat/eval/utils/weave_eval.py +17 -3
  92. nat/experimental/decorators/experimental_warning_decorator.py +27 -7
  93. nat/experimental/test_time_compute/functions/execute_score_select_function.py +1 -1
  94. nat/experimental/test_time_compute/functions/plan_select_execute_function.py +7 -3
  95. nat/experimental/test_time_compute/functions/ttc_tool_orchestration_function.py +1 -1
  96. nat/experimental/test_time_compute/functions/ttc_tool_wrapper_function.py +3 -3
  97. nat/experimental/test_time_compute/models/strategy_base.py +2 -2
  98. nat/experimental/test_time_compute/selection/llm_based_output_merging_selector.py +1 -1
  99. nat/front_ends/console/authentication_flow_handler.py +82 -30
  100. nat/front_ends/console/console_front_end_plugin.py +19 -7
  101. nat/front_ends/fastapi/auth_flow_handlers/http_flow_handler.py +1 -1
  102. nat/front_ends/fastapi/auth_flow_handlers/websocket_flow_handler.py +52 -17
  103. nat/front_ends/fastapi/dask_client_mixin.py +65 -0
  104. nat/front_ends/fastapi/fastapi_front_end_config.py +25 -3
  105. nat/front_ends/fastapi/fastapi_front_end_plugin.py +140 -3
  106. nat/front_ends/fastapi/fastapi_front_end_plugin_worker.py +445 -265
  107. nat/front_ends/fastapi/job_store.py +518 -99
  108. nat/front_ends/fastapi/main.py +11 -19
  109. nat/front_ends/fastapi/message_handler.py +69 -44
  110. nat/front_ends/fastapi/message_validator.py +8 -7
  111. nat/front_ends/fastapi/utils.py +57 -0
  112. nat/front_ends/mcp/introspection_token_verifier.py +73 -0
  113. nat/front_ends/mcp/mcp_front_end_config.py +71 -3
  114. nat/front_ends/mcp/mcp_front_end_plugin.py +85 -21
  115. nat/front_ends/mcp/mcp_front_end_plugin_worker.py +248 -29
  116. nat/front_ends/mcp/memory_profiler.py +320 -0
  117. nat/front_ends/mcp/tool_converter.py +78 -25
  118. nat/front_ends/simple_base/simple_front_end_plugin_base.py +3 -1
  119. nat/llm/aws_bedrock_llm.py +21 -8
  120. nat/llm/azure_openai_llm.py +14 -5
  121. nat/llm/litellm_llm.py +80 -0
  122. nat/llm/nim_llm.py +23 -9
  123. nat/llm/openai_llm.py +19 -7
  124. nat/llm/register.py +4 -0
  125. nat/llm/utils/thinking.py +1 -1
  126. nat/observability/exporter/base_exporter.py +1 -1
  127. nat/observability/exporter/processing_exporter.py +29 -55
  128. nat/observability/exporter/span_exporter.py +43 -15
  129. nat/observability/exporter_manager.py +2 -2
  130. nat/observability/mixin/redaction_config_mixin.py +5 -4
  131. nat/observability/mixin/tagging_config_mixin.py +26 -14
  132. nat/observability/mixin/type_introspection_mixin.py +420 -107
  133. nat/observability/processor/batching_processor.py +1 -1
  134. nat/observability/processor/processor.py +3 -0
  135. nat/observability/processor/redaction/__init__.py +24 -0
  136. nat/observability/processor/redaction/contextual_redaction_processor.py +125 -0
  137. nat/observability/processor/redaction/contextual_span_redaction_processor.py +66 -0
  138. nat/observability/processor/redaction/redaction_processor.py +177 -0
  139. nat/observability/processor/redaction/span_header_redaction_processor.py +92 -0
  140. nat/observability/processor/span_tagging_processor.py +21 -14
  141. nat/observability/register.py +16 -0
  142. nat/profiler/callbacks/langchain_callback_handler.py +32 -7
  143. nat/profiler/callbacks/llama_index_callback_handler.py +36 -2
  144. nat/profiler/callbacks/token_usage_base_model.py +2 -0
  145. nat/profiler/decorators/framework_wrapper.py +61 -9
  146. nat/profiler/decorators/function_tracking.py +35 -3
  147. nat/profiler/forecasting/models/linear_model.py +1 -1
  148. nat/profiler/forecasting/models/random_forest_regressor.py +1 -1
  149. nat/profiler/inference_optimization/bottleneck_analysis/nested_stack_analysis.py +1 -1
  150. nat/profiler/inference_optimization/experimental/prefix_span_analysis.py +1 -1
  151. nat/profiler/parameter_optimization/__init__.py +0 -0
  152. nat/profiler/parameter_optimization/optimizable_utils.py +93 -0
  153. nat/profiler/parameter_optimization/optimizer_runtime.py +67 -0
  154. nat/profiler/parameter_optimization/parameter_optimizer.py +189 -0
  155. nat/profiler/parameter_optimization/parameter_selection.py +107 -0
  156. nat/profiler/parameter_optimization/pareto_visualizer.py +460 -0
  157. nat/profiler/parameter_optimization/prompt_optimizer.py +384 -0
  158. nat/profiler/parameter_optimization/update_helpers.py +66 -0
  159. nat/profiler/utils.py +3 -1
  160. nat/registry_handlers/pypi/register_pypi.py +5 -3
  161. nat/registry_handlers/rest/register_rest.py +5 -3
  162. nat/retriever/milvus/retriever.py +1 -1
  163. nat/retriever/nemo_retriever/register.py +2 -1
  164. nat/runtime/loader.py +1 -1
  165. nat/runtime/runner.py +111 -6
  166. nat/runtime/session.py +49 -3
  167. nat/settings/global_settings.py +2 -2
  168. nat/tool/chat_completion.py +4 -1
  169. nat/tool/code_execution/code_sandbox.py +3 -6
  170. nat/tool/code_execution/local_sandbox/Dockerfile.sandbox +19 -32
  171. nat/tool/code_execution/local_sandbox/local_sandbox_server.py +6 -1
  172. nat/tool/code_execution/local_sandbox/sandbox.requirements.txt +2 -0
  173. nat/tool/code_execution/local_sandbox/start_local_sandbox.sh +10 -4
  174. nat/tool/datetime_tools.py +1 -1
  175. nat/tool/github_tools.py +450 -0
  176. nat/tool/memory_tools/add_memory_tool.py +3 -3
  177. nat/tool/memory_tools/delete_memory_tool.py +3 -4
  178. nat/tool/memory_tools/get_memory_tool.py +4 -4
  179. nat/tool/register.py +2 -7
  180. nat/tool/server_tools.py +15 -2
  181. nat/utils/__init__.py +76 -0
  182. nat/utils/callable_utils.py +70 -0
  183. nat/utils/data_models/schema_validator.py +1 -1
  184. nat/utils/decorators.py +210 -0
  185. nat/utils/exception_handlers/automatic_retries.py +278 -72
  186. nat/utils/io/yaml_tools.py +73 -3
  187. nat/utils/log_levels.py +25 -0
  188. nat/utils/responses_api.py +26 -0
  189. nat/utils/string_utils.py +16 -0
  190. nat/utils/type_converter.py +12 -3
  191. nat/utils/type_utils.py +6 -2
  192. nvidia_nat-1.4.0a20251112.dist-info/METADATA +197 -0
  193. {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/RECORD +199 -165
  194. {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/entry_points.txt +1 -0
  195. nat/cli/commands/info/list_mcp.py +0 -461
  196. nat/data_models/temperature_mixin.py +0 -43
  197. nat/data_models/top_p_mixin.py +0 -43
  198. nat/observability/processor/header_redaction_processor.py +0 -123
  199. nat/observability/processor/redaction_processor.py +0 -77
  200. nat/tool/code_execution/test_code_execution_sandbox.py +0 -414
  201. nat/tool/github_tools/create_github_commit.py +0 -133
  202. nat/tool/github_tools/create_github_issue.py +0 -87
  203. nat/tool/github_tools/create_github_pr.py +0 -106
  204. nat/tool/github_tools/get_github_file.py +0 -106
  205. nat/tool/github_tools/get_github_issue.py +0 -166
  206. nat/tool/github_tools/get_github_pr.py +0 -256
  207. nat/tool/github_tools/update_github_issue.py +0 -100
  208. nvidia_nat-1.3.0a20250910.dist-info/METADATA +0 -373
  209. /nat/{tool/github_tools → agent/prompt_optimizer}/__init__.py +0 -0
  210. {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/WHEEL +0 -0
  211. {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/licenses/LICENSE-3rd-party.txt +0 -0
  212. {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/licenses/LICENSE.md +0 -0
  213. {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/top_level.txt +0 -0
@@ -14,9 +14,9 @@
14
14
  # limitations under the License.
15
15
 
16
16
  import asyncio
17
+ import json
17
18
  import logging
18
19
  import os
19
- import time
20
20
  import typing
21
21
  from abc import ABC
22
22
  from abc import abstractmethod
@@ -25,19 +25,21 @@ from collections.abc import Callable
25
25
  from contextlib import asynccontextmanager
26
26
  from pathlib import Path
27
27
 
28
- from fastapi import BackgroundTasks
28
+ import httpx
29
+ from authlib.common.errors import AuthlibBaseError as OAuthError
29
30
  from fastapi import Body
30
31
  from fastapi import FastAPI
32
+ from fastapi import HTTPException
31
33
  from fastapi import Request
32
34
  from fastapi import Response
33
35
  from fastapi import UploadFile
34
- from fastapi.exceptions import HTTPException
35
36
  from fastapi.middleware.cors import CORSMiddleware
36
37
  from fastapi.responses import StreamingResponse
37
38
  from pydantic import BaseModel
38
39
  from pydantic import Field
39
40
  from starlette.websockets import WebSocket
40
41
 
42
+ from nat.builder.function import Function
41
43
  from nat.builder.workflow_builder import WorkflowBuilder
42
44
  from nat.data_models.api_server import ChatRequest
43
45
  from nat.data_models.api_server import ChatResponse
@@ -58,18 +60,30 @@ from nat.front_ends.fastapi.fastapi_front_end_config import EvaluateRequest
58
60
  from nat.front_ends.fastapi.fastapi_front_end_config import EvaluateResponse
59
61
  from nat.front_ends.fastapi.fastapi_front_end_config import EvaluateStatusResponse
60
62
  from nat.front_ends.fastapi.fastapi_front_end_config import FastApiFrontEndConfig
61
- from nat.front_ends.fastapi.job_store import JobInfo
62
- from nat.front_ends.fastapi.job_store import JobStore
63
63
  from nat.front_ends.fastapi.message_handler import WebSocketMessageHandler
64
64
  from nat.front_ends.fastapi.response_helpers import generate_single_response
65
65
  from nat.front_ends.fastapi.response_helpers import generate_streaming_response_as_str
66
66
  from nat.front_ends.fastapi.response_helpers import generate_streaming_response_full_as_str
67
67
  from nat.front_ends.fastapi.step_adaptor import StepAdaptor
68
+ from nat.front_ends.fastapi.utils import get_config_file_path
68
69
  from nat.object_store.models import ObjectStoreItem
70
+ from nat.runtime.loader import load_workflow
69
71
  from nat.runtime.session import SessionManager
70
72
 
71
73
  logger = logging.getLogger(__name__)
72
74
 
75
+ _DASK_AVAILABLE = False
76
+
77
+ try:
78
+ from nat.front_ends.fastapi.job_store import JobInfo
79
+ from nat.front_ends.fastapi.job_store import JobStatus
80
+ from nat.front_ends.fastapi.job_store import JobStore
81
+ _DASK_AVAILABLE = True
82
+ except ImportError:
83
+ JobInfo = None
84
+ JobStatus = None
85
+ JobStore = None
86
+
73
87
 
74
88
  class FastApiFrontEndPluginWorkerBase(ABC):
75
89
 
@@ -80,10 +94,29 @@ class FastApiFrontEndPluginWorkerBase(ABC):
80
94
  FastApiFrontEndConfig), ("Front end config is not FastApiFrontEndConfig")
81
95
 
82
96
  self._front_end_config = config.general.front_end
83
-
84
- self._cleanup_tasks: list[str] = []
85
- self._cleanup_tasks_lock = asyncio.Lock()
97
+ self._dask_available = False
98
+ self._job_store = None
86
99
  self._http_flow_handler: HTTPAuthenticationFlowHandler | None = HTTPAuthenticationFlowHandler()
100
+ self._scheduler_address = os.environ.get("NAT_DASK_SCHEDULER_ADDRESS")
101
+ self._db_url = os.environ.get("NAT_JOB_STORE_DB_URL")
102
+ self._config_file_path = get_config_file_path()
103
+
104
+ if self._scheduler_address is not None:
105
+ if not _DASK_AVAILABLE:
106
+ raise RuntimeError("Dask is not available, please install it to use the FastAPI front end with Dask.")
107
+
108
+ if self._db_url is None:
109
+ raise RuntimeError(
110
+ "NAT_JOB_STORE_DB_URL must be set when using Dask (configure a persistent JobStore database).")
111
+
112
+ try:
113
+ self._job_store = JobStore(scheduler_address=self._scheduler_address, db_url=self._db_url)
114
+ self._dask_available = True
115
+ logger.debug("Connected to Dask scheduler at %s", self._scheduler_address)
116
+ except Exception as e:
117
+ raise RuntimeError(f"Failed to connect to Dask scheduler at {self._scheduler_address}: {e}") from e
118
+ else:
119
+ logger.debug("No Dask scheduler address provided, running without Dask support.")
87
120
 
88
121
  @property
89
122
  def config(self) -> Config:
@@ -107,20 +140,6 @@ class FastApiFrontEndPluginWorkerBase(ABC):
107
140
 
108
141
  yield
109
142
 
110
- # If a cleanup task is running, cancel it
111
- async with self._cleanup_tasks_lock:
112
-
113
- # Cancel all cleanup tasks
114
- for task_name in self._cleanup_tasks:
115
- cleanup_task: asyncio.Task | None = getattr(starting_app.state, task_name, None)
116
- if cleanup_task is not None:
117
- logger.info("Cancelling %s cleanup task", task_name)
118
- cleanup_task.cancel()
119
- else:
120
- logger.warning("No cleanup task found for %s", task_name)
121
-
122
- self._cleanup_tasks.clear()
123
-
124
143
  logger.debug("Closing NAT server from process %s", os.getpid())
125
144
 
126
145
  nat_app = FastAPI(lifespan=lifespan)
@@ -208,32 +227,6 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
208
227
  self._outstanding_flows: dict[str, FlowState] = {}
209
228
  self._outstanding_flows_lock = asyncio.Lock()
210
229
 
211
- @staticmethod
212
- async def _periodic_cleanup(name: str, job_store: JobStore, sleep_time_sec: int = 300):
213
- while True:
214
- try:
215
- job_store.cleanup_expired_jobs()
216
- logger.debug("Expired %s jobs cleaned up", name)
217
- except Exception as e:
218
- logger.exception("Error during %s job cleanup: %s", name, e)
219
- await asyncio.sleep(sleep_time_sec)
220
-
221
- async def create_cleanup_task(self, app: FastAPI, name: str, job_store: JobStore, sleep_time_sec: int = 300):
222
- # Schedule periodic cleanup of expired jobs on first job creation
223
- attr_name = f"{name}_cleanup_task"
224
-
225
- # Cheap check, if it doesn't exist, we will need to re-check after we acquire the lock
226
- if not hasattr(app.state, attr_name):
227
- async with self._cleanup_tasks_lock:
228
- if not hasattr(app.state, attr_name):
229
- logger.info("Starting %s periodic cleanup task", name)
230
- setattr(
231
- app.state,
232
- attr_name,
233
- asyncio.create_task(
234
- self._periodic_cleanup(name=name, job_store=job_store, sleep_time_sec=sleep_time_sec)))
235
- self._cleanup_tasks.append(attr_name)
236
-
237
230
  def get_step_adaptor(self) -> StepAdaptor:
238
231
 
239
232
  return StepAdaptor(self.front_end_config.step_adaptor)
@@ -247,14 +240,15 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
247
240
 
248
241
  async def add_routes(self, app: FastAPI, builder: WorkflowBuilder):
249
242
 
250
- await self.add_default_route(app, SessionManager(builder.build()))
251
- await self.add_evaluate_route(app, SessionManager(builder.build()))
243
+ await self.add_default_route(app, SessionManager(await builder.build()))
244
+ await self.add_evaluate_route(app, SessionManager(await builder.build()))
252
245
  await self.add_static_files_route(app, builder)
253
246
  await self.add_authorization_route(app)
247
+ await self.add_mcp_client_tool_list_route(app, builder)
254
248
 
255
249
  for ep in self.front_end_config.endpoints:
256
250
 
257
- entry_workflow = builder.build(entry_function=ep.function_name)
251
+ entry_workflow = await builder.build(entry_function=ep.function_name)
258
252
 
259
253
  await self.add_route(app, endpoint=ep, session_manager=SessionManager(entry_workflow))
260
254
 
@@ -276,52 +270,72 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
276
270
  },
277
271
  }
278
272
 
279
- # Create job store for tracking evaluation jobs
280
- job_store = JobStore()
281
- # Don't run multiple evaluations at the same time
282
- evaluation_lock = asyncio.Lock()
283
-
284
- async def run_evaluation(job_id: str, config_file: str, reps: int, session_manager: SessionManager):
273
+ # TODO: Find another way to limit the number of concurrent evaluations
274
+ async def run_evaluation(scheduler_address: str,
275
+ db_url: str,
276
+ workflow_config_file_path: str,
277
+ job_id: str,
278
+ eval_config_file: str,
279
+ reps: int):
285
280
  """Background task to run the evaluation."""
286
- async with evaluation_lock:
287
- try:
288
- # Create EvaluationRunConfig using the CLI defaults
289
- eval_config = EvaluationRunConfig(config_file=Path(config_file), dataset=None, reps=reps)
290
-
291
- # Create a new EvaluationRun with the evaluation-specific config
292
- job_store.update_status(job_id, "running")
293
- eval_runner = EvaluationRun(eval_config)
294
- output: EvaluationRunOutput = await eval_runner.run_and_evaluate(session_manager=session_manager,
295
- job_id=job_id)
296
- if output.workflow_interrupted:
297
- job_store.update_status(job_id, "interrupted")
298
- else:
299
- parent_dir = os.path.dirname(
300
- output.workflow_output_file) if output.workflow_output_file else None
301
-
302
- job_store.update_status(job_id, "success", output_path=str(parent_dir))
303
- except Exception as e:
304
- logger.exception("Error in evaluation job %s: %s", job_id, str(e))
305
- job_store.update_status(job_id, "failure", error=str(e))
306
-
307
- async def start_evaluation(request: EvaluateRequest, background_tasks: BackgroundTasks, http_request: Request):
281
+ job_store = JobStore(scheduler_address=scheduler_address, db_url=db_url)
282
+
283
+ try:
284
+ # We have two config files, one for the workflow and one for the evaluation
285
+ # Create EvaluationRunConfig using the CLI defaults
286
+ eval_config = EvaluationRunConfig(config_file=Path(eval_config_file), dataset=None, reps=reps)
287
+
288
+ # Create a new EvaluationRun with the evaluation-specific config
289
+ await job_store.update_status(job_id, JobStatus.RUNNING)
290
+ eval_runner = EvaluationRun(eval_config)
291
+
292
+ async with load_workflow(workflow_config_file_path) as local_session_manager:
293
+ output: EvaluationRunOutput = await eval_runner.run_and_evaluate(
294
+ session_manager=local_session_manager, job_id=job_id)
295
+
296
+ if output.workflow_interrupted:
297
+ await job_store.update_status(job_id, JobStatus.INTERRUPTED)
298
+ else:
299
+ parent_dir = os.path.dirname(output.workflow_output_file) if output.workflow_output_file else None
300
+
301
+ await job_store.update_status(job_id, JobStatus.SUCCESS, output_path=str(parent_dir))
302
+ except Exception as e:
303
+ logger.exception("Error in evaluation job %s", job_id)
304
+ await job_store.update_status(job_id, JobStatus.FAILURE, error=str(e))
305
+
306
+ async def start_evaluation(request: EvaluateRequest, http_request: Request):
308
307
  """Handle evaluation requests."""
309
308
 
310
309
  async with session_manager.session(http_connection=http_request):
311
310
 
312
311
  # if job_id is present and already exists return the job info
312
+ # There is a race condition between this check and the actual job submission, however if the client is
313
+ # supplying their own job_ids, then it is their responsibility to ensure that the job_id is unique.
313
314
  if request.job_id:
314
- job = job_store.get_job(request.job_id)
315
- if job:
316
- return EvaluateResponse(job_id=job.job_id, status=job.status)
317
-
318
- job_id = job_store.create_job(request.config_file, request.job_id, request.expiry_seconds)
319
- await self.create_cleanup_task(app=app, name="async_evaluation", job_store=job_store)
320
- background_tasks.add_task(run_evaluation, job_id, request.config_file, request.reps, session_manager)
321
-
322
- return EvaluateResponse(job_id=job_id, status="submitted")
323
-
324
- def translate_job_to_response(job: JobInfo) -> EvaluateStatusResponse:
315
+ job_status = await self._job_store.get_status(request.job_id)
316
+ if job_status != JobStatus.NOT_FOUND:
317
+ return EvaluateResponse(job_id=request.job_id, status=job_status)
318
+
319
+ job_id = self._job_store.ensure_job_id(request.job_id)
320
+
321
+ await self._job_store.submit_job(job_id=job_id,
322
+ config_file=request.config_file,
323
+ expiry_seconds=request.expiry_seconds,
324
+ job_fn=run_evaluation,
325
+ job_args=[
326
+ self._scheduler_address,
327
+ self._db_url,
328
+ self._config_file_path,
329
+ job_id,
330
+ request.config_file,
331
+ request.reps
332
+ ])
333
+
334
+ logger.info("Submitted evaluation job %s with config %s", job_id, request.config_file)
335
+
336
+ return EvaluateResponse(job_id=job_id, status=JobStatus.SUBMITTED)
337
+
338
+ def translate_job_to_response(job: "JobInfo") -> EvaluateStatusResponse:
325
339
  """Translate a JobInfo object to an EvaluateStatusResponse."""
326
340
  return EvaluateStatusResponse(job_id=job.job_id,
327
341
  status=job.status,
@@ -330,7 +344,7 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
330
344
  output_path=str(job.output_path),
331
345
  created_at=job.created_at,
332
346
  updated_at=job.updated_at,
333
- expires_at=job_store.get_expires_at(job))
347
+ expires_at=self._job_store.get_expires_at(job))
334
348
 
335
349
  async def get_job_status(job_id: str, http_request: Request) -> EvaluateStatusResponse:
336
350
  """Get the status of an evaluation job."""
@@ -338,7 +352,7 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
338
352
 
339
353
  async with session_manager.session(http_connection=http_request):
340
354
 
341
- job = job_store.get_job(job_id)
355
+ job = await self._job_store.get_job(job_id)
342
356
  if not job:
343
357
  logger.warning("Job %s not found", job_id)
344
358
  raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
@@ -351,7 +365,7 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
351
365
 
352
366
  async with session_manager.session(http_connection=http_request):
353
367
 
354
- job = job_store.get_last_job()
368
+ job = await self._job_store.get_last_job()
355
369
  if not job:
356
370
  logger.warning("No jobs found when requesting last job status")
357
371
  raise HTTPException(status_code=404, detail="No jobs found")
@@ -365,61 +379,65 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
365
379
 
366
380
  if status is None:
367
381
  logger.info("Getting all jobs")
368
- jobs = job_store.get_all_jobs()
382
+ jobs = await self._job_store.get_all_jobs()
369
383
  else:
370
384
  logger.info("Getting jobs with status %s", status)
371
- jobs = job_store.get_jobs_by_status(status)
385
+ jobs = await self._job_store.get_jobs_by_status(JobStatus(status))
386
+
372
387
  logger.info("Found %d jobs", len(jobs))
373
388
  return [translate_job_to_response(job) for job in jobs]
374
389
 
375
390
  if self.front_end_config.evaluate.path:
376
- # Add last job endpoint first (most specific)
377
- app.add_api_route(
378
- path=f"{self.front_end_config.evaluate.path}/job/last",
379
- endpoint=get_last_job_status,
380
- methods=["GET"],
381
- response_model=EvaluateStatusResponse,
382
- description="Get the status of the last created evaluation job",
383
- responses={
384
- 404: {
385
- "description": "No jobs found"
386
- }, 500: response_500
387
- },
388
- )
391
+ if self._dask_available:
392
+ # Add last job endpoint first (most specific)
393
+ app.add_api_route(
394
+ path=f"{self.front_end_config.evaluate.path}/job/last",
395
+ endpoint=get_last_job_status,
396
+ methods=["GET"],
397
+ response_model=EvaluateStatusResponse,
398
+ description="Get the status of the last created evaluation job",
399
+ responses={
400
+ 404: {
401
+ "description": "No jobs found"
402
+ }, 500: response_500
403
+ },
404
+ )
389
405
 
390
- # Add specific job endpoint (least specific)
391
- app.add_api_route(
392
- path=f"{self.front_end_config.evaluate.path}/job/{{job_id}}",
393
- endpoint=get_job_status,
394
- methods=["GET"],
395
- response_model=EvaluateStatusResponse,
396
- description="Get the status of an evaluation job",
397
- responses={
398
- 404: {
399
- "description": "Job not found"
400
- }, 500: response_500
401
- },
402
- )
406
+ # Add specific job endpoint (least specific)
407
+ app.add_api_route(
408
+ path=f"{self.front_end_config.evaluate.path}/job/{{job_id}}",
409
+ endpoint=get_job_status,
410
+ methods=["GET"],
411
+ response_model=EvaluateStatusResponse,
412
+ description="Get the status of an evaluation job",
413
+ responses={
414
+ 404: {
415
+ "description": "Job not found"
416
+ }, 500: response_500
417
+ },
418
+ )
403
419
 
404
- # Add jobs endpoint with optional status query parameter
405
- app.add_api_route(
406
- path=f"{self.front_end_config.evaluate.path}/jobs",
407
- endpoint=get_jobs,
408
- methods=["GET"],
409
- response_model=list[EvaluateStatusResponse],
410
- description="Get all jobs, optionally filtered by status",
411
- responses={500: response_500},
412
- )
420
+ # Add jobs endpoint with optional status query parameter
421
+ app.add_api_route(
422
+ path=f"{self.front_end_config.evaluate.path}/jobs",
423
+ endpoint=get_jobs,
424
+ methods=["GET"],
425
+ response_model=list[EvaluateStatusResponse],
426
+ description="Get all jobs, optionally filtered by status",
427
+ responses={500: response_500},
428
+ )
413
429
 
414
- # Add HTTP endpoint for evaluation
415
- app.add_api_route(
416
- path=self.front_end_config.evaluate.path,
417
- endpoint=start_evaluation,
418
- methods=[self.front_end_config.evaluate.method],
419
- response_model=EvaluateResponse,
420
- description=self.front_end_config.evaluate.description,
421
- responses={500: response_500},
422
- )
430
+ # Add HTTP endpoint for evaluation
431
+ app.add_api_route(
432
+ path=self.front_end_config.evaluate.path,
433
+ endpoint=start_evaluation,
434
+ methods=[self.front_end_config.evaluate.method],
435
+ response_model=EvaluateResponse,
436
+ description=self.front_end_config.evaluate.description,
437
+ responses={500: response_500},
438
+ )
439
+ else:
440
+ logger.warning("Dask is not available, evaluation endpoints will not be added.")
423
441
 
424
442
  async def add_static_files_route(self, app: FastAPI, builder: WorkflowBuilder):
425
443
 
@@ -526,21 +544,28 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
526
544
  GenerateStreamResponseType = workflow.streaming_output_schema
527
545
  GenerateSingleResponseType = workflow.single_output_schema
528
546
 
529
- # Append job_id and expiry_seconds to the input schema, this effectively makes these reserved keywords
530
- # Consider prefixing these with "nat_" to avoid conflicts
531
- class AsyncGenerateRequest(GenerateBodyType):
532
- job_id: str | None = Field(default=None, description="Unique identifier for the evaluation job")
533
- sync_timeout: int = Field(
534
- default=0,
535
- ge=0,
536
- le=300,
537
- description="Attempt to perform the job synchronously up until `sync_timeout` sectonds, "
538
- "if the job hasn't been completed by then a job_id will be returned with a status code of 202.")
539
- expiry_seconds: int = Field(default=JobStore.DEFAULT_EXPIRY,
540
- ge=JobStore.MIN_EXPIRY,
541
- le=JobStore.MAX_EXPIRY,
542
- description="Optional time (in seconds) before the job expires. "
543
- "Clamped between 600 (10 min) and 86400 (24h).")
547
+ # Skip async generation for custom routes (those with function_name)
548
+ if self._dask_available and not hasattr(endpoint, 'function_name'):
549
+ # Append job_id and expiry_seconds to the input schema, this effectively makes these reserved keywords
550
+ # Consider prefixing these with "nat_" to avoid conflicts
551
+
552
+ class AsyncGenerateRequest(GenerateBodyType):
553
+ job_id: str | None = Field(default=None, description="Unique identifier for the evaluation job")
554
+ sync_timeout: int = Field(
555
+ default=0,
556
+ ge=0,
557
+ le=300,
558
+ description="Attempt to perform the job synchronously up until `sync_timeout` sectonds, "
559
+ "if the job hasn't been completed by then a job_id will be returned with a status code of 202.")
560
+ expiry_seconds: int = Field(default=JobStore.DEFAULT_EXPIRY,
561
+ ge=JobStore.MIN_EXPIRY,
562
+ le=JobStore.MAX_EXPIRY,
563
+ description="Optional time (in seconds) before the job expires. "
564
+ "Clamped between 600 (10 min) and 86400 (24h).")
565
+
566
+ def validate_model(self):
567
+ # Override to ensure that the parent class validator is not called
568
+ return self
544
569
 
545
570
  # Ensure that the input is in the body. POD types are treated as query parameters
546
571
  if (not issubclass(GenerateBodyType, BaseModel)):
@@ -560,12 +585,6 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
560
585
  },
561
586
  }
562
587
 
563
- # Create job store for tracking async generation jobs
564
- job_store = JobStore()
565
-
566
- # Run up to max_running_async_jobs jobs at the same time
567
- async_job_concurrency = asyncio.Semaphore(self._front_end_config.max_running_async_jobs)
568
-
569
588
  def get_single_endpoint(result_type: type | None):
570
589
 
571
590
  async def get_single(response: Response, request: Request):
@@ -675,10 +694,13 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
675
694
 
676
695
  async def post_openai_api_compatible(response: Response, request: Request, payload: request_type):
677
696
  # Check if streaming is requested
697
+
698
+ response.headers["Content-Type"] = "application/json"
678
699
  stream_requested = getattr(payload, 'stream', False)
679
700
 
680
701
  async with session_manager.session(http_connection=request):
681
702
  if stream_requested:
703
+
682
704
  # Return streaming response
683
705
  return StreamingResponse(headers={"Content-Type": "text/event-stream; charset=utf-8"},
684
706
  content=generate_streaming_response_as_str(
@@ -689,71 +711,48 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
689
711
  result_type=ChatResponseChunk,
690
712
  output_type=ChatResponseChunk))
691
713
 
692
- # Return single response - check if workflow supports non-streaming
693
- try:
694
- response.headers["Content-Type"] = "application/json"
695
- return await generate_single_response(payload, session_manager, result_type=ChatResponse)
696
- except ValueError as e:
697
- if "Cannot get a single output value for streaming workflows" in str(e):
698
- # Workflow only supports streaming, but client requested non-streaming
699
- # Fall back to streaming and collect the result
700
- chunks = []
701
- async for chunk_str in generate_streaming_response_as_str(
702
- payload,
703
- session_manager=session_manager,
704
- streaming=True,
705
- step_adaptor=self.get_step_adaptor(),
706
- result_type=ChatResponseChunk,
707
- output_type=ChatResponseChunk):
708
- if chunk_str.startswith("data: ") and not chunk_str.startswith("data: [DONE]"):
709
- chunk_data = chunk_str[6:].strip() # Remove "data: " prefix
710
- if chunk_data:
711
- try:
712
- chunk_json = ChatResponseChunk.model_validate_json(chunk_data)
713
- if (chunk_json.choices and len(chunk_json.choices) > 0
714
- and chunk_json.choices[0].delta
715
- and chunk_json.choices[0].delta.content is not None):
716
- chunks.append(chunk_json.choices[0].delta.content)
717
- except Exception:
718
- continue
719
-
720
- # Create a single response from collected chunks
721
- content = "".join(chunks)
722
- single_response = ChatResponse.from_string(content)
723
- response.headers["Content-Type"] = "application/json"
724
- return single_response
725
- raise
714
+ return await generate_single_response(payload, session_manager, result_type=ChatResponse)
726
715
 
727
716
  return post_openai_api_compatible
728
717
 
729
- async def run_generation(job_id: str, payload: typing.Any, session_manager: SessionManager, result_type: type):
730
- """Background task to run the evaluation."""
731
- async with async_job_concurrency:
732
- try:
733
- result = await generate_single_response(payload=payload,
734
- session_manager=session_manager,
735
- result_type=result_type)
736
- job_store.update_status(job_id, "success", output=result)
737
- except Exception as e:
738
- logger.exception("Error in evaluation job %s: %s", job_id, e)
739
- job_store.update_status(job_id, "failure", error=str(e))
740
-
741
- def _job_status_to_response(job: JobInfo) -> AsyncGenerationStatusResponse:
718
+ def _job_status_to_response(job: "JobInfo") -> AsyncGenerationStatusResponse:
742
719
  job_output = job.output
743
720
  if job_output is not None:
744
- job_output = job_output.model_dump()
721
+ try:
722
+ job_output = json.loads(job_output)
723
+ except json.JSONDecodeError:
724
+ logger.error("Failed to parse job output as JSON: %s", job_output)
725
+ job_output = {"error": "Output parsing failed"}
726
+
745
727
  return AsyncGenerationStatusResponse(job_id=job.job_id,
746
728
  status=job.status,
747
729
  error=job.error,
748
730
  output=job_output,
749
731
  created_at=job.created_at,
750
732
  updated_at=job.updated_at,
751
- expires_at=job_store.get_expires_at(job))
733
+ expires_at=self._job_store.get_expires_at(job))
734
+
735
+ async def run_generation(scheduler_address: str,
736
+ db_url: str,
737
+ config_file_path: str,
738
+ job_id: str,
739
+ payload: typing.Any):
740
+ """Background task to run the workflow."""
741
+ job_store = JobStore(scheduler_address=scheduler_address, db_url=db_url)
742
+ try:
743
+ async with load_workflow(config_file_path) as local_session_manager:
744
+ result = await generate_single_response(
745
+ payload, local_session_manager, result_type=local_session_manager.workflow.single_output_schema)
752
746
 
753
- def post_async_generation(request_type: type, final_result_type: type):
747
+ await job_store.update_status(job_id, JobStatus.SUCCESS, output=result)
748
+ except Exception as e:
749
+ logger.exception("Error in async job %s", job_id)
750
+ await job_store.update_status(job_id, JobStatus.FAILURE, error=str(e))
751
+
752
+ def post_async_generation(request_type: type):
754
753
 
755
754
  async def start_async_generation(
756
- request: request_type, background_tasks: BackgroundTasks, response: Response,
755
+ request: request_type, response: Response,
757
756
  http_request: Request) -> AsyncGenerateResponse | AsyncGenerationStatusResponse:
758
757
  """Handle async generation requests."""
759
758
 
@@ -761,41 +760,30 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
761
760
 
762
761
  # if job_id is present and already exists return the job info
763
762
  if request.job_id:
764
- job = job_store.get_job(request.job_id)
763
+ job = await self._job_store.get_job(request.job_id)
765
764
  if job:
766
765
  return AsyncGenerateResponse(job_id=job.job_id, status=job.status)
767
766
 
768
- job_id = job_store.create_job(job_id=request.job_id, expiry_seconds=request.expiry_seconds)
769
- await self.create_cleanup_task(app=app, name="async_generation", job_store=job_store)
770
-
771
- # The fastapi/starlette background tasks won't begin executing until after the response is sent
772
- # to the client, so we need to wrap the task in a function, alowing us to start the task now,
773
- # and allowing the background task function to await the results.
774
- task = asyncio.create_task(
775
- run_generation(job_id=job_id,
776
- payload=request,
777
- session_manager=session_manager,
778
- result_type=final_result_type))
779
-
780
- async def wrapped_task(t: asyncio.Task):
781
- return await t
782
-
783
- background_tasks.add_task(wrapped_task, task)
784
-
785
- now = time.time()
786
- sync_timeout = now + request.sync_timeout
787
- while time.time() < sync_timeout:
788
- job = job_store.get_job(job_id)
789
- if job is not None and job.status not in job_store.ACTIVE_STATUS:
790
- # If the job is done, return the result
791
- response.status_code = 200
792
- return _job_status_to_response(job)
793
-
794
- # Sleep for a short time before checking again
795
- await asyncio.sleep(0.1)
767
+ job_id = self._job_store.ensure_job_id(request.job_id)
768
+ (_, job) = await self._job_store.submit_job(
769
+ job_id=job_id,
770
+ expiry_seconds=request.expiry_seconds,
771
+ job_fn=run_generation,
772
+ sync_timeout=request.sync_timeout,
773
+ job_args=[
774
+ self._scheduler_address,
775
+ self._db_url,
776
+ self._config_file_path,
777
+ job_id,
778
+ request.model_dump(mode="json", exclude=["job_id", "sync_timeout", "expiry_seconds"])
779
+ ])
780
+
781
+ if job is not None:
782
+ response.status_code = 200
783
+ return _job_status_to_response(job)
796
784
 
797
785
  response.status_code = 202
798
- return AsyncGenerateResponse(job_id=job_id, status="submitted")
786
+ return AsyncGenerateResponse(job_id=job_id, status=JobStatus.SUBMITTED)
799
787
 
800
788
  return start_async_generation
801
789
 
@@ -805,8 +793,8 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
805
793
 
806
794
  async with session_manager.session(http_connection=http_request):
807
795
 
808
- job = job_store.get_job(job_id)
809
- if not job:
796
+ job = await self._job_store.get_job(job_id)
797
+ if job is None:
810
798
  logger.warning("Job %s not found", job_id)
811
799
  raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
812
800
 
@@ -934,30 +922,33 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
934
922
  responses={500: response_500},
935
923
  )
936
924
 
937
- app.add_api_route(
938
- path=f"{endpoint.path}/async",
939
- endpoint=post_async_generation(request_type=AsyncGenerateRequest,
940
- final_result_type=GenerateSingleResponseType),
941
- methods=[endpoint.method],
942
- response_model=AsyncGenerateResponse | AsyncGenerationStatusResponse,
943
- description="Start an async generate job",
944
- responses={500: response_500},
945
- )
925
+ if self._dask_available and not hasattr(endpoint, 'function_name'):
926
+ app.add_api_route(
927
+ path=f"{endpoint.path}/async",
928
+ endpoint=post_async_generation(request_type=AsyncGenerateRequest),
929
+ methods=[endpoint.method],
930
+ response_model=AsyncGenerateResponse | AsyncGenerationStatusResponse,
931
+ description="Start an async generate job",
932
+ responses={500: response_500},
933
+ )
934
+ else:
935
+ logger.warning("Dask is not available, async generation endpoints will not be added.")
946
936
  else:
947
937
  raise ValueError(f"Unsupported method {endpoint.method}")
948
938
 
949
- app.add_api_route(
950
- path=f"{endpoint.path}/async/job/{{job_id}}",
951
- endpoint=get_async_job_status,
952
- methods=["GET"],
953
- response_model=AsyncGenerationStatusResponse,
954
- description="Get the status of an async job",
955
- responses={
956
- 404: {
957
- "description": "Job not found"
958
- }, 500: response_500
959
- },
960
- )
939
+ if self._dask_available and not hasattr(endpoint, 'function_name'):
940
+ app.add_api_route(
941
+ path=f"{endpoint.path}/async/job/{{job_id}}",
942
+ endpoint=get_async_job_status,
943
+ methods=["GET"],
944
+ response_model=AsyncGenerationStatusResponse,
945
+ description="Get the status of an async job",
946
+ responses={
947
+ 404: {
948
+ "description": "Job not found"
949
+ }, 500: response_500
950
+ },
951
+ )
961
952
 
962
953
  if (endpoint.openai_api_path):
963
954
  if (endpoint.method == "GET"):
@@ -1060,8 +1051,13 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
1060
1051
  code_verifier=verifier,
1061
1052
  state=state)
1062
1053
  flow_state.future.set_result(res)
1054
+ except OAuthError as e:
1055
+ flow_state.future.set_exception(
1056
+ RuntimeError(f"Authorization server rejected request: {e.error} ({e.description})"))
1057
+ except httpx.HTTPError as e:
1058
+ flow_state.future.set_exception(RuntimeError(f"Network error during token fetch: {e}"))
1063
1059
  except Exception as e:
1064
- flow_state.future.set_exception(e)
1060
+ flow_state.future.set_exception(RuntimeError(f"Authentication failed: {e}"))
1065
1061
 
1066
1062
  return HTMLResponse(content=AUTH_REDIRECT_SUCCESS_HTML,
1067
1063
  status_code=200,
@@ -1077,6 +1073,186 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
1077
1073
  methods=["GET"],
1078
1074
  description="Handles the authorization code and state returned from the Authorization Code Grant Flow.")
1079
1075
 
1076
+ async def add_mcp_client_tool_list_route(self, app: FastAPI, builder: WorkflowBuilder):
1077
+ """Add the MCP client tool list endpoint to the FastAPI app."""
1078
+ from typing import Any
1079
+
1080
+ from pydantic import BaseModel
1081
+
1082
+ class MCPToolInfo(BaseModel):
1083
+ name: str
1084
+ description: str
1085
+ server: str
1086
+ available: bool
1087
+
1088
+ class MCPClientToolListResponse(BaseModel):
1089
+ mcp_clients: list[dict[str, Any]]
1090
+
1091
+ async def get_mcp_client_tool_list() -> MCPClientToolListResponse:
1092
+ """
1093
+ Get the list of MCP tools from all MCP clients in the workflow configuration.
1094
+ Checks session health and compares with workflow function group configuration.
1095
+ """
1096
+ mcp_clients_info = []
1097
+
1098
+ try:
1099
+ # Get all function groups from the builder
1100
+ function_groups = builder._function_groups
1101
+
1102
+ # Find MCP client function groups
1103
+ for group_name, configured_group in function_groups.items():
1104
+ if configured_group.config.type != "mcp_client":
1105
+ continue
1106
+
1107
+ from nat.plugins.mcp.client_config import MCPClientConfig
1108
+
1109
+ config = configured_group.config
1110
+ assert isinstance(config, MCPClientConfig)
1111
+
1112
+ # Reuse the existing MCP client session stored on the function group instance
1113
+ group_instance = configured_group.instance
1114
+
1115
+ client = group_instance.mcp_client
1116
+ if client is None:
1117
+ raise RuntimeError(f"MCP client not found for group {group_name}")
1118
+
1119
+ try:
1120
+ session_healthy = False
1121
+ server_tools: dict[str, Any] = {}
1122
+
1123
+ try:
1124
+ server_tools = await client.get_tools()
1125
+ session_healthy = True
1126
+ except Exception as e:
1127
+ logger.exception(f"Failed to connect to MCP server {client.server_name}: {e}")
1128
+ session_healthy = False
1129
+
1130
+ # Get workflow function group configuration (configured client-side tools)
1131
+ configured_short_names: set[str] = set()
1132
+ configured_full_to_fn: dict[str, Function] = {}
1133
+ try:
1134
+ # Pass a no-op filter function to bypass any default filtering that might check
1135
+ # health status, preventing potential infinite recursion during health status checks.
1136
+ async def pass_through_filter(fn):
1137
+ return fn
1138
+
1139
+ accessible_functions = await group_instance.get_accessible_functions(
1140
+ filter_fn=pass_through_filter)
1141
+ configured_full_to_fn = accessible_functions
1142
+ configured_short_names = {name.split('.', 1)[1] for name in accessible_functions.keys()}
1143
+ except Exception as e:
1144
+ logger.exception(f"Failed to get accessible functions for group {group_name}: {e}")
1145
+
1146
+ # Build alias->original mapping and override configs from overrides
1147
+ alias_to_original: dict[str, str] = {}
1148
+ override_configs: dict[str, Any] = {}
1149
+ try:
1150
+ if config.tool_overrides is not None:
1151
+ for orig_name, override in config.tool_overrides.items():
1152
+ if override.alias is not None:
1153
+ alias_to_original[override.alias] = orig_name
1154
+ override_configs[override.alias] = override
1155
+ else:
1156
+ override_configs[orig_name] = override
1157
+ except Exception:
1158
+ pass
1159
+
1160
+ # Create tool info list (always return configured tools; mark availability)
1161
+ tools_info: list[dict[str, Any]] = []
1162
+ available_count = 0
1163
+ for wf_fn, fn_short in zip(configured_full_to_fn.values(), configured_short_names):
1164
+ orig_name = alias_to_original.get(fn_short, fn_short)
1165
+ available = session_healthy and (orig_name in server_tools)
1166
+ if available:
1167
+ available_count += 1
1168
+
1169
+ # Prefer tool override description, then workflow function description,
1170
+ # then server description
1171
+ description = ""
1172
+ if fn_short in override_configs and override_configs[fn_short].description:
1173
+ description = override_configs[fn_short].description
1174
+ elif wf_fn.description:
1175
+ description = wf_fn.description
1176
+ elif available and orig_name in server_tools:
1177
+ description = server_tools[orig_name].description or ""
1178
+
1179
+ tools_info.append(
1180
+ MCPToolInfo(name=fn_short,
1181
+ description=description or "",
1182
+ server=client.server_name,
1183
+ available=available).model_dump())
1184
+
1185
+ # Sort tools_info by name to maintain consistent ordering
1186
+ tools_info.sort(key=lambda x: x['name'])
1187
+
1188
+ mcp_clients_info.append({
1189
+ "function_group": group_name,
1190
+ "server": client.server_name,
1191
+ "transport": config.server.transport,
1192
+ "session_healthy": session_healthy,
1193
+ "protected": True if config.server.auth_provider is not None else False,
1194
+ "tools": tools_info,
1195
+ "total_tools": len(configured_short_names),
1196
+ "available_tools": available_count
1197
+ })
1198
+
1199
+ except Exception as e:
1200
+ logger.error(f"Error processing MCP client {group_name}: {e}")
1201
+ mcp_clients_info.append({
1202
+ "function_group": group_name,
1203
+ "server": "unknown",
1204
+ "transport": config.server.transport if config.server else "unknown",
1205
+ "session_healthy": False,
1206
+ "protected": False,
1207
+ "error": str(e),
1208
+ "tools": [],
1209
+ "total_tools": 0,
1210
+ "workflow_tools": 0
1211
+ })
1212
+
1213
+ return MCPClientToolListResponse(mcp_clients=mcp_clients_info)
1214
+
1215
+ except Exception as e:
1216
+ logger.error(f"Error in MCP client tool list endpoint: {e}")
1217
+ raise HTTPException(status_code=500, detail=f"Failed to retrieve MCP client information: {str(e)}")
1218
+
1219
+ # Add the route to the FastAPI app
1220
+ app.add_api_route(
1221
+ path="/mcp/client/tool/list",
1222
+ endpoint=get_mcp_client_tool_list,
1223
+ methods=["GET"],
1224
+ response_model=MCPClientToolListResponse,
1225
+ description="Get list of MCP client tools with session health and workflow configuration comparison",
1226
+ responses={
1227
+ 200: {
1228
+ "description": "Successfully retrieved MCP client tool information",
1229
+ "content": {
1230
+ "application/json": {
1231
+ "example": {
1232
+ "mcp_clients": [{
1233
+ "function_group": "mcp_tools",
1234
+ "server": "streamable-http:http://localhost:9901/mcp",
1235
+ "transport": "streamable-http",
1236
+ "session_healthy": True,
1237
+ "protected": False,
1238
+ "tools": [{
1239
+ "name": "tool_a",
1240
+ "description": "Tool A description",
1241
+ "server": "streamable-http:http://localhost:9901/mcp",
1242
+ "available": True
1243
+ }],
1244
+ "total_tools": 1,
1245
+ "available_tools": 1
1246
+ }]
1247
+ }
1248
+ }
1249
+ }
1250
+ },
1251
+ 500: {
1252
+ "description": "Internal Server Error"
1253
+ }
1254
+ })
1255
+
1080
1256
  async def _add_flow(self, state: str, flow_state: FlowState):
1081
1257
  async with self._outstanding_flows_lock:
1082
1258
  self._outstanding_flows[state] = flow_state
@@ -1084,3 +1260,7 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
1084
1260
  async def _remove_flow(self, state: str):
1085
1261
  async with self._outstanding_flows_lock:
1086
1262
  del self._outstanding_flows[state]
1263
+
1264
+
1265
+ # Prevent Sphinx from documenting items not a part of the public API
1266
+ __all__ = ["FastApiFrontEndPluginWorkerBase", "FastApiFrontEndPluginWorker", "RouteInfo"]