nvidia-nat-mcp 1.4.0a20251028__py3-none-any.whl → 1.4.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.

Potentially problematic release.


This version of nvidia-nat-mcp might be problematic. Click here for more details.

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