acp-sdk 0.0.6__py3-none-any.whl → 0.1.0rc5__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 (77) hide show
  1. acp_sdk/__init__.py +1 -0
  2. acp_sdk/client/__init__.py +1 -0
  3. acp_sdk/client/client.py +139 -0
  4. acp_sdk/models/__init__.py +3 -0
  5. acp_sdk/models/errors.py +23 -0
  6. acp_sdk/models/models.py +181 -0
  7. acp_sdk/models/schemas.py +39 -0
  8. acp_sdk/server/__init__.py +6 -0
  9. acp_sdk/server/agent.py +105 -0
  10. acp_sdk/server/app.py +161 -0
  11. acp_sdk/server/bundle.py +131 -0
  12. acp_sdk/server/context.py +33 -0
  13. acp_sdk/server/errors.py +54 -0
  14. acp_sdk/server/logging.py +16 -0
  15. acp_sdk/server/server.py +120 -0
  16. acp_sdk/server/telemetry.py +52 -0
  17. acp_sdk/server/types.py +6 -0
  18. acp_sdk/server/utils.py +14 -0
  19. acp_sdk-0.1.0rc5.dist-info/METADATA +78 -0
  20. acp_sdk-0.1.0rc5.dist-info/RECORD +22 -0
  21. acp/__init__.py +0 -138
  22. acp/cli/__init__.py +0 -6
  23. acp/cli/claude.py +0 -139
  24. acp/cli/cli.py +0 -471
  25. acp/client/__init__.py +0 -0
  26. acp/client/__main__.py +0 -79
  27. acp/client/session.py +0 -372
  28. acp/client/sse.py +0 -145
  29. acp/client/stdio.py +0 -153
  30. acp/server/__init__.py +0 -3
  31. acp/server/__main__.py +0 -50
  32. acp/server/highlevel/__init__.py +0 -9
  33. acp/server/highlevel/agents/__init__.py +0 -5
  34. acp/server/highlevel/agents/agent_manager.py +0 -110
  35. acp/server/highlevel/agents/base.py +0 -20
  36. acp/server/highlevel/agents/templates.py +0 -21
  37. acp/server/highlevel/context.py +0 -185
  38. acp/server/highlevel/exceptions.py +0 -25
  39. acp/server/highlevel/prompts/__init__.py +0 -4
  40. acp/server/highlevel/prompts/base.py +0 -167
  41. acp/server/highlevel/prompts/manager.py +0 -50
  42. acp/server/highlevel/prompts/prompt_manager.py +0 -33
  43. acp/server/highlevel/resources/__init__.py +0 -23
  44. acp/server/highlevel/resources/base.py +0 -48
  45. acp/server/highlevel/resources/resource_manager.py +0 -94
  46. acp/server/highlevel/resources/templates.py +0 -80
  47. acp/server/highlevel/resources/types.py +0 -185
  48. acp/server/highlevel/server.py +0 -705
  49. acp/server/highlevel/tools/__init__.py +0 -4
  50. acp/server/highlevel/tools/base.py +0 -83
  51. acp/server/highlevel/tools/tool_manager.py +0 -53
  52. acp/server/highlevel/utilities/__init__.py +0 -1
  53. acp/server/highlevel/utilities/func_metadata.py +0 -210
  54. acp/server/highlevel/utilities/logging.py +0 -43
  55. acp/server/highlevel/utilities/types.py +0 -54
  56. acp/server/lowlevel/__init__.py +0 -3
  57. acp/server/lowlevel/helper_types.py +0 -9
  58. acp/server/lowlevel/server.py +0 -643
  59. acp/server/models.py +0 -17
  60. acp/server/session.py +0 -315
  61. acp/server/sse.py +0 -175
  62. acp/server/stdio.py +0 -83
  63. acp/server/websocket.py +0 -61
  64. acp/shared/__init__.py +0 -0
  65. acp/shared/context.py +0 -14
  66. acp/shared/exceptions.py +0 -14
  67. acp/shared/memory.py +0 -87
  68. acp/shared/progress.py +0 -40
  69. acp/shared/session.py +0 -413
  70. acp/shared/version.py +0 -3
  71. acp/types.py +0 -1258
  72. acp_sdk-0.0.6.dist-info/METADATA +0 -46
  73. acp_sdk-0.0.6.dist-info/RECORD +0 -57
  74. acp_sdk-0.0.6.dist-info/entry_points.txt +0 -2
  75. acp_sdk-0.0.6.dist-info/licenses/LICENSE +0 -22
  76. {acp → acp_sdk}/py.typed +0 -0
  77. {acp_sdk-0.0.6.dist-info → acp_sdk-0.1.0rc5.dist-info}/WHEEL +0 -0
