nvidia-nat-mcp 1.3.0a20250910__py3-none-any.whl → 1.5.0a20260117__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 (42) hide show
  1. nat/meta/pypi.md +3 -3
  2. nat/plugins/mcp/__init__.py +1 -1
  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 +87 -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 +1094 -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 +2 -2
  20. nat/plugins/mcp/exceptions.py +1 -1
  21. nat/plugins/mcp/register.py +5 -4
  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 +415 -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 +290 -0
  30. nat/plugins/mcp/utils.py +228 -0
  31. {nvidia_nat_mcp-1.3.0a20250910.dist-info → nvidia_nat_mcp-1.5.0a20260117.dist-info}/METADATA +15 -6
  32. nvidia_nat_mcp-1.5.0a20260117.dist-info/RECORD +37 -0
  33. nvidia_nat_mcp-1.5.0a20260117.dist-info/entry_points.txt +9 -0
  34. nvidia_nat_mcp-1.5.0a20260117.dist-info/licenses/LICENSE-3rd-party.txt +5478 -0
  35. nvidia_nat_mcp-1.5.0a20260117.dist-info/licenses/LICENSE.md +201 -0
  36. nat/plugins/mcp/client_base.py +0 -406
  37. nat/plugins/mcp/client_impl.py +0 -229
  38. nat/plugins/mcp/tool.py +0 -133
  39. nvidia_nat_mcp-1.3.0a20250910.dist-info/RECORD +0 -13
  40. nvidia_nat_mcp-1.3.0a20250910.dist-info/entry_points.txt +0 -2
  41. {nvidia_nat_mcp-1.3.0a20250910.dist-info → nvidia_nat_mcp-1.5.0a20260117.dist-info}/WHEEL +0 -0
  42. {nvidia_nat_mcp-1.3.0a20250910.dist-info → nvidia_nat_mcp-1.5.0a20260117.dist-info}/top_level.txt +0 -0
