|
| 1 | +"""Claude app integration utilities.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +import shutil |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from mcp.server.fastmcp.utilities.logging import get_logger |
| 11 | + |
| 12 | +logger = get_logger(__name__) |
| 13 | + |
| 14 | +MCP_PACKAGE = "mcp[cli]" |
| 15 | + |
| 16 | + |
| 17 | +def get_claude_config_path() -> Path | None: |
| 18 | + """Get the Claude config directory based on platform.""" |
| 19 | + if sys.platform == "win32": |
| 20 | + path = Path(Path.home(), "AppData", "Roaming", "Claude") |
| 21 | + elif sys.platform == "darwin": |
| 22 | + path = Path(Path.home(), "Library", "Application Support", "Claude") |
| 23 | + elif sys.platform.startswith("linux"): |
| 24 | + path = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"), "Claude") |
| 25 | + else: |
| 26 | + return None |
| 27 | + |
| 28 | + if path.exists(): |
| 29 | + return path |
| 30 | + return None |
| 31 | + |
| 32 | + |
| 33 | +def get_uv_path() -> str: |
| 34 | + """Get the full path to the uv executable.""" |
| 35 | + uv_path = shutil.which("uv") |
| 36 | + if not uv_path: |
| 37 | + logger.error( |
| 38 | + "uv executable not found in PATH, falling back to 'uv'. Please ensure uv is installed and in your PATH" |
| 39 | + ) |
| 40 | + return "uv" # Fall back to just "uv" if not found |
| 41 | + return uv_path |
| 42 | + |
| 43 | + |
| 44 | +def update_claude_config( |
| 45 | + file_spec: str, |
| 46 | + server_name: str, |
| 47 | + *, |
| 48 | + with_editable: Path | None = None, |
| 49 | + with_packages: list[str] | None = None, |
| 50 | + env_vars: dict[str, str] | None = None, |
| 51 | +) -> bool: |
| 52 | + """Add or update a FastMCP server in Claude's configuration. |
| 53 | +
|
| 54 | + Args: |
| 55 | + file_spec: Path to the server file, optionally with :object suffix |
| 56 | + server_name: Name for the server in Claude's config |
| 57 | + with_editable: Optional directory to install in editable mode |
| 58 | + with_packages: Optional list of additional packages to install |
| 59 | + env_vars: Optional dictionary of environment variables. These are merged with |
| 60 | + any existing variables, with new values taking precedence. |
| 61 | +
|
| 62 | + Raises: |
| 63 | + RuntimeError: If Claude Desktop's config directory is not found, indicating |
| 64 | + Claude Desktop may not be installed or properly set up. |
| 65 | + """ |
| 66 | + config_dir = get_claude_config_path() |
| 67 | + uv_path = get_uv_path() |
| 68 | + if not config_dir: |
| 69 | + raise RuntimeError( |
| 70 | + "Claude Desktop config directory not found. Please ensure Claude Desktop" |
| 71 | + " is installed and has been run at least once to initialize its config." |
| 72 | + ) |
| 73 | + |
| 74 | + config_file = config_dir / "claude_desktop_config.json" |
| 75 | + if not config_file.exists(): |
| 76 | + try: |
| 77 | + config_file.write_text("{}") |
| 78 | + except Exception: |
| 79 | + logger.exception( |
| 80 | + "Failed to create Claude config file", |
| 81 | + extra={ |
| 82 | + "config_file": str(config_file), |
| 83 | + }, |
| 84 | + ) |
| 85 | + return False |
| 86 | + |
| 87 | + try: |
| 88 | + config = json.loads(config_file.read_text()) |
| 89 | + if "mcpServers" not in config: |
| 90 | + config["mcpServers"] = {} |
| 91 | + |
| 92 | + # Always preserve existing env vars and merge with new ones |
| 93 | + if server_name in config["mcpServers"] and "env" in config["mcpServers"][server_name]: |
| 94 | + existing_env = config["mcpServers"][server_name]["env"] |
| 95 | + if env_vars: |
| 96 | + # New vars take precedence over existing ones |
| 97 | + env_vars = {**existing_env, **env_vars} |
| 98 | + else: |
| 99 | + env_vars = existing_env |
| 100 | + |
| 101 | + # Build uv run command |
| 102 | + args = ["run"] |
| 103 | + |
| 104 | + # Collect all packages in a set to deduplicate |
| 105 | + packages = {MCP_PACKAGE} |
| 106 | + if with_packages: |
| 107 | + packages.update(pkg for pkg in with_packages if pkg) |
| 108 | + |
| 109 | + # Add all packages with --with |
| 110 | + for pkg in sorted(packages): |
| 111 | + args.extend(["--with", pkg]) |
| 112 | + |
| 113 | + if with_editable: |
| 114 | + args.extend(["--with-editable", str(with_editable)]) |
| 115 | + |
| 116 | + # Convert file path to absolute before adding to command |
| 117 | + # Split off any :object suffix first |
| 118 | + if ":" in file_spec: |
| 119 | + file_path, server_object = file_spec.rsplit(":", 1) |
| 120 | + file_spec = f"{Path(file_path).resolve()}:{server_object}" |
| 121 | + else: |
| 122 | + file_spec = str(Path(file_spec).resolve()) |
| 123 | + |
| 124 | + # Add fastmcp run command |
| 125 | + args.extend(["mcp", "run", file_spec]) |
| 126 | + |
| 127 | + server_config: dict[str, Any] = {"command": uv_path, "args": args} |
| 128 | + |
| 129 | + # Add environment variables if specified |
| 130 | + if env_vars: |
| 131 | + server_config["env"] = env_vars |
| 132 | + |
| 133 | + config["mcpServers"][server_name] = server_config |
| 134 | + |
| 135 | + config_file.write_text(json.dumps(config, indent=2)) |
| 136 | + logger.info( |
| 137 | + f"Added server '{server_name}' to Claude config", |
| 138 | + extra={"config_file": str(config_file)}, |
| 139 | + ) |
| 140 | + return True |
| 141 | + except Exception: |
| 142 | + logger.exception( |
| 143 | + "Failed to update Claude config", |
| 144 | + extra={ |
| 145 | + "config_file": str(config_file), |
| 146 | + }, |
| 147 | + ) |
| 148 | + return False |
0 commit comments