acp/cli/claude.py DELETED
@@ -1,139 +0,0 @@
1
- """Claude app integration utilities."""
2
-
3
- import json
4
- import sys
5
- from pathlib import Path
6
-
7
- from acp.server.highlevel.utilities.logging import get_logger
8
-
9
- logger = get_logger(__name__)
10
-
11
- MCP_PACKAGE = "acp[cli]"
12
-
13
-
14
- def get_claude_config_path() -> Path | None:
15
- """Get the Claude config directory based on platform."""
16
- if sys.platform == "win32":
17
- path = Path(Path.home(), "AppData", "Roaming", "Claude")
18
- elif sys.platform == "darwin":
19
- path = Path(Path.home(), "Library", "Application Support", "Claude")
20
- else:
21
- return None
22
-
23
- if path.exists():
24
- return path
25
- return None
26
-
27
-
28
- def update_claude_config(
29
- file_spec: str,
30
- server_name: str,
31
- *,
32
- with_editable: Path | None = None,
33
- with_packages: list[str] | None = None,
34
- env_vars: dict[str, str] | None = None,
35
- ) -> bool:
36
- """Add or update a FastMCP server in Claude's configuration.
37
-
38
- Args:
39
- file_spec: Path to the server file, optionally with :object suffix
40
- server_name: Name for the server in Claude's config
41
- with_editable: Optional directory to install in editable mode
42
- with_packages: Optional list of additional packages to install
43
- env_vars: Optional dictionary of environment variables. These are merged with
44
- any existing variables, with new values taking precedence.
45
-
46
- Raises:
47
- RuntimeError: If Claude Desktop's config directory is not found, indicating
48
- Claude Desktop may not be installed or properly set up.
49
- """
50
- config_dir = get_claude_config_path()
51
- if not config_dir:
52
- raise RuntimeError(
53
- "Claude Desktop config directory not found. Please ensure Claude Desktop"
54
- " is installed and has been run at least once to initialize its config."
55
- )
56
-
57
- config_file = config_dir / "claude_desktop_config.json"
58
- if not config_file.exists():
59
- try:
60
- config_file.write_text("{}")
61
- except Exception as e:
62
- logger.error(
63
- "Failed to create Claude config file",
64
- extra={
65
- "error": str(e),
66
- "config_file": str(config_file),
67
- },
68
- )
69
- return False
70
-
71
- try:
72
- config = json.loads(config_file.read_text())
73
- if "mcpServers" not in config:
74
- config["mcpServers"] = {}
75
-
76
- # Always preserve existing env vars and merge with new ones
77
- if (
78
- server_name in config["mcpServers"]
79
- and "env" in config["mcpServers"][server_name]
80
- ):
81
- existing_env = config["mcpServers"][server_name]["env"]
82
- if env_vars:
83
- # New vars take precedence over existing ones
84
- env_vars = {**existing_env, **env_vars}
85
- else:
86
- env_vars = existing_env
87
-
88
- # Build uv run command
89
- args = ["run"]
90
-
91
- # Collect all packages in a set to deduplicate
92
- packages = {MCP_PACKAGE}
93
- if with_packages:
94
- packages.update(pkg for pkg in with_packages if pkg)
95
-
96
- # Add all packages with --with
97
- for pkg in sorted(packages):
98
- args.extend(["--with", pkg])
99
-
100
- if with_editable:
101
- args.extend(["--with-editable", str(with_editable)])
102
-
103
- # Convert file path to absolute before adding to command
104
- # Split off any :object suffix first
105
- if ":" in file_spec:
106
- file_path, server_object = file_spec.rsplit(":", 1)
107
- file_spec = f"{Path(file_path).resolve()}:{server_object}"
108
- else:
109
- file_spec = str(Path(file_spec).resolve())
110
-
111
- # Add fastmcp run command
112
- args.extend(["acp", "run", file_spec])
113
-
114
- server_config = {
115
- "command": "uv",
116
- "args": args,
117
- }
118
-
119
- # Add environment variables if specified
120
- if env_vars:
121
- server_config["env"] = env_vars
122
-
123
- config["mcpServers"][server_name] = server_config
124
-
125
- config_file.write_text(json.dumps(config, indent=2))
126
- logger.info(
127
- f"Added server '{server_name}' to Claude config",
128
- extra={"config_file": str(config_file)},
129
- )
130
- return True
131
- except Exception as e:
132
- logger.error(
133
- "Failed to update Claude config",
134
- extra={
135
- "error": str(e),
136
- "config_file": str(config_file),
137
- },
138
- )
139
- return False
acp/cli/cli.py DELETED
@@ -1,471 +0,0 @@
1
- """MCP CLI tools."""
2
-
3
- import importlib.metadata
4
- import importlib.util
5
- import os
6
- import subprocess
7
- import sys
8
- from pathlib import Path
9
- from typing import Annotated
10
-
11
- try:
12
- import typer
13
- except ImportError:
14
- print("Error: typer is required. Install with 'pip install mcp[cli]'")
15
- sys.exit(1)
16
-
17
- try:
18
- from acp.cli import claude
19
- from acp.server.highlevel.utilities.logging import get_logger
20
- except ImportError:
21
- print("Error: acp.server.highlevel is not installed or not in PYTHONPATH")
22
- sys.exit(1)
23
-
24
- try:
25
- import dotenv
26
- except ImportError:
27
- dotenv = None
28
-
29
- logger = get_logger("cli")
30
-
31
- app = typer.Typer(
32
- name="mcp",
33
- help="MCP development tools",
34
- add_completion=False,
35
- no_args_is_help=True, # Show help if no args provided
36
- )
37
-
38
-
39
- def _get_npx_command():
40
- """Get the correct npx command for the current platform."""
41
- if sys.platform == "win32":
42
- # Try both npx.cmd and npx.exe on Windows
43
- for cmd in ["npx.cmd", "npx.exe", "npx"]:
44
- try:
45
- subprocess.run(
46
- [cmd, "--version"], check=True, capture_output=True, shell=True
47
- )
48
- return cmd
49
- except subprocess.CalledProcessError:
50
- continue
51
- return None
52
- return "npx" # On Unix-like systems, just use npx
53
-
54
-
55
- def _parse_env_var(env_var: str) -> tuple[str, str]:
56
- """Parse environment variable string in format KEY=VALUE."""
57
- if "=" not in env_var:
58
- logger.error(
59
- f"Invalid environment variable format: {env_var}. Must be KEY=VALUE"
60
- )
61
- sys.exit(1)
62
- key, value = env_var.split("=", 1)
63
- return key.strip(), value.strip()
64
-
65
-
66
- def _build_uv_command(
67
- file_spec: str,
68
- with_editable: Path | None = None,
69
- with_packages: list[str] | None = None,
70
- ) -> list[str]:
71
- """Build the uv run command that runs a MCP server through mcp run."""
72
- cmd = ["uv"]
73
-
74
- cmd.extend(["run", "--with", "acp"])
75
-
76
- if with_editable:
77
- cmd.extend(["--with-editable", str(with_editable)])
78
-
79
- if with_packages:
80
- for pkg in with_packages:
81
- if pkg:
82
- cmd.extend(["--with", pkg])
83
-
84
- # Add mcp run command
85
- cmd.extend(["acp", "run", file_spec])
86
- return cmd
87
-
88
-
89
- def _parse_file_path(file_spec: str) -> tuple[Path, str | None]:
90
- """Parse a file path that may include a server object specification.
91
-
92
- Args:
93
- file_spec: Path to file, optionally with :object suffix
94
-
95
- Returns:
96
- Tuple of (file_path, server_object)
97
- """
98
- # First check if we have a Windows path (e.g., C:\...)
99
- has_windows_drive = len(file_spec) > 1 and file_spec[1] == ":"
100
-
101
- # Split on the last colon, but only if it's not part of the Windows drive letter
102
- # and there's actually another colon in the string after the drive letter
103
- if ":" in (file_spec[2:] if has_windows_drive else file_spec):
104
- file_str, server_object = file_spec.rsplit(":", 1)
105
- else:
106
- file_str, server_object = file_spec, None
107
-
108
- # Resolve the file path
109
- file_path = Path(file_str).expanduser().resolve()
110
- if not file_path.exists():
111
- logger.error(f"File not found: {file_path}")
112
- sys.exit(1)
113
- if not file_path.is_file():
114
- logger.error(f"Not a file: {file_path}")
115
- sys.exit(1)
116
-
117
- return file_path, server_object
118
-
119
-
120
- def _import_server(file: Path, server_object: str | None = None):
121
- """Import a MCP server from a file.
122
-
123
- Args:
124
- file: Path to the file
125
- server_object: Optional object name in format "module:object" or just "object"
126
-
127
- Returns:
128
- The server object
129
- """
130
- # Add parent directory to Python path so imports can be resolved
131
- file_dir = str(file.parent)
132
- if file_dir not in sys.path:
133
- sys.path.insert(0, file_dir)
134
-
135
- # Import the module
136
- spec = importlib.util.spec_from_file_location("server_module", file)
137
- if not spec or not spec.loader:
138
- logger.error("Could not load module", extra={"file": str(file)})
139
- sys.exit(1)
140
-
141
- module = importlib.util.module_from_spec(spec)
142
- spec.loader.exec_module(module)
143
-
144
- # If no object specified, try common server names
145
- if not server_object:
146
- # Look for the most common server object names
147
- for name in ["mcp", "server", "app"]:
148
- if hasattr(module, name):
149
- return getattr(module, name)
150
-
151
- logger.error(
152
- f"No server object found in {file}. Please either:\n"
153
- "1. Use a standard variable name (mcp, server, or app)\n"
154
- "2. Specify the object name with file:object syntax",
155
- extra={"file": str(file)},
156
- )
157
- sys.exit(1)
158
-
159
- # Handle module:object syntax
160
- if ":" in server_object:
161
- module_name, object_name = server_object.split(":", 1)
162
- try:
163
- server_module = importlib.import_module(module_name)
164
- server = getattr(server_module, object_name, None)
165
- except ImportError:
166
- logger.error(
167
- f"Could not import module '{module_name}'",
168
- extra={"file": str(file)},
169
- )
170
- sys.exit(1)
171
- else:
172
- # Just object name
173
- server = getattr(module, server_object, None)
174
-
175
- if server is None:
176
- logger.error(
177
- f"Server object '{server_object}' not found",
178
- extra={"file": str(file)},
179
- )
180
- sys.exit(1)
181
-
182
- return server
183
-
184
-
185
- @app.command()
186
- def version() -> None:
187
- """Show the MCP version."""
188
- try:
189
- version = importlib.metadata.version("mcp")
190
- print(f"MCP version {version}")
191
- except importlib.metadata.PackageNotFoundError:
192
- print("MCP version unknown (package not installed)")
193
- sys.exit(1)
194
-
195
-
196
- @app.command()
197
- def dev(
198
- file_spec: str = typer.Argument(
199
- ...,
200
- help="Python file to run, optionally with :object suffix",
201
- ),
202
- with_editable: Annotated[
203
- Path | None,
204
- typer.Option(
205
- "--with-editable",
206
- "-e",
207
- help="Directory containing pyproject.toml to install in editable mode",
208
- exists=True,
209
- file_okay=False,
210
- resolve_path=True,
211
- ),
212
- ] = None,
213
- with_packages: Annotated[
214
- list[str],
215
- typer.Option(
216
- "--with",
217
- help="Additional packages to install",
218
- ),
219
- ] = [],
220
- ) -> None:
221
- """Run a MCP server with the MCP Inspector."""
222
- file, server_object = _parse_file_path(file_spec)
223
-
224
- logger.debug(
225
- "Starting dev server",
226
- extra={
227
- "file": str(file),
228
- "server_object": server_object,
229
- "with_editable": str(with_editable) if with_editable else None,
230
- "with_packages": with_packages,
231
- },
232
- )
233
-
234
- try:
235
- # Import server to get dependencies
236
- server = _import_server(file, server_object)
237
- if hasattr(server, "dependencies"):
238
- with_packages = list(set(with_packages + server.dependencies))
239
-
240
- uv_cmd = _build_uv_command(file_spec, with_editable, with_packages)
241
-
242
- # Get the correct npx command
243
- npx_cmd = _get_npx_command()
244
- if not npx_cmd:
245
- logger.error(
246
- "npx not found. Please ensure Node.js and npm are properly installed "
247
- "and added to your system PATH."
248
- )
249
- sys.exit(1)
250
-
251
- # Run the MCP Inspector command with shell=True on Windows
252
- shell = sys.platform == "win32"
253
- process = subprocess.run(
254
- [npx_cmd, "@modelcontextprotocol/inspector"] + uv_cmd,
255
- check=True,
256
- shell=shell,
257
- env=dict(os.environ.items()), # Convert to list of tuples for env update
258
- )
259
- sys.exit(process.returncode)
260
- except subprocess.CalledProcessError as e:
261
- logger.error(
262
- "Dev server failed",
263
- extra={
264
- "file": str(file),
265
- "error": str(e),
266
- "returncode": e.returncode,
267
- },
268
- )
269
- sys.exit(e.returncode)
270
- except FileNotFoundError:
271
- logger.error(
272
- "npx not found. Please ensure Node.js and npm are properly installed "
273
- "and added to your system PATH. You may need to restart your terminal "
274
- "after installation.",
275
- extra={"file": str(file)},
276
- )
277
- sys.exit(1)
278
-
279
-
280
- @app.command()
281
- def run(
282
- file_spec: str = typer.Argument(
283
- ...,
284
- help="Python file to run, optionally with :object suffix",
285
- ),
286
- transport: Annotated[
287
- str | None,
288
- typer.Option(
289
- "--transport",
290
- "-t",
291
- help="Transport protocol to use (stdio or sse)",
292
- ),
293
- ] = None,
294
- ) -> None:
295
- """Run a MCP server.
296
-
297
- The server can be specified in two ways:
298
- 1. Module approach: server.py - runs the module directly, expecting a server.run()
299
- call
300
- 2. Import approach: server.py:app - imports and runs the specified server object
301
-
302
- Note: This command runs the server directly. You are responsible for ensuring
303
- all dependencies are available. For dependency management, use mcp install
304
- or mcp dev instead.
305
- """
306
- file, server_object = _parse_file_path(file_spec)
307
-
308
- logger.debug(
309
- "Running server",
310
- extra={
311
- "file": str(file),
312
- "server_object": server_object,
313
- "transport": transport,
314
- },
315
- )
316
-
317
- try:
318
- # Import and get server object
319
- server = _import_server(file, server_object)
320
-
321
- # Run the server
322
- kwargs = {}
323
- if transport:
324
- kwargs["transport"] = transport
325
-
326
- server.run(**kwargs)
327
-
328
- except Exception as e:
329
- logger.error(
330
- f"Failed to run server: {e}",
331
- extra={
332
- "file": str(file),
333
- "error": str(e),
334
- },
335
- )
336
- sys.exit(1)
337
-
338
-
339
- @app.command()
340
- def install(
341
- file_spec: str = typer.Argument(
342
- ...,
343
- help="Python file to run, optionally with :object suffix",
344
- ),
345
- server_name: Annotated[
346
- str | None,
347
- typer.Option(
348
- "--name",
349
- "-n",
350
- help="Custom name for the server (defaults to server's name attribute or"
351
- " file name)",
352
- ),
353
- ] = None,
354
- with_editable: Annotated[
355
- Path | None,
356
- typer.Option(
357
- "--with-editable",
358
- "-e",
359
- help="Directory containing pyproject.toml to install in editable mode",
360
- exists=True,
361
- file_okay=False,
362
- resolve_path=True,
363
- ),
364
- ] = None,
365
- with_packages: Annotated[
366
- list[str],
367
- typer.Option(
368
- "--with",
369
- help="Additional packages to install",
370
- ),
371
- ] = [],
372
- env_vars: Annotated[
373
- list[str],
374
- typer.Option(
375
- "--env-var",
376
- "-v",
377
- help="Environment variables in KEY=VALUE format",
378
- ),
379
- ] = [],
380
- env_file: Annotated[
381
- Path | None,
382
- typer.Option(
383
- "--env-file",
384
- "-f",
385
- help="Load environment variables from a .env file",
386
- exists=True,
387
- file_okay=True,
388
- dir_okay=False,
389
- resolve_path=True,
390
- ),
391
- ] = None,
392
- ) -> None:
393
- """Install a MCP server in the Claude desktop app.
394
-
395
- Environment variables are preserved once added and only updated if new values
396
- are explicitly provided.
397
- """
398
- file, server_object = _parse_file_path(file_spec)
399
-
400
- logger.debug(
401
- "Installing server",
402
- extra={
403
- "file": str(file),
404
- "server_name": server_name,
405
- "server_object": server_object,
406
- "with_editable": str(with_editable) if with_editable else None,
407
- "with_packages": with_packages,
408
- },
409
- )
410
-
411
- if not claude.get_claude_config_path():
412
- logger.error("Claude app not found")
413
- sys.exit(1)
414
-
415
- # Try to import server to get its name, but fall back to file name if dependencies
416
- # missing
417
- name = server_name
418
- server = None
419
- if not name:
420
- try:
421
- server = _import_server(file, server_object)
422
- name = server.name
423
- except (ImportError, ModuleNotFoundError) as e:
424
- logger.debug(
425
- "Could not import server (likely missing dependencies), using file"
426
- " name",
427
- extra={"error": str(e)},
428
- )
429
- name = file.stem
430
-
431
- # Get server dependencies if available
432
- server_dependencies = getattr(server, "dependencies", []) if server else []
433
- if server_dependencies:
434
- with_packages = list(set(with_packages + server_dependencies))
435
-
436
- # Process environment variables if provided
437
- env_dict: dict[str, str] | None = None
438
- if env_file or env_vars:
439
- env_dict = {}
440
- # Load from .env file if specified
441
- if env_file:
442
- if dotenv:
443
- try:
444
- env_dict |= {
445
- k: v
446
- for k, v in dotenv.dotenv_values(env_file).items()
447
- if v is not None
448
- }
449
- except Exception as e:
450
- logger.error(f"Failed to load .env file: {e}")
451
- sys.exit(1)
452
- else:
453
- logger.error("python-dotenv is not installed. Cannot load .env file.")
454
- sys.exit(1)
455
-
456
- # Add command line environment variables
457
- for env_var in env_vars:
458
- key, value = _parse_env_var(env_var)
459
- env_dict[key] = value
460
-
461
- if claude.update_claude_config(
462
- file_spec,
463
- name,
464
- with_editable=with_editable,
465
- with_packages=with_packages,
466
- env_vars=env_dict,
467
- ):
468
- logger.info(f"Successfully installed {name} in Claude app")
469
- else:
470
- logger.error(f"Failed to install {name} in Claude app")
471
- sys.exit(1)
acp/client/__init__.py DELETED
File without changes
acp/client/__main__.py DELETED
@@ -1,79 +0,0 @@
1
- import argparse
2
- import logging
3
- import sys
4
- from functools import partial
5
- from urllib.parse import urlparse
6
-
7
- import anyio
8
-
9
- from acp.client.session import ClientSession
10
- from acp.client.sse import sse_client
11
- from acp.client.stdio import StdioServerParameters, stdio_client
12
-
13
- if not sys.warnoptions:
14
- import warnings
15
-
16
- warnings.simplefilter("ignore")
17
-
18
- logging.basicConfig(level=logging.INFO)
19
- logger = logging.getLogger("client")
20
-
21
-
22
- async def receive_loop(session: ClientSession):
23
- logger.info("Starting receive loop")
24
- async for message in session.incoming_messages:
25
- if isinstance(message, Exception):
26
- logger.error("Error: %s", message)
27
- continue
28
-
29
- logger.info("Received message from server: %s", message)
30
-
31
-
32
- async def run_session(read_stream, write_stream):
33
- async with (
34
- ClientSession(read_stream, write_stream) as session,
35
- anyio.create_task_group() as tg,
36
- ):
37
- tg.start_soon(receive_loop, session)
38
-
39
- logger.info("Initializing session")
40
- await session.initialize()
41
- logger.info("Initialized")
42
-
43
-
44
- async def main(command_or_url: str, args: list[str], env: list[tuple[str, str]]):
45
- env_dict = dict(env)
46
-
47
- if urlparse(command_or_url).scheme in ("http", "https"):
48
- # Use SSE client for HTTP(S) URLs
49
- async with sse_client(command_or_url) as streams:
50
- await run_session(*streams)
51
- else:
52
- # Use stdio client for commands
53
- server_parameters = StdioServerParameters(
54
- command=command_or_url, args=args, env=env_dict
55
- )
56
- async with stdio_client(server_parameters) as streams:
57
- await run_session(*streams)
58
-
59
-
60
- def cli():
61
- parser = argparse.ArgumentParser()
62
- parser.add_argument("command_or_url", help="Command or URL to connect to")
63
- parser.add_argument("args", nargs="*", help="Additional arguments")
64
- parser.add_argument(
65
- "-e",
66
- "--env",
67
- nargs=2,
68
- action="append",
69
- metavar=("KEY", "VALUE"),
70
- help="Environment variables to set. Can be used multiple times.",
71
- default=[],
72
- )
73
-
74
- args = parser.parse_args()
75
- anyio.run(partial(main, args.command_or_url, args.args, args.env), backend="trio")
76
-
77
-
78
- if __name__ == "__main__":
79
- cli()