nvidia-nat-mcp 1.4.0a20260107__py3-none-any.whl

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