nvidia-nat-mcp 1.4.0a20260107__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 (37) hide show
  1. nat/meta/pypi.md +32 -0
  2. nat/plugins/mcp/__init__.py +14 -0
  3. nat/plugins/mcp/auth/__init__.py +14 -0
  4. nat/plugins/mcp/auth/auth_flow_handler.py +208 -0
  5. nat/plugins/mcp/auth/auth_provider.py +431 -0
  6. nat/plugins/mcp/auth/auth_provider_config.py +86 -0
  7. nat/plugins/mcp/auth/register.py +33 -0
  8. nat/plugins/mcp/auth/service_account/__init__.py +14 -0
  9. nat/plugins/mcp/auth/service_account/provider.py +136 -0
  10. nat/plugins/mcp/auth/service_account/provider_config.py +137 -0
  11. nat/plugins/mcp/auth/service_account/token_client.py +156 -0
  12. nat/plugins/mcp/auth/token_storage.py +265 -0
  13. nat/plugins/mcp/cli/__init__.py +15 -0
  14. nat/plugins/mcp/cli/commands.py +1051 -0
  15. nat/plugins/mcp/client/__init__.py +15 -0
  16. nat/plugins/mcp/client/client_base.py +665 -0
  17. nat/plugins/mcp/client/client_config.py +146 -0
  18. nat/plugins/mcp/client/client_impl.py +782 -0
  19. nat/plugins/mcp/exception_handler.py +211 -0
  20. nat/plugins/mcp/exceptions.py +142 -0
  21. nat/plugins/mcp/register.py +23 -0
  22. nat/plugins/mcp/server/__init__.py +15 -0
  23. nat/plugins/mcp/server/front_end_config.py +109 -0
  24. nat/plugins/mcp/server/front_end_plugin.py +155 -0
  25. nat/plugins/mcp/server/front_end_plugin_worker.py +411 -0
  26. nat/plugins/mcp/server/introspection_token_verifier.py +72 -0
  27. nat/plugins/mcp/server/memory_profiler.py +320 -0
  28. nat/plugins/mcp/server/register_frontend.py +27 -0
  29. nat/plugins/mcp/server/tool_converter.py +286 -0
  30. nat/plugins/mcp/utils.py +228 -0
  31. nvidia_nat_mcp-1.4.0a20260107.dist-info/METADATA +55 -0
  32. nvidia_nat_mcp-1.4.0a20260107.dist-info/RECORD +37 -0
  33. nvidia_nat_mcp-1.4.0a20260107.dist-info/WHEEL +5 -0
  34. nvidia_nat_mcp-1.4.0a20260107.dist-info/entry_points.txt +9 -0
  35. nvidia_nat_mcp-1.4.0a20260107.dist-info/licenses/LICENSE-3rd-party.txt +5478 -0
  36. nvidia_nat_mcp-1.4.0a20260107.dist-info/licenses/LICENSE.md +201 -0
  37. nvidia_nat_mcp-1.4.0a20260107.dist-info/top_level.txt +1 -0