@@ -1,229 +0,0 @@
1
- # SPDX-FileCopyrightText: Copyright (c) 2025, 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 typing import Literal
18
-
19
- from pydantic import BaseModel
20
- from pydantic import Field
21
- from pydantic import HttpUrl
22
- from pydantic import model_validator
23
-
24
- from nat.builder.builder import Builder
25
- from nat.builder.function_info import FunctionInfo
26
- from nat.cli.register_workflow import register_function
27
- from nat.data_models.function import FunctionBaseConfig
28
- from nat.experimental.decorators.experimental_warning_decorator import experimental
29
- from nat.plugins.mcp.client_base import MCPBaseClient
30
-
31
- logger = logging.getLogger(__name__)
32
-
33
-
34
- class MCPToolOverrideConfig(BaseModel):
35
- """
36
- Configuration for overriding tool properties when exposing from MCP server.
37
- """
38
- alias: str | None = Field(default=None, description="Override the tool name (function name in the workflow)")
39
- description: str | None = Field(default=None, description="Override the tool description")
40
-
41
-
42
- class MCPServerConfig(BaseModel):
43
- """
44
- Server connection details for MCP client.
45
- Supports stdio, sse, and streamable-http transports.
46
- streamable-http is the recommended default for HTTP-based connections.
47
- """
48
- transport: Literal["stdio", "sse", "streamable-http"] = Field(
49
- ..., description="Transport type to connect to the MCP server (stdio, sse, or streamable-http)")
50
- url: HttpUrl | None = Field(default=None,
51
- description="URL of the MCP server (for sse or streamable-http transport)")
52
- command: str | None = Field(default=None,
53
- description="Command to run for stdio transport (e.g. 'python' or 'docker')")
54
- args: list[str] | None = Field(default=None, description="Arguments for the stdio command")
55
- env: dict[str, str] | None = Field(default=None, description="Environment variables for the stdio process")
56
-
57
- @model_validator(mode="after")
58
- def validate_model(self):
59
- """Validate that stdio and SSE/Streamable HTTP properties are mutually exclusive."""
60
- if self.transport == "stdio":
61
- if self.url is not None:
62
- raise ValueError("url should not be set when using stdio transport")
63
- if not self.command:
64
- raise ValueError("command is required when using stdio transport")
65
- elif self.transport in ("sse", "streamable-http"):
66
- if self.command is not None or self.args is not None or self.env is not None:
67
- raise ValueError("command, args, and env should not be set when using sse or streamable-http transport")
68
- if not self.url:
69
- raise ValueError("url is required when using sse or streamable-http transport")
70
- return self
71
-
72
-
73
- class MCPClientConfig(FunctionBaseConfig, name="mcp_client"):
74
- """
75
- Configuration for connecting to an MCP server as a client and exposing selected tools.
76
- """
77
- server: MCPServerConfig = Field(..., description="Server connection details (transport, url/command, etc.)")
78
- tool_filter: dict[str, MCPToolOverrideConfig] | list[str] | None = Field(
79
- default=None,
80
- description="""Filter or map tools to expose from the server (list or dict).
81
- Can be:
82
- - A list of tool names to expose: ['tool1', 'tool2']
83
- - A dict mapping tool names to override configs:
84
- {'tool1': {'alias': 'new_name', 'description': 'New desc'}}
85
- {'tool2': {'description': 'Override description only'}} # alias defaults to 'tool2'
86
- """)
87
-
88
-
89
- class MCPSingleToolConfig(FunctionBaseConfig, name="mcp_single_tool"):
90
- """
91
- Configuration for wrapping a single tool from an MCP server as a NeMo Agent toolkit function.
92
- """
93
- client: MCPBaseClient = Field(..., description="MCP client to use for the tool")
94
- tool_name: str = Field(..., description="Name of the tool to use")
95
- tool_description: str | None = Field(default=None, description="Description of the tool")
96
-
97
- model_config = {"arbitrary_types_allowed": True}
98
-
99
-
100
- def _get_server_name_safe(client: MCPBaseClient) -> str:
101
- # Avoid leaking env secrets from stdio client in logs.
102
- if client.transport == "stdio":
103
- safe_server = f"stdio: {client.command}"
104
- else:
105
- safe_server = f"{client.transport}: {client.url}"
106
-
107
- return safe_server
108
-
109
-
110
- @register_function(config_type=MCPSingleToolConfig)
111
- async def mcp_single_tool(config: MCPSingleToolConfig, builder: Builder):
112
- """
113
- Wrap a single tool from an MCP server as a NeMo Agent toolkit function.
114
- """
115
- tool = await config.client.get_tool(config.tool_name)
116
- if config.tool_description:
117
- tool.set_description(description=config.tool_description)
118
- input_schema = tool.input_schema
119
-
120
- logger.info("Configured to use tool: %s from MCP server at %s", tool.name, _get_server_name_safe(config.client))
121
-
122
- def _convert_from_str(input_str: str) -> BaseModel:
123
- return input_schema.model_validate_json(input_str)
124
-
125
- @experimental(feature_name="mcp_client")
126
- async def _response_fn(tool_input: BaseModel | None = None, **kwargs) -> str:
127
- try:
128
- if tool_input:
129
- return await tool.acall(tool_input.model_dump())
130
- _ = input_schema.model_validate(kwargs)
131
- return await tool.acall(kwargs)
132
- except Exception as e:
133
- return str(e)
134
-
135
- fn = FunctionInfo.create(single_fn=_response_fn,
136
- description=tool.description,
137
- input_schema=input_schema,
138
- converters=[_convert_from_str])
139
- yield fn
140
-
141
-
142
- @register_function(MCPClientConfig)
143
- async def mcp_client_function_handler(config: MCPClientConfig, builder: Builder):
144
- """
145
- Connect to an MCP server, discover tools, and register them as functions in the workflow.
146
-
147
- Note:
148
- - Uses builder's exit stack to manage client lifecycle
149
- - Applies tool filters if provided
150
- """
151
- from nat.plugins.mcp.client_base import MCPSSEClient
152
- from nat.plugins.mcp.client_base import MCPStdioClient
153
- from nat.plugins.mcp.client_base import MCPStreamableHTTPClient
154
-
155
- # Build the appropriate client
156
- client_cls = {
157
- "stdio": lambda: MCPStdioClient(config.server.command, config.server.args, config.server.env),
158
- "sse": lambda: MCPSSEClient(str(config.server.url)),
159
- "streamable-http": lambda: MCPStreamableHTTPClient(str(config.server.url)),
160
- }.get(config.server.transport)
161
-
162
- if not client_cls:
163
- raise ValueError(f"Unsupported transport: {config.server.transport}")
164
-
165
- client = client_cls()
166
- logger.info("Configured to use MCP server at %s", _get_server_name_safe(client))
167
-
168
- # client aenter connects to the server and stores the client in the exit stack
169
- # so it's cleaned up when the workflow is done
170
- async with client:
171
- all_tools = await client.get_tools()
172
- tool_configs = mcp_filter_tools(all_tools, config.tool_filter)
173
-
174
- for tool_name, tool_cfg in tool_configs.items():
175
- await builder.add_function(
176
- tool_cfg["function_name"],
177
- MCPSingleToolConfig(
178
- client=client,
179
- tool_name=tool_name,
180
- tool_description=tool_cfg["description"],
181
- ))
182
-
183
- @experimental(feature_name="mcp_client")
184
- async def idle_fn(text: str) -> str:
185
- # This function is a placeholder and will be removed when function groups are used
186
- return f"MCP client connected: {text}"
187
-
188
- yield FunctionInfo.create(single_fn=idle_fn, description="MCP client")
189
-
190
-
191
- def mcp_filter_tools(all_tools: dict, tool_filter) -> dict[str, dict]:
192
- """
193
- Apply tool filtering and optional aliasing/description overrides.
194
-
195
- Returns:
196
- Dict[str, dict] where each value has:
197
- - function_name
198
- - description
199
- """
200
- if tool_filter is None:
201
- return {name: {"function_name": name, "description": tool.description} for name, tool in all_tools.items()}
202
-
203
- if isinstance(tool_filter, list):
204
- return {
205
- name: {
206
- "function_name": name, "description": all_tools[name].description
207
- }
208
- for name in tool_filter if name in all_tools
209
- }
210
-
211
- if isinstance(tool_filter, dict):
212
- result = {}
213
- for name, override in tool_filter.items():
214
- tool = all_tools.get(name)
215
- if not tool:
216
- logger.warning("Tool '%s' specified in tool_filter not found in MCP server", name)
217
- continue
218
-
219
- if isinstance(override, MCPToolOverrideConfig):
220
- result[name] = {
221
- "function_name": override.alias or name, "description": override.description or tool.description
222
- }
223
- else:
224
- logger.warning("Unsupported override type for '%s': %s", name, type(override))
225
- result[name] = {"function_name": name, "description": tool.description}
226
- return result
227
-
228
- # Fallback for unsupported tool_filter types
229
- raise ValueError(f"Unsupported tool_filter type: {type(tool_filter)}")
nat/plugins/mcp/tool.py DELETED
@@ -1,133 +0,0 @@
1
- # SPDX-FileCopyrightText: Copyright (c) 2025, 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 typing import Literal
18
-
19
- from pydantic import BaseModel
20
- from pydantic import Field
21
- from pydantic import HttpUrl
22
- from pydantic import model_validator
23
-
24
- from nat.builder.builder import Builder
25
- from nat.builder.function_info import FunctionInfo
26
- from nat.cli.register_workflow import register_function
27
- from nat.data_models.function import FunctionBaseConfig
28
-
29
- logger = logging.getLogger(__name__)
30
-
31
-
32
- class MCPToolConfig(FunctionBaseConfig, name="mcp_tool_wrapper"):
33
- """
34
- Function which connects to a Model Context Protocol (MCP) server and wraps the selected tool as a NeMo Agent toolkit
35
- function.
36
- """
37
- # Add your custom configuration parameters here
38
- url: HttpUrl | None = Field(default=None,
39
- description="The URL of the MCP server (for streamable-http or sse modes)")
40
- mcp_tool_name: str = Field(description="The name of the tool served by the MCP Server that you want to use")
41
- transport: Literal["sse", "stdio", "streamable-http"] = Field(
42
- default="streamable-http",
43
- description="The type of transport to use (default: streamable-http, backwards compatible with sse)")
44
- command: str | None = Field(default=None,
45
- description="The command to run for stdio mode (e.g. 'docker' or 'python')")
46
- args: list[str] | None = Field(default=None, description="Additional arguments for the stdio command")
47
- env: dict[str, str] | None = Field(default=None, description="Environment variables to set for the stdio process")
48
- description: str | None = Field(default=None,
49
- description="""
50
- Description for the tool that will override the description provided by the MCP server. Should only be used if
51
- the description provided by the server is poor or nonexistent
52
- """)
53
- return_exception: bool = Field(default=True,
54
- description="""
55
- If true, the tool will return the exception message if the tool call fails.
56
- If false, raise the exception.
57
- """)
58
-
59
- @model_validator(mode="after")
60
- def validate_model(self):
61
- """Validate that stdio and SSE/Streamable HTTP properties are mutually exclusive."""
62
- if self.transport == 'stdio':
63
- if self.url is not None:
64
- raise ValueError("url should not be set when using stdio client type")
65
- if not self.command:
66
- raise ValueError("command is required when using stdio client type")
67
- elif self.transport in ['streamable-http', 'sse']:
68
- if self.command is not None or self.args is not None or self.env is not None:
69
- raise ValueError(
70
- "command, args, and env should not be set when using streamable-http or sse client type")
71
- if not self.url:
72
- raise ValueError("url is required when using streamable-http or sse client type")
73
- return self
74
-
75
-
76
- @register_function(config_type=MCPToolConfig)
77
- async def mcp_tool(config: MCPToolConfig, builder: Builder):
78
- """
79
- Generate a NeMo Agent Toolkit Function that wraps a tool provided by the MCP server.
80
- """
81
-
82
- from nat.plugins.mcp.client_base import MCPSSEClient
83
- from nat.plugins.mcp.client_base import MCPStdioClient
84
- from nat.plugins.mcp.client_base import MCPStreamableHTTPClient
85
- from nat.plugins.mcp.client_base import MCPToolClient
86
-
87
- # Initialize the client
88
- if config.transport == 'stdio':
89
- client = MCPStdioClient(command=config.command, args=config.args, env=config.env)
90
- elif config.transport == 'streamable-http':
91
- client = MCPStreamableHTTPClient(url=str(config.url))
92
- elif config.transport == 'sse':
93
- client = MCPSSEClient(url=str(config.url))
94
- else:
95
- raise ValueError(f"Invalid transport type: {config.transport}")
96
-
97
- async with client:
98
- # If the tool is found create a MCPToolClient object and set the description if provided
99
- tool: MCPToolClient = await client.get_tool(config.mcp_tool_name)
100
- if config.description:
101
- tool.set_description(description=config.description)
102
-
103
- logger.info("Configured to use tool: %s from MCP server at %s", tool.name, client.server_name)
104
-
105
- def _convert_from_str(input_str: str) -> tool.input_schema:
106
- return tool.input_schema.model_validate_json(input_str)
107
-
108
- async def _response_fn(tool_input: BaseModel | None = None, **kwargs) -> str:
109
- # Run the tool, catching any errors and sending to agent for correction
110
- try:
111
- if tool_input:
112
- args = tool_input.model_dump()
113
- return await tool.acall(args)
114
-
115
- _ = tool.input_schema.model_validate(kwargs)
116
- return await tool.acall(kwargs)
117
- except Exception as e:
118
- if config.return_exception:
119
- if tool_input:
120
- logger.warning("Error calling tool %s with serialized input: %s",
121
- tool.name,
122
- tool_input.model_dump(),
123
- exc_info=True)
124
- else:
125
- logger.warning("Error calling tool %s with input: %s", tool.name, kwargs, exc_info=True)
126
- return str(e)
127
- # If the tool call fails, raise the exception.
128
- raise
129
-
130
- yield FunctionInfo.create(single_fn=_response_fn,
131
- description=tool.description,
132
- input_schema=tool.input_schema,
133
- converters=[_convert_from_str])
@@ -1,13 +0,0 @@
1
- nat/meta/pypi.md,sha256=GyV4DI1d9ThgEhnYTQ0vh40Q9hPC8jN-goLnRiFDmZ8,1498
2
- nat/plugins/mcp/__init__.py,sha256=GUJrgGtpvyMUCjUBvR3faAdv-tZzbU9W-izgx9aMEQg,680
3
- nat/plugins/mcp/client_base.py,sha256=4vFOBFoSpLpkq7r2iXDMbi6tDj02JBidZo5RiBR167w,13424
4
- nat/plugins/mcp/client_impl.py,sha256=6rG3LcCX4TFsiST5O0_C8eOpY9LdnoSMarfAWeR76XA,9724
5
- nat/plugins/mcp/exception_handler.py,sha256=JdPdZG1NgWpdRnIz7JTGHiJASS5wot9nJiD3SRWV4Kw,7649
6
- nat/plugins/mcp/exceptions.py,sha256=EGVOnYlui8xufm8dhJyPL1SUqBLnCGOTvRoeyNcmcWE,5980
7
- nat/plugins/mcp/register.py,sha256=HOT2Wl2isGuyFc7BUTi58-BbjI5-EtZMZo7stsv5pN4,831
8
- nat/plugins/mcp/tool.py,sha256=MSRnnr1a6OjfqVkt2SYPkfLi9lU0JqovIZuTOL1cgHQ,6378
9
- nvidia_nat_mcp-1.3.0a20250910.dist-info/METADATA,sha256=nZU24irAcgdYvg6UOdvSSgh1NHt8-iShmC-7O_sJGpQ,1997
10
- nvidia_nat_mcp-1.3.0a20250910.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
11
- nvidia_nat_mcp-1.3.0a20250910.dist-info/entry_points.txt,sha256=x7dQTqek3GEdU-y9GslnygxMu0BSbEeUiOOMa2gvaaQ,52
12
- nvidia_nat_mcp-1.3.0a20250910.dist-info/top_level.txt,sha256=8-CJ2cP6-f0ZReXe5Hzqp-5pvzzHz-5Ds5H2bGqh1-U,4
13
- nvidia_nat_mcp-1.3.0a20250910.dist-info/RECORD,,
@@ -1,2 +0,0 @@
1
- [nat.components]
2
- nat_mcp = nat.plugins.mcp.register