nvidia-nat-mcp 1.4.0a20251014__py3-none-any.whl → 1.5.0a20260115__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 (40) hide show
  1. nat/meta/pypi.md +1 -1
  2. nat/plugins/mcp/__init__.py +1 -1
  3. nat/plugins/mcp/auth/__init__.py +1 -1
  4. nat/plugins/mcp/auth/auth_flow_handler.py +65 -1
  5. nat/plugins/mcp/auth/auth_provider.py +3 -2
  6. nat/plugins/mcp/auth/auth_provider_config.py +5 -2
  7. nat/plugins/mcp/auth/register.py +9 -1
  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 +2 -2
  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_base.py → client/client_base.py} +18 -10
  17. nat/plugins/mcp/{client_config.py → client/client_config.py} +24 -9
  18. nat/plugins/mcp/{client_impl.py → client/client_impl.py} +253 -62
  19. nat/plugins/mcp/exception_handler.py +1 -1
  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 +153 -36
  31. {nvidia_nat_mcp-1.4.0a20251014.dist-info → nvidia_nat_mcp-1.5.0a20260115.dist-info}/METADATA +5 -5
  32. nvidia_nat_mcp-1.5.0a20260115.dist-info/RECORD +37 -0
  33. nvidia_nat_mcp-1.5.0a20260115.dist-info/entry_points.txt +9 -0
  34. nat/plugins/mcp/tool.py +0 -138
  35. nvidia_nat_mcp-1.4.0a20251014.dist-info/RECORD +0 -23
  36. nvidia_nat_mcp-1.4.0a20251014.dist-info/entry_points.txt +0 -3
  37. {nvidia_nat_mcp-1.4.0a20251014.dist-info → nvidia_nat_mcp-1.5.0a20260115.dist-info}/WHEEL +0 -0
  38. {nvidia_nat_mcp-1.4.0a20251014.dist-info → nvidia_nat_mcp-1.5.0a20260115.dist-info}/licenses/LICENSE-3rd-party.txt +0 -0
  39. {nvidia_nat_mcp-1.4.0a20251014.dist-info → nvidia_nat_mcp-1.5.0a20260115.dist-info}/licenses/LICENSE.md +0 -0
  40. {nvidia_nat_mcp-1.4.0a20251014.dist-info → nvidia_nat_mcp-1.5.0a20260115.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1094 @@
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 asyncio
17
+ import json
18
+ import logging
19
+ import time
20
+ from typing import Any
21
+ from typing import Literal
22
+ from typing import cast
23
+
24
+ import click
25
+ from pydantic import BaseModel
26
+
27
+ from nat.builder.function import FunctionGroup
28
+ from nat.cli.commands.start import start_command
29
+ from nat.plugins.mcp.client.client_config import MCPClientBaseConfig
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ @click.group(name=__name__, invoke_without_command=False, help="MCP-related commands.")
35
+ def mcp_command():
36
+ """
37
+ MCP-related commands.
38
+ """
39
+ return None
40
+
41
+
42
+ # nat mcp serve: reuses the start/mcp frontend command
43
+ mcp_command.add_command(start_command.get_command(None, "mcp"), name="serve") # type: ignore
44
+
45
+ # Suppress verbose logs from mcp.client.sse and httpx
46
+ logging.getLogger("mcp.client.sse").setLevel(logging.WARNING)
47
+ logging.getLogger("httpx").setLevel(logging.WARNING)
48
+
49
+ try:
50
+ from nat.plugins.mcp.exception_handler import format_mcp_error
51
+ from nat.plugins.mcp.exceptions import MCPError
52
+ except ImportError:
53
+ # Fallback for when MCP client package is not installed
54
+ MCPError = Exception
55
+
56
+ def format_mcp_error(error, include_traceback=False):
57
+ click.echo(f"Error: {error}", err=True)
58
+
59
+
60
+ def validate_transport_cli_args(transport: str, command: str | None, args: str | None, env: str | None) -> bool:
61
+ """
62
+ Validate transport and parameter combinations, returning False if invalid.
63
+
64
+ Args:
65
+ transport: The transport type ('sse', 'stdio', or 'streamable-http')
66
+ command: Command for stdio transport
67
+ args: Arguments for stdio transport
68
+ env: Environment variables for stdio transport
69
+
70
+ Returns:
71
+ bool: True if valid, False if invalid (error message already displayed)
72
+ """
73
+ if transport == 'stdio':
74
+ if not command:
75
+ click.echo("--command is required when using stdio client type", err=True)
76
+ return False
77
+ elif transport in ['sse', 'streamable-http']:
78
+ if command or args or env:
79
+ click.echo("--command, --args, and --env are not allowed when using sse or streamable-http client type",
80
+ err=True)
81
+ return False
82
+ return True
83
+
84
+
85
+ class MCPPingResult(BaseModel):
86
+ """Result of an MCP server ping request.
87
+
88
+ Attributes:
89
+ url (str): The MCP server URL that was pinged
90
+ status (str): Health status - 'healthy', 'unhealthy', or 'unknown'
91
+ response_time_ms (float | None): Response time in milliseconds, None if request failed completely
92
+ error (str | None): Error message if the ping failed, None if successful
93
+ """
94
+ url: str
95
+ status: str
96
+ response_time_ms: float | None
97
+ error: str | None
98
+
99
+
100
+ def format_tool(tool: Any) -> dict[str, str | None]:
101
+ """Format an MCP tool into a dictionary for display.
102
+
103
+ Extracts name, description, and input schema from various MCP tool object types
104
+ and normalizes them into a consistent dictionary format for CLI display.
105
+
106
+ Args:
107
+ tool (Any): MCPToolClient or raw MCP Tool object (uses Any due to different types)
108
+
109
+ Returns:
110
+ dict[str, str | None]: Dictionary with name, description, and input_schema as keys
111
+ """
112
+ name = getattr(tool, 'name', None)
113
+ description = getattr(tool, 'description', '')
114
+ input_schema = getattr(tool, 'input_schema', None) or getattr(tool, 'inputSchema', None)
115
+
116
+ # Normalize schema to JSON string
117
+ if input_schema is None:
118
+ return {
119
+ "name": name,
120
+ "description": description,
121
+ "input_schema": None,
122
+ }
123
+ elif hasattr(input_schema, "schema_json"):
124
+ schema_str = input_schema.schema_json(indent=2)
125
+ elif hasattr(input_schema, "model_json_schema"):
126
+ schema_str = json.dumps(input_schema.model_json_schema(), indent=2)
127
+ elif isinstance(input_schema, dict):
128
+ schema_str = json.dumps(input_schema, indent=2)
129
+ else:
130
+ # Final fallback: attempt to dump stringified version wrapped as JSON string
131
+ schema_str = json.dumps({"raw": str(input_schema)}, indent=2)
132
+
133
+ return {
134
+ "name": name,
135
+ "description": description,
136
+ "input_schema": schema_str,
137
+ }
138
+
139
+
140
+ def print_tool(tool_dict: dict[str, str | None], detail: bool = False) -> None:
141
+ """Print a formatted tool to the console with optional detailed information.
142
+
143
+ Outputs tool information in a user-friendly format to stdout. When detail=True
144
+ or when description/schema are available, shows full information with separator.
145
+
146
+ Args:
147
+ tool_dict (dict[str, str | None]): Dictionary containing tool information with name, description, and
148
+ input_schema as keys
149
+ detail (bool, optional): Whether to force detailed output. Defaults to False.
150
+ """
151
+ click.echo(f"Tool: {tool_dict.get('name', 'Unknown')}")
152
+ if detail or tool_dict.get('input_schema') or tool_dict.get('description'):
153
+ click.echo(f"Description: {tool_dict.get('description', 'No description available')}")
154
+ if tool_dict.get("input_schema"):
155
+ click.echo("Input Schema:")
156
+ click.echo(tool_dict.get("input_schema"))
157
+ else:
158
+ click.echo("Input Schema: None")
159
+ click.echo("-" * 60)
160
+
161
+
162
+ def _set_auth_defaults(auth: bool,
163
+ url: str | None,
164
+ auth_redirect_uri: str | None,
165
+ auth_user_id: str | None,
166
+ auth_scopes: str | None) -> tuple[str | None, str | None, list[str] | None]:
167
+ """Set default auth values when --auth flag is used.
168
+
169
+ Args:
170
+ auth: Whether --auth flag was used
171
+ url: MCP server URL
172
+ auth_redirect_uri: OAuth2 redirect URI
173
+ auth_user_id: User ID for authentication
174
+ auth_scopes: OAuth2 scopes (comma-separated string)
175
+
176
+ Returns:
177
+ Tuple of (auth_redirect_uri, auth_user_id, auth_scopes_list) with defaults applied
178
+ """
179
+ if auth:
180
+ auth_redirect_uri = auth_redirect_uri or "http://localhost:8000/auth/redirect"
181
+ auth_user_id = auth_user_id or url
182
+ auth_scopes = auth_scopes or ""
183
+
184
+ # Convert comma-separated string to list, stripping whitespace
185
+ auth_scopes_list = [scope.strip() for scope in auth_scopes.split(',')] if auth_scopes else None
186
+
187
+ return auth_redirect_uri, auth_user_id, auth_scopes_list
188
+
189
+
190
+ async def _create_mcp_client_config(
191
+ builder,
192
+ server_cfg,
193
+ url: str | None,
194
+ transport: str,
195
+ auth_redirect_uri: str | None,
196
+ auth_user_id: str | None,
197
+ auth_scopes: list[str] | None,
198
+ per_user: bool = False,
199
+ ) -> tuple[str, MCPClientBaseConfig]:
200
+ from nat.plugins.mcp.client.client_config import MCPClientConfig
201
+ from nat.plugins.mcp.client.client_config import PerUserMCPClientConfig
202
+
203
+ if url and transport == "streamable-http" and auth_redirect_uri:
204
+ try:
205
+ from nat.plugins.mcp.auth.auth_provider_config import MCPOAuth2ProviderConfig
206
+ auth_config = MCPOAuth2ProviderConfig(
207
+ server_url=url,
208
+ redirect_uri=auth_redirect_uri,
209
+ default_user_id=auth_user_id or url,
210
+ scopes=auth_scopes or [],
211
+ )
212
+ auth_provider_name = "mcp_oauth2_cli"
213
+ await builder.add_auth_provider(auth_provider_name, auth_config)
214
+ server_cfg.auth_provider = auth_provider_name
215
+ except ImportError:
216
+ click.echo(
217
+ "[WARNING] MCP OAuth2 authentication requires nvidia-nat-mcp package.",
218
+ err=True,
219
+ )
220
+ if per_user:
221
+ group_cfg = PerUserMCPClientConfig(server=server_cfg)
222
+ group_name = "per_user_mcp_client"
223
+ else:
224
+ group_cfg = MCPClientConfig(server=server_cfg)
225
+ group_name = "mcp_client"
226
+
227
+ return group_name, group_cfg
228
+
229
+
230
+ async def _create_bearer_token_auth_config(
231
+ builder,
232
+ server_cfg,
233
+ bearer_token: str | None,
234
+ bearer_token_env: str | None,
235
+ ):
236
+ """Create bearer token auth configuration for CLI usage."""
237
+ import os
238
+
239
+ from pydantic import SecretStr
240
+
241
+ from nat.authentication.api_key.api_key_auth_provider_config import APIKeyAuthProviderConfig
242
+ from nat.data_models.authentication import HeaderAuthScheme
243
+
244
+ # Get token from env var or direct input
245
+ if bearer_token_env:
246
+ token_value = os.getenv(bearer_token_env)
247
+ if not token_value:
248
+ raise ValueError(f"Environment variable '{bearer_token_env}' not found or empty")
249
+ elif bearer_token:
250
+ token_value = bearer_token
251
+ else:
252
+ raise ValueError("No bearer token provided")
253
+
254
+ # Create API key auth config with Bearer scheme
255
+ auth_config = APIKeyAuthProviderConfig(
256
+ raw_key=SecretStr(token_value),
257
+ auth_scheme=HeaderAuthScheme.BEARER,
258
+ )
259
+
260
+ auth_provider_name = "bearer_token_cli"
261
+ await builder.add_auth_provider(auth_provider_name, auth_config)
262
+ server_cfg.auth_provider = auth_provider_name
263
+
264
+
265
+ async def list_tools_via_function_group(
266
+ command: str | None,
267
+ url: str | None,
268
+ tool_name: str | None = None,
269
+ transport: str = 'sse',
270
+ args: list[str] | None = None,
271
+ env: dict[str, str] | None = None,
272
+ auth_redirect_uri: str | None = None,
273
+ auth_user_id: str | None = None,
274
+ auth_scopes: list[str] | None = None,
275
+ per_user: bool = False,
276
+ user_id: str | None = None,
277
+ ) -> list[dict[str, str | None]]:
278
+ """List tools by constructing the mcp_client function group and introspecting functions.
279
+
280
+ Mirrors the behavior of list_mcp.py but routes through the registered function group to ensure
281
+ parity with workflow configuration.
282
+ """
283
+ try:
284
+ # Ensure the registration side-effects are loaded
285
+ from nat.builder.workflow_builder import WorkflowBuilder
286
+ from nat.plugins.mcp.client.client_config import MCPServerConfig
287
+ except ImportError:
288
+ click.echo(
289
+ "MCP client functionality requires nvidia-nat-mcp package. Install with: uv pip install nvidia-nat-mcp",
290
+ err=True)
291
+ return []
292
+
293
+ if args is None:
294
+ args = []
295
+
296
+ # Build server config according to transport
297
+ server_cfg = MCPServerConfig(
298
+ transport=cast(Literal["stdio", "sse", "streamable-http"], transport),
299
+ url=cast(Any, url) if transport in ('sse', 'streamable-http') else None,
300
+ command=command if transport == 'stdio' else None,
301
+ args=args if transport == 'stdio' else None,
302
+ env=env if transport == 'stdio' else None,
303
+ )
304
+
305
+ tools: list[dict[str, str | None]] = []
306
+
307
+ async with WorkflowBuilder() as builder: # type: ignore
308
+ # Set user_id in context for per-user workflows
309
+ if per_user:
310
+ from nat.builder.context import ContextState
311
+ context_state = ContextState()
312
+ context_state.user_id.set(user_id)
313
+ logger.debug(f"Set user_id in context: {user_id}")
314
+
315
+ # Add auth provider if url is provided and auth_redirect_uri is given (only for streamable-http)
316
+ group_name, group_cfg = await _create_mcp_client_config(builder,
317
+ server_cfg,
318
+ url,
319
+ transport,
320
+ auth_redirect_uri,
321
+ auth_user_id,
322
+ auth_scopes,
323
+ per_user)
324
+ group = await builder.add_function_group(group_name, group_cfg)
325
+
326
+ # Access functions exposed by the group
327
+ fns = await group.get_accessible_functions()
328
+
329
+ def to_tool_entry(full_name: str, fn_obj) -> dict[str, str | None]:
330
+ # full_name like "mcp_client__<tool>"
331
+ sep = FunctionGroup.SEPARATOR
332
+ name = full_name.split(sep, 1)[1] if sep in full_name else full_name
333
+ schema = getattr(fn_obj, 'input_schema', None)
334
+ if schema is None:
335
+ schema_str = None
336
+ elif hasattr(schema, "schema_json"):
337
+ schema_str = schema.schema_json(indent=2)
338
+ elif hasattr(schema, "model_json_schema"):
339
+ try:
340
+ schema_str = json.dumps(schema.model_json_schema(), indent=2)
341
+ except Exception:
342
+ schema_str = None
343
+ else:
344
+ schema_str = None
345
+ return {"name": name, "description": getattr(fn_obj, 'description', ''), "input_schema": schema_str}
346
+
347
+ if tool_name:
348
+ full = f"{group_name}{FunctionGroup.SEPARATOR}{tool_name}"
349
+ fn = fns.get(full)
350
+ if fn is not None:
351
+ tools.append(to_tool_entry(full, fn))
352
+ else:
353
+ logger.debug(f"Tool '{tool_name}' not found. Available: {list(fns.keys())}")
354
+ else:
355
+ for full, fn in fns.items():
356
+ tools.append(to_tool_entry(full, fn))
357
+
358
+ return tools
359
+
360
+
361
+ async def list_tools_direct(command, url, tool_name=None, transport='sse', args=None, env=None):
362
+ """List MCP tools using direct MCP protocol with structured exception handling.
363
+
364
+ Bypasses MCPBuilder and uses raw MCP ClientSession and SSE client directly.
365
+ Converts raw exceptions to structured MCPErrors for consistent user experience.
366
+ Used when --direct flag is specified in CLI.
367
+
368
+ Args:
369
+ url (str): MCP server URL to connect to
370
+ tool_name (str | None, optional): Specific tool name to retrieve.
371
+ If None, retrieves all available tools. Defaults to None.
372
+
373
+ Returns:
374
+ list[dict[str, str | None]]: List of formatted tool dictionaries, each containing name, description, and
375
+ input_schema as keys
376
+
377
+ Note:
378
+ This function handles ExceptionGroup by extracting the most relevant exception
379
+ and converting it to MCPError for consistent error reporting.
380
+ """
381
+ if args is None:
382
+ args = []
383
+ from mcp import ClientSession
384
+ from mcp.client.sse import sse_client
385
+ from mcp.client.stdio import StdioServerParameters
386
+ from mcp.client.stdio import stdio_client
387
+ from mcp.client.streamable_http import streamablehttp_client
388
+
389
+ try:
390
+ if transport == 'stdio':
391
+
392
+ def get_stdio_client():
393
+ return stdio_client(server=StdioServerParameters(command=command, args=args, env=env))
394
+
395
+ client = get_stdio_client
396
+ elif transport == 'streamable-http':
397
+
398
+ def get_streamable_http_client():
399
+ return streamablehttp_client(url=url)
400
+
401
+ client = get_streamable_http_client
402
+ else:
403
+
404
+ def get_sse_client():
405
+ return sse_client(url=url)
406
+
407
+ client = get_sse_client
408
+
409
+ async with client() as ctx:
410
+ read, write = (ctx[0], ctx[1]) if isinstance(ctx, tuple) else ctx
411
+ async with ClientSession(read, write) as session:
412
+ await session.initialize()
413
+ response = await session.list_tools()
414
+
415
+ tools = []
416
+ for tool in response.tools:
417
+ if tool_name:
418
+ if tool.name == tool_name:
419
+ tools.append(format_tool(tool))
420
+ else:
421
+ tools.append(format_tool(tool))
422
+
423
+ if tool_name and not tools:
424
+ click.echo(f"[INFO] Tool '{tool_name}' not found.")
425
+ return tools
426
+ except Exception as e:
427
+ # Convert raw exceptions to structured MCPError for consistency
428
+ try:
429
+ from nat.plugins.mcp.exception_handler import convert_to_mcp_error
430
+ from nat.plugins.mcp.exception_handler import extract_primary_exception
431
+ except ImportError:
432
+ # Fallback when MCP client package is not installed
433
+ def convert_to_mcp_error(exception, url):
434
+ return Exception(f"Error connecting to {url}: {exception}")
435
+
436
+ def extract_primary_exception(exceptions):
437
+ return exceptions[0] if exceptions else Exception("Unknown error")
438
+
439
+ if isinstance(e, ExceptionGroup):
440
+ primary_exception = extract_primary_exception(list(e.exceptions))
441
+ mcp_error = convert_to_mcp_error(primary_exception, url)
442
+ else:
443
+ mcp_error = convert_to_mcp_error(e, url)
444
+
445
+ format_mcp_error(mcp_error, include_traceback=False)
446
+ return []
447
+
448
+
449
+ async def ping_mcp_server(url: str,
450
+ timeout: int,
451
+ transport: str = 'streamable-http',
452
+ command: str | None = None,
453
+ args: list[str] | None = None,
454
+ env: dict[str, str] | None = None,
455
+ auth_redirect_uri: str | None = None,
456
+ auth_user_id: str | None = None,
457
+ auth_scopes: list[str] | None = None) -> MCPPingResult:
458
+ """Ping an MCP server to check if it's responsive.
459
+
460
+ Args:
461
+ url (str): MCP server URL to ping
462
+ timeout (int): Timeout in seconds for the ping request
463
+
464
+ Returns:
465
+ MCPPingResult: Structured result with status, response_time, and any error info
466
+ """
467
+ from mcp.client.session import ClientSession
468
+ from mcp.client.sse import sse_client
469
+ from mcp.client.stdio import StdioServerParameters
470
+ from mcp.client.stdio import stdio_client
471
+ from mcp.client.streamable_http import streamablehttp_client
472
+
473
+ async def _ping_operation():
474
+ # Select transport
475
+ if transport == 'stdio':
476
+ stdio_args_local: list[str] = args or []
477
+ if not command:
478
+ raise RuntimeError("--command is required for stdio transport")
479
+ client_ctx = stdio_client(server=StdioServerParameters(command=command, args=stdio_args_local, env=env))
480
+ elif transport == 'sse':
481
+ client_ctx = sse_client(url)
482
+ else: # streamable-http
483
+ client_ctx = streamablehttp_client(url=url)
484
+
485
+ async with client_ctx as ctx:
486
+ read, write = (ctx[0], ctx[1]) if isinstance(ctx, tuple) else ctx
487
+ async with ClientSession(read, write) as session:
488
+ await session.initialize()
489
+
490
+ start_time = time.time()
491
+ await session.send_ping()
492
+ end_time = time.time()
493
+ response_time_ms = round((end_time - start_time) * 1000, 2)
494
+
495
+ return MCPPingResult(url=url, status="healthy", response_time_ms=response_time_ms, error=None)
496
+
497
+ try:
498
+ # Apply timeout to the entire ping operation
499
+ return await asyncio.wait_for(_ping_operation(), timeout=timeout)
500
+
501
+ except TimeoutError:
502
+ return MCPPingResult(url=url,
503
+ status="unhealthy",
504
+ response_time_ms=None,
505
+ error=f"Timeout after {timeout} seconds")
506
+
507
+ except Exception as e:
508
+ return MCPPingResult(url=url, status="unhealthy", response_time_ms=None, error=str(e))
509
+
510
+
511
+ @mcp_command.group(name="client", invoke_without_command=False, help="MCP client commands.")
512
+ def mcp_client_command():
513
+ """
514
+ MCP client commands.
515
+ """
516
+ try:
517
+ from nat.runtime.loader import PluginTypes
518
+ from nat.runtime.loader import discover_and_register_plugins
519
+ discover_and_register_plugins(PluginTypes.CONFIG_OBJECT)
520
+ except ImportError:
521
+ click.echo("[WARNING] MCP client functionality requires nvidia-nat-mcp package.", err=True)
522
+ pass
523
+
524
+
525
+ @mcp_client_command.group(name="tool", invoke_without_command=False, help="Inspect and call MCP tools.")
526
+ def mcp_client_tool_group():
527
+ """
528
+ MCP client tool commands.
529
+ """
530
+ return None
531
+
532
+
533
+ @mcp_client_tool_group.command(name="list", help="List tool names (default), or show details with --detail or --tool.")
534
+ @click.option('--direct', is_flag=True, help='Bypass MCPBuilder and use direct MCP protocol')
535
+ @click.option(
536
+ '--url',
537
+ default='http://localhost:9901/mcp',
538
+ show_default=True,
539
+ help='MCP server URL (e.g. http://localhost:8080/mcp for streamable-http, http://localhost:8080/sse for sse)')
540
+ @click.option('--transport',
541
+ type=click.Choice(['sse', 'stdio', 'streamable-http']),
542
+ default='streamable-http',
543
+ show_default=True,
544
+ help='Type of client to use (default: streamable-http, backwards compatible with sse)')
545
+ @click.option('--command', help='For stdio: The command to run (e.g. mcp-server)')
546
+ @click.option('--args', help='For stdio: Additional arguments for the command (space-separated)')
547
+ @click.option('--env', help='For stdio: Environment variables in KEY=VALUE format (space-separated)')
548
+ @click.option('--tool', default=None, help='Get details for a specific tool by name')
549
+ @click.option('--detail', is_flag=True, help='Show full details for all tools')
550
+ @click.option('--json-output', is_flag=True, help='Output tool metadata in JSON format')
551
+ @click.option('--auth',
552
+ is_flag=True,
553
+ help='Enable OAuth2 authentication with default settings (streamable-http only, not with --direct)')
554
+ @click.option('--auth-redirect-uri',
555
+ help='OAuth2 redirect URI for authentication (streamable-http only, not with --direct)')
556
+ @click.option('--auth-user-id', help='User ID for authentication (streamable-http only, not with --direct)')
557
+ @click.option('--auth-scopes', help='OAuth2 scopes (comma-separated, streamable-http only, not with --direct)')
558
+ @click.option('--per-user', is_flag=True, help='Use per-user function group instead of shared function group')
559
+ @click.option('--user-id',
560
+ default='nat_mcp_cli_user_id',
561
+ help='User ID for per-user workflows (defaults to nat_mcp_cli_user_id)')
562
+ @click.pass_context
563
+ def mcp_client_tool_list(ctx,
564
+ direct,
565
+ url,
566
+ transport,
567
+ command,
568
+ args,
569
+ env,
570
+ tool,
571
+ detail,
572
+ json_output,
573
+ auth,
574
+ auth_redirect_uri,
575
+ auth_user_id,
576
+ auth_scopes,
577
+ per_user,
578
+ user_id):
579
+ """List MCP tool names (default) or show detailed tool information.
580
+
581
+ Use --detail for full output including descriptions and input schemas.
582
+ If --tool is provided, always shows full output for that specific tool.
583
+ Use --direct to bypass MCPBuilder and use raw MCP protocol.
584
+ Use --json-output to get structured JSON data instead of formatted text.
585
+ Use --auth to enable auth with default settings (streamable-http only, not with --direct).
586
+ Use --auth-redirect-uri to enable auth for protected MCP servers (streamable-http only, not with --direct).
587
+
588
+ Args:
589
+ ctx (click.Context): Click context object for command invocation
590
+ direct (bool): Whether to bypass MCPBuilder and use direct MCP protocol
591
+ url (str): MCP server URL to connect to (default: http://localhost:9901/mcp)
592
+ tool (str | None): Optional specific tool name to retrieve detailed info for
593
+ detail (bool): Whether to show full details (description + schema) for all tools
594
+ json_output (bool): Whether to output tool metadata in JSON format instead of text
595
+ auth (bool): Whether to enable OAuth2 authentication (streamable-http only, not with --direct)
596
+ auth_redirect_uri (str | None): redirect URI for auth (streamable-http only, not with --direct)
597
+ auth_user_id (str | None): User ID for authentication (streamable-http only, not with --direct)
598
+ auth_scopes (str | None): OAuth2 scopes (comma-separated, streamable-http only, not with --direct)
599
+
600
+ Examples:
601
+ nat mcp client tool list # List tool names only
602
+ nat mcp client tool list --detail # Show all tools with full details
603
+ nat mcp client tool list --tool my_tool # Show details for specific tool
604
+ nat mcp client tool list --json-output # Get JSON format output
605
+ nat mcp client tool list --direct --url http://... # Use direct protocol with custom URL (no auth)
606
+ nat mcp client tool list --url https://example.com/mcp/ --auth # With auth using defaults
607
+ nat mcp client tool list --url https://example.com/mcp/ --transport streamable-http \
608
+ --auth-redirect-uri http://localhost:8000/auth/redirect # With custom auth settings
609
+ nat mcp client tool list --url https://example.com/mcp/ --transport streamable-http \
610
+ --auth-redirect-uri http://localhost:8000/auth/redirect --auth-user-id myuser # With auth and user ID
611
+ """
612
+ if ctx.invoked_subcommand is not None:
613
+ return
614
+
615
+ if not validate_transport_cli_args(transport, command, args, env):
616
+ return
617
+
618
+ if transport in ['sse', 'streamable-http']:
619
+ if not url:
620
+ click.echo("[ERROR] --url is required when using sse or streamable-http client type", err=True)
621
+ return
622
+
623
+ # Set auth defaults if --auth flag is used
624
+ auth_redirect_uri, auth_user_id, auth_scopes_list = _set_auth_defaults(
625
+ auth, url, auth_redirect_uri, auth_user_id, auth_scopes
626
+ )
627
+
628
+ stdio_args = args.split() if args else []
629
+ stdio_env = dict(var.split('=', 1) for var in env.split()) if env else None
630
+
631
+ if direct:
632
+ tools = asyncio.run(
633
+ list_tools_direct(command, url, tool_name=tool, transport=transport, args=stdio_args, env=stdio_env))
634
+ else:
635
+ tools = asyncio.run(
636
+ list_tools_via_function_group(command,
637
+ url,
638
+ tool_name=tool,
639
+ transport=transport,
640
+ args=stdio_args,
641
+ env=stdio_env,
642
+ auth_redirect_uri=auth_redirect_uri,
643
+ auth_user_id=auth_user_id,
644
+ auth_scopes=auth_scopes_list,
645
+ per_user=per_user,
646
+ user_id=user_id))
647
+
648
+ if json_output:
649
+ click.echo(json.dumps(tools, indent=2))
650
+ elif tool:
651
+ for tool_dict in (tools or []):
652
+ print_tool(tool_dict, detail=True)
653
+ elif detail:
654
+ for tool_dict in (tools or []):
655
+ print_tool(tool_dict, detail=True)
656
+ else:
657
+ for tool_dict in (tools or []):
658
+ click.echo(tool_dict.get('name', 'Unknown tool'))
659
+
660
+
661
+ @mcp_client_command.command(name="ping", help="Ping an MCP server to check if it's responsive.")
662
+ @click.option(
663
+ '--url',
664
+ default='http://localhost:9901/mcp',
665
+ show_default=True,
666
+ help='MCP server URL (e.g. http://localhost:8080/mcp for streamable-http, http://localhost:8080/sse for sse)')
667
+ @click.option('--transport',
668
+ type=click.Choice(['sse', 'stdio', 'streamable-http']),
669
+ default='streamable-http',
670
+ show_default=True,
671
+ help='Type of client to use for ping')
672
+ @click.option('--command', help='For stdio: The command to run (e.g. mcp-server)')
673
+ @click.option('--args', help='For stdio: Additional arguments for the command (space-separated)')
674
+ @click.option('--env', help='For stdio: Environment variables in KEY=VALUE format (space-separated)')
675
+ @click.option('--timeout', default=60, show_default=True, help='Timeout in seconds for ping request')
676
+ @click.option('--json-output', is_flag=True, help='Output ping result in JSON format')
677
+ @click.option('--auth-redirect-uri',
678
+ help='OAuth2 redirect URI for authentication (streamable-http only, not with --direct)')
679
+ @click.option('--auth-user-id', help='User ID for authentication (streamable-http only, not with --direct)')
680
+ @click.option('--auth-scopes', help='OAuth2 scopes (comma-separated, streamable-http only, not with --direct)')
681
+ def mcp_client_ping(url: str,
682
+ transport: str,
683
+ command: str | None,
684
+ args: str | None,
685
+ env: str | None,
686
+ timeout: int,
687
+ json_output: bool,
688
+ auth_redirect_uri: str | None,
689
+ auth_user_id: str | None,
690
+ auth_scopes: str | None) -> None:
691
+ """Ping an MCP server to check if it's responsive.
692
+
693
+ This command sends a ping request to the MCP server and measures the response time.
694
+ It's useful for health checks and monitoring server availability.
695
+
696
+ Args:
697
+ url (str): MCP server URL to ping (default: http://localhost:9901/mcp)
698
+ timeout (int): Timeout in seconds for the ping request (default: 60)
699
+ json_output (bool): Whether to output the result in JSON format
700
+ auth_redirect_uri (str | None): redirect URI for auth (streamable-http only, not with --direct)
701
+ auth_user_id (str | None): User ID for auth (streamable-http only, not with --direct)
702
+ auth_scopes (str | None): OAuth2 scopes (comma-separated, streamable-http only, not with --direct)
703
+
704
+ Examples:
705
+ nat mcp client ping # Ping default server
706
+ nat mcp client ping --url http://custom-server:9901/mcp # Ping custom server
707
+ nat mcp client ping --timeout 10 # Use 10 second timeout
708
+ nat mcp client ping --json-output # Get JSON format output
709
+ nat mcp client ping --url https://example.com/mcp/ --transport streamable-http --auth # With auth
710
+ """
711
+ # Validate combinations similar to list command
712
+ if not validate_transport_cli_args(transport, command, args, env):
713
+ return
714
+
715
+ stdio_args = args.split() if args else []
716
+ stdio_env = dict(var.split('=', 1) for var in env.split()) if env else None
717
+
718
+ # Auth validation: if user_id or scopes provided, require redirect_uri
719
+ if (auth_user_id or auth_scopes) and not auth_redirect_uri:
720
+ click.echo("[ERROR] --auth-redirect-uri is required when using --auth-user-id or --auth-scopes", err=True)
721
+ return
722
+
723
+ # Parse auth scopes, stripping whitespace
724
+ auth_scopes_list = [scope.strip() for scope in auth_scopes.split(',')] if auth_scopes else None
725
+
726
+ result = asyncio.run(
727
+ ping_mcp_server(url,
728
+ timeout,
729
+ transport,
730
+ command,
731
+ stdio_args,
732
+ stdio_env,
733
+ auth_redirect_uri,
734
+ auth_user_id,
735
+ auth_scopes_list))
736
+
737
+ if json_output:
738
+ click.echo(result.model_dump_json(indent=2))
739
+ elif result.status == "healthy":
740
+ click.echo(f"Server at {result.url} is healthy (response time: {result.response_time_ms}ms)")
741
+ else:
742
+ click.echo(f"Server at {result.url} {result.status}: {result.error}")
743
+
744
+
745
+ async def call_tool_direct(command: str | None,
746
+ url: str | None,
747
+ tool_name: str,
748
+ transport: str,
749
+ args: list[str] | None,
750
+ env: dict[str, str] | None,
751
+ tool_args: dict[str, Any] | None) -> str:
752
+ """Call an MCP tool directly via the selected transport.
753
+
754
+ Bypasses the WorkflowBuilder and talks to the MCP server using the raw
755
+ protocol client for the given transport. Aggregates tool outputs into a
756
+ plain string suitable for terminal display. Converts transport/protocol
757
+ exceptions into a structured MCPError for consistency.
758
+
759
+ Args:
760
+ command (str | None): For ``stdio`` transport, the command to execute.
761
+ url (str | None): For ``sse`` or ``streamable-http`` transports, the server URL.
762
+ tool_name (str): Name of the tool to call.
763
+ transport (str): One of ``'stdio'``, ``'sse'``, or ``'streamable-http'``.
764
+ args (list[str] | None): For ``stdio`` transport, additional command arguments.
765
+ env (dict[str, str] | None): For ``stdio`` transport, environment variables.
766
+ tool_args (dict[str, Any] | None): JSON-serializable arguments passed to the tool.
767
+
768
+ Returns:
769
+ str: Concatenated textual output from the tool invocation.
770
+
771
+ Raises:
772
+ MCPError: If the connection, initialization, or tool call fails. When the
773
+ MCP client package is not installed, a generic ``Exception`` is raised
774
+ with an MCP-like error message.
775
+ RuntimeError: If required parameters for the chosen transport are missing
776
+ or if the tool returns an error response.
777
+ """
778
+ from mcp import ClientSession
779
+ from mcp.client.sse import sse_client
780
+ from mcp.client.stdio import StdioServerParameters
781
+ from mcp.client.stdio import stdio_client
782
+ from mcp.client.streamable_http import streamablehttp_client
783
+ from mcp.types import TextContent
784
+
785
+ try:
786
+ if transport == 'stdio':
787
+ if not command:
788
+ raise RuntimeError("--command is required for stdio transport")
789
+
790
+ def get_stdio_client():
791
+ return stdio_client(server=StdioServerParameters(command=command, args=args or [], env=env))
792
+
793
+ client = get_stdio_client
794
+ elif transport == 'streamable-http':
795
+
796
+ def get_streamable_http_client():
797
+ if not url:
798
+ raise RuntimeError("--url is required for streamable-http transport")
799
+ return streamablehttp_client(url=url)
800
+
801
+ client = get_streamable_http_client
802
+ else:
803
+
804
+ def get_sse_client():
805
+ if not url:
806
+ raise RuntimeError("--url is required for sse transport")
807
+ return sse_client(url=url)
808
+
809
+ client = get_sse_client
810
+
811
+ async with client() as ctx:
812
+ read, write = (ctx[0], ctx[1]) if isinstance(ctx, tuple) else ctx
813
+ async with ClientSession(read, write) as session:
814
+ await session.initialize()
815
+ result = await session.call_tool(tool_name, tool_args or {})
816
+
817
+ outputs: list[str] = []
818
+ for content in result.content:
819
+ if isinstance(content, TextContent):
820
+ outputs.append(content.text)
821
+ else:
822
+ outputs.append(str(content))
823
+
824
+ # If the result indicates an error, raise to surface in CLI
825
+ if getattr(result, "isError", False):
826
+ raise RuntimeError("\n".join(outputs) or f"Tool call '{tool_name}' returned an error")
827
+
828
+ return "\n".join(outputs)
829
+ except Exception as e:
830
+ # Convert raw exceptions to structured MCPError for consistency
831
+ try:
832
+ from nat.plugins.mcp.exception_handler import convert_to_mcp_error
833
+ from nat.plugins.mcp.exception_handler import extract_primary_exception
834
+ except ImportError:
835
+ # Fallback when MCP client package is not installed
836
+ def convert_to_mcp_error(exception: Exception, url: str):
837
+ return Exception(f"Error connecting to {url}: {exception}")
838
+
839
+ def extract_primary_exception(exceptions):
840
+ return exceptions[0] if exceptions else Exception("Unknown error")
841
+
842
+ endpoint = url or (f"stdio:{command}" if transport == 'stdio' else "unknown")
843
+ if isinstance(e, ExceptionGroup):
844
+ primary_exception = extract_primary_exception(list(e.exceptions))
845
+ mcp_error = convert_to_mcp_error(primary_exception, endpoint)
846
+ else:
847
+ mcp_error = convert_to_mcp_error(e, endpoint)
848
+ raise mcp_error from e
849
+
850
+
851
+ async def call_tool_and_print(command: str | None,
852
+ url: str | None,
853
+ tool_name: str,
854
+ transport: str,
855
+ args: list[str] | None,
856
+ env: dict[str, str] | None,
857
+ tool_args: dict[str, Any] | None,
858
+ direct: bool,
859
+ auth_redirect_uri: str | None = None,
860
+ auth_user_id: str | None = None,
861
+ auth_scopes: list[str] | None = None,
862
+ bearer_token: str | None = None,
863
+ bearer_token_env: str | None = None,
864
+ per_user: bool = False,
865
+ user_id: str | None = None) -> str:
866
+ """Call an MCP tool either directly or via the function group and return output.
867
+
868
+ When ``direct`` is True, uses the raw MCP protocol client (bypassing the
869
+ builder). Otherwise, constructs the ``mcp_client`` function group and
870
+ invokes the corresponding function, mirroring workflow configuration.
871
+
872
+ Args:
873
+ command (str | None): For ``stdio`` transport, the command to execute.
874
+ url (str | None): For ``sse`` or ``streamable-http`` transports, the server URL.
875
+ tool_name (str): Name of the tool to call.
876
+ transport (str): One of ``'stdio'``, ``'sse'``, or ``'streamable-http'``.
877
+ args (list[str] | None): For ``stdio`` transport, additional command arguments.
878
+ env (dict[str, str] | None): For ``stdio`` transport, environment variables.
879
+ tool_args (dict[str, Any] | None): JSON-serializable arguments passed to the tool.
880
+ direct (bool): If True, bypass WorkflowBuilder and use direct MCP client.
881
+
882
+ Returns:
883
+ str: Stringified tool output suitable for terminal display. May be an
884
+ empty string when the MCP client package is not installed and ``direct``
885
+ is False.
886
+
887
+ Raises:
888
+ RuntimeError: If the tool is not found when using the function group.
889
+ MCPError: Propagated from ``call_tool_direct`` when direct mode fails.
890
+ """
891
+ if direct:
892
+ return await call_tool_direct(command, url, tool_name, transport, args, env, tool_args)
893
+
894
+ try:
895
+ from nat.builder.workflow_builder import WorkflowBuilder
896
+ from nat.plugins.mcp.client.client_config import MCPClientConfig
897
+ from nat.plugins.mcp.client.client_config import MCPServerConfig
898
+ from nat.plugins.mcp.client.client_config import PerUserMCPClientConfig
899
+ except ImportError:
900
+ click.echo(
901
+ "MCP client functionality requires nvidia-nat-mcp package. Install with: uv pip install nvidia-nat-mcp",
902
+ err=True)
903
+ return ""
904
+
905
+ server_cfg = MCPServerConfig(
906
+ transport=cast(Literal["stdio", "sse", "streamable-http"], transport),
907
+ url=cast(Any, url) if transport in ('sse', 'streamable-http') else None,
908
+ command=command if transport == 'stdio' else None,
909
+ args=args if transport == 'stdio' else None,
910
+ env=env if transport == 'stdio' else None,
911
+ )
912
+
913
+ async with WorkflowBuilder() as builder: # type: ignore
914
+ # Set user_id in context for per-user workflows
915
+ if per_user:
916
+ from nat.builder.context import ContextState
917
+ context_state = ContextState()
918
+ context_state.user_id.set(user_id)
919
+ logger.debug(f"Set user_id in context: {user_id}")
920
+
921
+ if bearer_token or bearer_token_env:
922
+ # Use bearer token auth
923
+ try:
924
+ await _create_bearer_token_auth_config(builder, server_cfg, bearer_token, bearer_token_env)
925
+ if per_user:
926
+ group_cfg = PerUserMCPClientConfig(server=server_cfg)
927
+ group_name = "per_user_mcp_client"
928
+ else:
929
+ group_cfg = MCPClientConfig(server=server_cfg)
930
+ group_name = "mcp_client"
931
+ except Exception as e:
932
+ click.echo(f"[ERROR] Failed to configure bearer token authentication: {e}", err=True)
933
+ return ""
934
+ else:
935
+ group_name, group_cfg = await _create_mcp_client_config(builder,
936
+ server_cfg,
937
+ url,
938
+ transport,
939
+ auth_redirect_uri,
940
+ auth_user_id,
941
+ auth_scopes,
942
+ per_user)
943
+
944
+ group = await builder.add_function_group(group_name, group_cfg)
945
+ fns = await group.get_accessible_functions()
946
+ full = f"{group_name}{FunctionGroup.SEPARATOR}{tool_name}"
947
+ fn = fns.get(full)
948
+ if fn is None:
949
+ raise RuntimeError(f"Tool '{tool_name}' not found. Available: {list(fns.keys())}")
950
+ # The group exposes a Function that we can invoke with kwargs
951
+ result = await fn.acall_invoke(**(tool_args or {}))
952
+ # Ensure string output for terminal
953
+ return str(result)
954
+
955
+
956
+ @mcp_client_tool_group.command(name="call", help="Call a tool by name with optional arguments.")
957
+ @click.argument('tool_name', nargs=1, required=True)
958
+ @click.option('--direct', is_flag=True, help='Bypass MCPBuilder and use direct MCP protocol')
959
+ @click.option(
960
+ '--url',
961
+ default='http://localhost:9901/mcp',
962
+ show_default=True,
963
+ help='MCP server URL (e.g. http://localhost:8080/mcp for streamable-http, http://localhost:8080/sse for sse)')
964
+ @click.option('--transport',
965
+ type=click.Choice(['sse', 'stdio', 'streamable-http']),
966
+ default='streamable-http',
967
+ show_default=True,
968
+ help='Type of client to use (default: streamable-http, backwards compatible with sse)')
969
+ @click.option('--command', help='For stdio: The command to run (e.g. mcp-server)')
970
+ @click.option('--args', help='For stdio: Additional arguments for the command (space-separated)')
971
+ @click.option('--env', help='For stdio: Environment variables in KEY=VALUE format (space-separated)')
972
+ @click.option('--json-args', default=None, help='Pass tool args as a JSON object string')
973
+ @click.option('--auth',
974
+ is_flag=True,
975
+ help='Enable OAuth2 authentication with default settings (streamable-http only, not with --direct)')
976
+ @click.option('--auth-redirect-uri',
977
+ help='OAuth2 redirect URI for authentication (streamable-http only, not with --direct)')
978
+ @click.option('--auth-user-id', help='User ID for authentication (streamable-http only, not with --direct)')
979
+ @click.option('--auth-scopes', help='OAuth2 scopes (comma-separated, streamable-http only, not with --direct)')
980
+ @click.option('--bearer-token', help='Bearer token for authentication (streamable-http only, not with --direct)')
981
+ @click.option('--bearer-token-env',
982
+ help='Environment variable name containing bearer token (e.g., KAGGLE_BEARER_TOKEN)')
983
+ @click.option('--per-user', is_flag=True, help='Use per-user function group instead of shared function group')
984
+ @click.option('--user-id',
985
+ default='nat_mcp_cli_user_id',
986
+ help='User ID for per-user workflows (defaults to nat_mcp_cli_user_id)')
987
+ def mcp_client_tool_call(tool_name: str,
988
+ direct: bool,
989
+ url: str | None,
990
+ transport: str,
991
+ command: str | None,
992
+ args: str | None,
993
+ env: str | None,
994
+ json_args: str | None,
995
+ auth: bool,
996
+ auth_redirect_uri: str | None,
997
+ auth_user_id: str | None,
998
+ auth_scopes: str | None,
999
+ bearer_token: str | None,
1000
+ bearer_token_env: str | None,
1001
+ per_user: bool,
1002
+ user_id: str | None) -> None:
1003
+ """Call an MCP tool by name with optional JSON arguments.
1004
+
1005
+ Validates transport parameters, parses ``--json-args`` into a dictionary,
1006
+ invokes the tool (either directly or via the function group), and prints
1007
+ the resulting output to stdout. Errors are formatted consistently with
1008
+ other MCP CLI commands.
1009
+
1010
+ Args:
1011
+ tool_name (str): Name of the tool to call.
1012
+ direct (bool): If True, bypass WorkflowBuilder and use the direct MCP client.
1013
+ url (str | None): For ``sse`` or ``streamable-http`` transports, the server URL.
1014
+ transport (str): One of ``'stdio'``, ``'sse'``, or ``'streamable-http'``.
1015
+ command (str | None): For ``stdio`` transport, the command to execute.
1016
+ args (str | None): For ``stdio`` transport, space-separated command arguments.
1017
+ env (str | None): For ``stdio`` transport, space-separated ``KEY=VALUE`` pairs.
1018
+ json_args (str | None): JSON object string with tool arguments (e.g. '{"q": "hello"}').
1019
+ auth_redirect_uri (str | None): redirect URI for auth (streamable-http only, not with --direct)
1020
+ auth_user_id (str | None): User ID for authentication (streamable-http only, not with --direct)
1021
+ auth_scopes (str | None): OAuth2 scopes (comma-separated, streamable-http only, not with --direct)
1022
+
1023
+ Examples:
1024
+ nat mcp client tool call echo --json-args '{"text": "Hello"}'
1025
+ nat mcp client tool call search --direct --url http://localhost:9901/mcp \
1026
+ --json-args '{"query": "NVIDIA"}' # Direct mode (no auth)
1027
+ nat mcp client tool call run --transport stdio --command mcp-server \
1028
+ --args "--flag1 --flag2" --env "ENV1=V1 ENV2=V2" --json-args '{}'
1029
+ nat mcp client tool call search --url https://example.com/mcp/ --auth \
1030
+ --json-args '{"query": "test"}' # With auth using defaults
1031
+ nat mcp client tool call search --url https://example.com/mcp/ \
1032
+ --transport streamable-http --json-args '{"query": "test"}' --auth
1033
+ """
1034
+ # Validate transport args
1035
+ if not validate_transport_cli_args(transport, command, args, env):
1036
+ return
1037
+
1038
+ # Parse stdio params
1039
+ stdio_args = args.split() if args else []
1040
+ stdio_env = dict(var.split('=', 1) for var in env.split()) if env else None
1041
+
1042
+ # Set auth defaults if --auth flag is used
1043
+ auth_redirect_uri, auth_user_id, auth_scopes_list = _set_auth_defaults(
1044
+ auth, url, auth_redirect_uri, auth_user_id, auth_scopes
1045
+ )
1046
+
1047
+ # Validate: only one auth method at a time
1048
+ if (auth or auth_redirect_uri) and (bearer_token or bearer_token_env):
1049
+ click.echo("[ERROR] Cannot use both OAuth2 (--auth) and bearer token authentication", err=True)
1050
+ return
1051
+
1052
+ # Bearer token not supported with --direct
1053
+ if direct and (bearer_token or bearer_token_env):
1054
+ click.echo("[ERROR] --bearer-token and --bearer-token-env are not supported with --direct mode", err=True)
1055
+ return
1056
+
1057
+ # Parse tool args
1058
+ arg_obj: dict[str, Any] = {}
1059
+ if json_args:
1060
+ try:
1061
+ parsed = json.loads(json_args)
1062
+ if not isinstance(parsed, dict):
1063
+ click.echo("[ERROR] --json-args must be a JSON object", err=True)
1064
+ return
1065
+ arg_obj.update(parsed)
1066
+ except json.JSONDecodeError as e:
1067
+ click.echo(f"[ERROR] Failed to parse --json-args: {e}", err=True)
1068
+ return
1069
+
1070
+ try:
1071
+ output = asyncio.run(
1072
+ call_tool_and_print(
1073
+ command=command,
1074
+ url=url,
1075
+ tool_name=tool_name,
1076
+ transport=transport,
1077
+ args=stdio_args,
1078
+ env=stdio_env,
1079
+ tool_args=arg_obj,
1080
+ direct=direct,
1081
+ auth_redirect_uri=auth_redirect_uri,
1082
+ auth_user_id=auth_user_id,
1083
+ auth_scopes=auth_scopes_list,
1084
+ bearer_token=bearer_token,
1085
+ bearer_token_env=bearer_token_env,
1086
+ per_user=per_user,
1087
+ user_id=user_id,
1088
+ ))
1089
+ if output:
1090
+ click.echo(output)
1091
+ except MCPError as e:
1092
+ format_mcp_error(e, include_traceback=False)
1093
+ except Exception as e:
1094
+ click.echo(f"[ERROR] {e}", err=True)