@@ -0,0 +1,411 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import logging
17
+ from abc import ABC
18
+ from abc import abstractmethod
19
+ from collections.abc import Mapping
20
+ from typing import TYPE_CHECKING
21
+ from typing import Any
22
+
23
+ from starlette.exceptions import HTTPException
24
+ from starlette.requests import Request
25
+
26
+ from mcp.server.fastmcp import FastMCP
27
+
28
+ if TYPE_CHECKING:
29
+ from fastapi import FastAPI
30
+
31
+ from nat.builder.function import Function
32
+ from nat.builder.function_base import FunctionBase
33
+ from nat.builder.workflow import Workflow
34
+ from nat.builder.workflow_builder import WorkflowBuilder
35
+ from nat.data_models.config import Config
36
+ from nat.plugins.mcp.server.front_end_config import MCPFrontEndConfig
37
+ from nat.plugins.mcp.server.memory_profiler import MemoryProfiler
38
+ from nat.runtime.session import SessionManager
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+
43
+ class MCPFrontEndPluginWorkerBase(ABC):
44
+ """Base class for MCP front end plugin workers.
45
+
46
+ This abstract base class provides shared utilities and defines the contract
47
+ for MCP worker implementations. Most users should inherit from
48
+ MCPFrontEndPluginWorker instead of this class directly.
49
+ """
50
+
51
+ def __init__(self, config: Config):
52
+ """Initialize the MCP worker with configuration.
53
+
54
+ Args:
55
+ config: The full NAT configuration
56
+ """
57
+ self.full_config = config
58
+ self.front_end_config: MCPFrontEndConfig = config.general.front_end
59
+
60
+ # Initialize memory profiler if enabled
61
+ self.memory_profiler = MemoryProfiler(enabled=self.front_end_config.enable_memory_profiling,
62
+ log_interval=self.front_end_config.memory_profile_interval,
63
+ top_n=self.front_end_config.memory_profile_top_n,
64
+ log_level=self.front_end_config.memory_profile_log_level)
65
+
66
+ def _setup_health_endpoint(self, mcp: FastMCP):
67
+ """Set up the HTTP health endpoint that exercises MCP ping handler."""
68
+
69
+ @mcp.custom_route("/health", methods=["GET"])
70
+ async def health_check(_request: Request):
71
+ """HTTP health check using server's internal ping handler"""
72
+ from starlette.responses import JSONResponse
73
+
74
+ try:
75
+ from mcp.types import PingRequest
76
+
77
+ # Create a ping request
78
+ ping_request = PingRequest(method="ping")
79
+
80
+ # Call the ping handler directly (same one that responds to MCP pings)
81
+ await mcp._mcp_server.request_handlers[PingRequest](ping_request)
82
+
83
+ return JSONResponse({
84
+ "status": "healthy",
85
+ "error": None,
86
+ "server_name": mcp.name,
87
+ })
88
+
89
+ except Exception as e:
90
+ return JSONResponse({
91
+ "status": "unhealthy",
92
+ "error": str(e),
93
+ "server_name": mcp.name,
94
+ },
95
+ status_code=503)
96
+
97
+ @abstractmethod
98
+ async def create_mcp_server(self) -> FastMCP:
99
+ """Create and configure the MCP server instance.
100
+
101
+ This is the main extension point. Plugins can return FastMCP or any subclass
102
+ to customize server behavior (for example, add authentication, custom transports).
103
+
104
+ Returns:
105
+ FastMCP instance or a subclass with custom behavior
106
+ """
107
+ ...
108
+
109
+ @abstractmethod
110
+ async def add_routes(self, mcp: FastMCP, builder: WorkflowBuilder):
111
+ """Add routes to the MCP server.
112
+
113
+ Plugins must implement this method. Most plugins can call
114
+ _default_add_routes() for standard behavior and then add
115
+ custom enhancements.
116
+
117
+ Args:
118
+ mcp: The FastMCP server instance
119
+ builder: The workflow builder instance
120
+ """
121
+ ...
122
+
123
+ async def _default_add_routes(self, mcp: FastMCP, builder: WorkflowBuilder):
124
+ """Default route registration logic - reusable by subclasses.
125
+
126
+ This is a protected helper method that plugins can call to get
127
+ standard route registration behavior. Plugins typically call this
128
+ from their add_routes() implementation and then add custom features.
129
+
130
+ This method:
131
+ - Sets up the health endpoint
132
+ - Builds the workflow and extracts all functions
133
+ - Filters functions based on tool_names config
134
+ - Registers each function as an MCP tool
135
+ - Sets up debug endpoints for tool introspection
136
+
137
+ Args:
138
+ mcp: The FastMCP server instance
139
+ builder: The workflow builder instance
140
+ """
141
+ from nat.plugins.mcp.server.tool_converter import register_function_with_mcp
142
+
143
+ # Set up the health endpoint
144
+ self._setup_health_endpoint(mcp)
145
+
146
+ # Build the default workflow
147
+ workflow = await builder.build()
148
+
149
+ # Get all functions from the workflow
150
+ functions = await self._get_all_functions(workflow)
151
+
152
+ # Filter functions based on tool_names if provided
153
+ if self.front_end_config.tool_names:
154
+ logger.info("Filtering functions based on tool_names: %s", self.front_end_config.tool_names)
155
+ filtered_functions: dict[str, Function] = {}
156
+ for function_name, function in functions.items():
157
+ if function_name in self.front_end_config.tool_names:
158
+ # Treat current tool_names as function names, so check if the function name is in the list
159
+ filtered_functions[function_name] = function
160
+ elif any(function_name.startswith(f"{group_name}.") for group_name in self.front_end_config.tool_names):
161
+ # Treat tool_names as function group names, so check if the function name starts with the group name
162
+ filtered_functions[function_name] = function
163
+ else:
164
+ logger.debug("Skipping function %s as it's not in tool_names", function_name)
165
+ functions = filtered_functions
166
+
167
+ # Create SessionManagers for each function
168
+ # For regular functions, wrap them in a mini-workflow with that function as entry point
169
+ # For workflows, use them directly
170
+ session_managers: dict[str, SessionManager] = {}
171
+ for function_name, function in functions.items():
172
+ if isinstance(function, Workflow):
173
+ # Already a workflow, use it directly
174
+ logger.info("Function %s is a Workflow, using directly", function_name)
175
+ session_managers[function_name] = await SessionManager.create(config=self.full_config,
176
+ shared_builder=builder,
177
+ entry_function=None)
178
+ else:
179
+ # Regular function - build a workflow with this function as entry point
180
+ logger.info("Function %s is a regular function, building entry workflow", function_name)
181
+ session_managers[function_name] = await SessionManager.create(config=self.full_config,
182
+ shared_builder=builder,
183
+ entry_function=function_name)
184
+
185
+ # Register each function with MCP, passing SessionManager for observability
186
+ for function_name, session_manager in session_managers.items():
187
+ register_function_with_mcp(mcp, function_name, session_manager, self.memory_profiler)
188
+
189
+ # Add a simple fallback function if no functions were found
190
+ if not session_managers:
191
+ raise RuntimeError("No functions found in workflow. Please check your configuration.")
192
+
193
+ # After registration, expose debug endpoints for tool/schema inspection
194
+ # Extract the entry functions from session managers for debug endpoints
195
+ debug_functions = {name: sm.workflow for name, sm in session_managers.items()}
196
+ self._setup_debug_endpoints(mcp, debug_functions)
197
+
198
+ async def _get_all_functions(self, workflow: Workflow) -> dict[str, Function]:
199
+ """Get all functions from the workflow.
200
+
201
+ Args:
202
+ workflow: The NAT workflow.
203
+
204
+ Returns:
205
+ Dict mapping function names to Function objects.
206
+ """
207
+ functions: dict[str, Function] = {}
208
+
209
+ # Extract all functions from the workflow
210
+ functions.update(workflow.functions)
211
+ for function_group in workflow.function_groups.values():
212
+ functions.update(await function_group.get_accessible_functions())
213
+
214
+ if workflow.config.workflow.workflow_alias:
215
+ functions[workflow.config.workflow.workflow_alias] = workflow
216
+ else:
217
+ functions[workflow.config.workflow.type] = workflow
218
+
219
+ return functions
220
+
221
+ async def add_root_level_routes(self, wrapper_app: "FastAPI", mcp: FastMCP) -> None:
222
+ """Add routes to the wrapper FastAPI app (optional extension point).
223
+
224
+ This method is called when base_path is configured and a wrapper
225
+ FastAPI app is created to mount the MCP server. Plugins can override
226
+ this to add routes to the wrapper app at the root level, outside the
227
+ mounted MCP server path.
228
+
229
+ Common use cases:
230
+ - OAuth discovery endpoints (e.g., /.well-known/oauth-protected-resource)
231
+ - Health checks at root level
232
+ - Static file serving
233
+ - Custom authentication/authorization endpoints
234
+
235
+ Default implementation does nothing, making this an optional extension point.
236
+
237
+ Args:
238
+ wrapper_app: The FastAPI wrapper application that mounts the MCP server
239
+ mcp: The FastMCP server instance (already mounted at base_path)
240
+ """
241
+ pass # Default: no additional root-level routes
242
+
243
+ def _setup_debug_endpoints(self, mcp: FastMCP, functions: Mapping[str, FunctionBase]) -> None:
244
+ """Set up HTTP debug endpoints for introspecting tools and schemas.
245
+
246
+ Exposes:
247
+ - GET /debug/tools/list: List tools. Optional query param `name` (one or more, repeatable or comma separated)
248
+ selects a subset and returns details for those tools.
249
+ - GET /debug/memory/stats: Get current memory profiling statistics (read-only)
250
+ """
251
+
252
+ @mcp.custom_route("/debug/tools/list", methods=["GET"])
253
+ async def list_tools(request: Request):
254
+ """HTTP list tools endpoint."""
255
+
256
+ from starlette.responses import JSONResponse
257
+
258
+ from nat.plugins.mcp.server.tool_converter import get_function_description
259
+
260
+ # Query params
261
+ # Support repeated names and comma-separated lists
262
+ names_param_list = set(request.query_params.getlist("name"))
263
+ names: list[str] = []
264
+ for raw in names_param_list:
265
+ # if p.strip() is empty, it won't be included in the list!
266
+ parts = [p.strip() for p in raw.split(",") if p.strip()]
267
+ names.extend(parts)
268
+ detail_raw = request.query_params.get("detail")
269
+
270
+ def _parse_detail_param(detail_param: str | None, has_names: bool) -> bool:
271
+ if detail_param is None:
272
+ if has_names:
273
+ return True
274
+ return False
275
+ v = detail_param.strip().lower()
276
+ if v in ("0", "false", "no", "off"):
277
+ return False
278
+ if v in ("1", "true", "yes", "on"):
279
+ return True
280
+ # For invalid values, default based on whether names are present
281
+ return has_names
282
+
283
+ # Helper function to build the input schema info
284
+ def _build_schema_info(fn: FunctionBase) -> dict[str, Any] | None:
285
+ schema = getattr(fn, "input_schema", None)
286
+ if schema is None:
287
+ return None
288
+
289
+ # check if schema is a ChatRequest
290
+ schema_name = getattr(schema, "__name__", "")
291
+ schema_qualname = getattr(schema, "__qualname__", "")
292
+ if "ChatRequest" in schema_name or "ChatRequest" in schema_qualname:
293
+ # Simplified interface used by MCP wrapper for ChatRequest
294
+ return {
295
+ "type": "object",
296
+ "properties": {
297
+ "query": {
298
+ "type": "string", "description": "User query string"
299
+ }
300
+ },
301
+ "required": ["query"],
302
+ "title": "ChatRequestQuery",
303
+ }
304
+
305
+ # Pydantic models provide model_json_schema
306
+ if schema is not None and hasattr(schema, "model_json_schema"):
307
+ return schema.model_json_schema()
308
+
309
+ return None
310
+
311
+ def _build_final_json(functions_to_include: Mapping[str, FunctionBase],
312
+ include_schemas: bool = False) -> dict[str, Any]:
313
+ tools = []
314
+ for name, fn in functions_to_include.items():
315
+ list_entry: dict[str, Any] = {
316
+ "name": name, "description": get_function_description(fn), "is_workflow": hasattr(fn, "run")
317
+ }
318
+ if include_schemas:
319
+ list_entry["schema"] = _build_schema_info(fn)
320
+ tools.append(list_entry)
321
+
322
+ return {
323
+ "count": len(tools),
324
+ "tools": tools,
325
+ "server_name": mcp.name,
326
+ }
327
+
328
+ if names:
329
+ # Return selected tools
330
+ try:
331
+ functions_to_include = {n: functions[n] for n in names}
332
+ except KeyError as e:
333
+ raise HTTPException(status_code=404, detail=f"Tool \"{e.args[0]}\" not found.") from e
334
+ else:
335
+ functions_to_include = functions
336
+
337
+ # Default for listing all: detail defaults to False unless explicitly set true
338
+ return JSONResponse(
339
+ _build_final_json(functions_to_include, _parse_detail_param(detail_raw, has_names=bool(names))))
340
+
341
+ # Memory profiling endpoint (read-only)
342
+ @mcp.custom_route("/debug/memory/stats", methods=["GET"])
343
+ async def get_memory_stats(_request: Request):
344
+ """Get current memory profiling statistics."""
345
+ from starlette.responses import JSONResponse
346
+
347
+ stats = self.memory_profiler.get_stats()
348
+ return JSONResponse(stats)
349
+
350
+
351
+ class MCPFrontEndPluginWorker(MCPFrontEndPluginWorkerBase):
352
+ """Default MCP server worker implementation.
353
+
354
+ Inherit from this class to create custom MCP workers that extend or modify
355
+ server behavior. Override create_mcp_server() to use a different server type,
356
+ and override add_routes() to add custom functionality.
357
+
358
+ Example:
359
+ class CustomWorker(MCPFrontEndPluginWorker):
360
+ async def create_mcp_server(self):
361
+ # Return custom MCP server instance
362
+ return MyCustomFastMCP(...)
363
+
364
+ async def add_routes(self, mcp, builder):
365
+ # Get default routes
366
+ await super().add_routes(mcp, builder)
367
+ # Add custom features
368
+ self._add_my_custom_features(mcp)
369
+ """
370
+
371
+ async def create_mcp_server(self) -> FastMCP:
372
+ """Create default MCP server with optional authentication.
373
+
374
+ Returns:
375
+ FastMCP instance configured with settings from NAT config
376
+ """
377
+ # Handle auth if configured
378
+ auth_settings = None
379
+ token_verifier = None
380
+
381
+ if self.front_end_config.server_auth:
382
+ from pydantic import AnyHttpUrl
383
+
384
+ from mcp.server.auth.settings import AuthSettings
385
+
386
+ server_url = f"http://{self.front_end_config.host}:{self.front_end_config.port}"
387
+ auth_settings = AuthSettings(issuer_url=AnyHttpUrl(self.front_end_config.server_auth.issuer_url),
388
+ required_scopes=self.front_end_config.server_auth.scopes,
389
+ resource_server_url=AnyHttpUrl(server_url))
390
+
391
+ # Create token verifier
392
+ from nat.plugins.mcp.server.introspection_token_verifier import IntrospectionTokenVerifier
393
+
394
+ token_verifier = IntrospectionTokenVerifier(self.front_end_config.server_auth)
395
+
396
+ return FastMCP(name=self.front_end_config.name,
397
+ host=self.front_end_config.host,
398
+ port=self.front_end_config.port,
399
+ debug=self.front_end_config.debug,
400
+ auth=auth_settings,
401
+ token_verifier=token_verifier)
402
+
403
+ async def add_routes(self, mcp: FastMCP, builder: WorkflowBuilder):
404
+ """Add default routes to the MCP server.
405
+
406
+ Args:
407
+ mcp: The FastMCP server instance
408
+ builder: The workflow builder instance
409
+ """
410
+ # Use the default implementation from base class to add the tools to the MCP server
411
+ await self._default_add_routes(mcp, builder)
@@ -0,0 +1,72 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """OAuth 2.0 Token Introspection verifier implementation for MCP servers."""
16
+
17
+ import logging
18
+
19
+ from mcp.server.auth.provider import AccessToken
20
+ from mcp.server.auth.provider import TokenVerifier
21
+ from nat.authentication.credential_validator.bearer_token_validator import BearerTokenValidator
22
+ from nat.authentication.oauth2.oauth2_resource_server_config import OAuth2ResourceServerConfig
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ class IntrospectionTokenVerifier(TokenVerifier):
28
+ """Token verifier that delegates token verification to BearerTokenValidator."""
29
+
30
+ def __init__(self, config: OAuth2ResourceServerConfig):
31
+ """Create IntrospectionTokenVerifier from OAuth2ResourceServerConfig.
32
+
33
+ Args:
34
+ config: OAuth2ResourceServerConfig
35
+ """
36
+ issuer = config.issuer_url
37
+ scopes = config.scopes or []
38
+ audience = config.audience
39
+ jwks_uri = config.jwks_uri
40
+ introspection_endpoint = config.introspection_endpoint
41
+ discovery_url = config.discovery_url
42
+ client_id = config.client_id
43
+ client_secret = config.client_secret
44
+
45
+ self._bearer_token_validator = BearerTokenValidator(
46
+ issuer=issuer,
47
+ audience=audience,
48
+ scopes=scopes,
49
+ jwks_uri=jwks_uri,
50
+ introspection_endpoint=introspection_endpoint,
51
+ discovery_url=discovery_url,
52
+ client_id=client_id,
53
+ client_secret=client_secret,
54
+ )
55
+
56
+ async def verify_token(self, token: str) -> AccessToken | None:
57
+ """Verify token by delegating to BearerTokenValidator.
58
+
59
+ Args:
60
+ token: The Bearer token to verify
61
+
62
+ Returns:
63
+ AccessToken | None: AccessToken if valid, None if invalid
64
+ """
65
+ validation_result = await self._bearer_token_validator.verify(token)
66
+
67
+ if validation_result.active:
68
+ return AccessToken(token=token,
69
+ expires_at=validation_result.expires_at,
70
+ scopes=validation_result.scopes or [],
71
+ client_id=validation_result.client_id or "")
72
+ return None