update_server
Modify specific settings of existing MCP servers in AWS Q Developer and Claude Desktop configuration files, allowing partial updates to command, arguments, and environment variables.
Instructions
既存のMCPサーバー設定を更新する。
指定されたフィールドのみが更新されます。
Args:
name: 更新するサーバーの名前
command: 新しいコマンド(オプション)
args: 新しい引数リスト(オプション)
env: 追加/更新する環境変数(オプション)
replace_env: Trueの場合、環境変数を完全に置き換える(デフォルト: False)
Returns:
Dict[str, Any]: 成功メッセージと更新されたサーバー情報、またはエラー情報
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| name | Yes | ||
| command | No | ||
| args | No | ||
| env | No | ||
| replace_env | No |
Implementation Reference
- The core handler function for the 'update_server' tool. It loads the MCP configuration, updates the specified server's command, args, or env (with merge or replace option), saves the changes with backup, and returns success/error details.@mcp.tool(name="update_server") async def update_server( name: str, command: Optional[str] = None, args: Optional[list[str]] = None, env: Optional[Dict[str, str]] = None, replace_env: bool = False, ) -> Dict[str, Any]: """既存のMCPサーバー設定を更新する。 指定されたフィールドのみが更新されます。 Args: name: 更新するサーバーの名前 command: 新しいコマンド(オプション) args: 新しい引数リスト(オプション) env: 追加/更新する環境変数(オプション) replace_env: Trueの場合、環境変数を完全に置き換える(デフォルト: False) Returns: Dict[str, Any]: 成功メッセージと更新されたサーバー情報、またはエラー情報 """ config = load_config() if name not in config.mcpServers: # サーバーが見つからない場合はエラーを返す logger.warning(f"Attempted to update non-existent server: {name}") return {"error": f"Server '{name}' not found", "available_servers": list(config.mcpServers.keys())} server = config.mcpServers[name] # 指定されたフィールドを更新 if command is not None: server.command = command if args is not None: server.args = args if env is not None: if replace_env or server.env is None: # 環境変数を完全に置き換える、または初回設定 server.env = env else: # 既存の環境変数にマージ server.env.update(env) # 変更を保存 try: save_config(config) logger.info(f"Successfully updated server: {name}") return { "message": f"Server '{name}' updated successfully", "server": {"name": name, "command": server.command, "args": server.args, "env": server.env}, } except Exception as e: logger.error(f"Failed to save configuration after updating server {name}: {e}") return {"error": f"Failed to save configuration: {str(e)}", "hint": "Check file permissions and disk space"}
- Pydantic model defining the structure of individual server configurations used by the update_server tool.class ServerConfig(BaseModel): """MCPサーバーの設定を表すモデル。 Attributes: command: 実行するコマンド(例: "python", "uvx", "node") args: コマンドライン引数のリスト env: 環境変数の辞書(オプション) """ command: str args: list[str] = Field(default_factory=list) env: Optional[Dict[str, str]] = None
- Pydantic model defining the top-level structure of the mcp.json file, containing a dictionary of server configurations.class MCPConfig(BaseModel): """mcp.json設定ファイルの構造を表すモデル。 Attributes: mcpServers: サーバー名をキーとし、ServerConfigを値とする辞書 """ mcpServers: Dict[str, ServerConfig] = Field(default_factory=dict)
- Helper function to save the updated MCP configuration to the JSON file atomically, with optional backup creation.def save_config(config: MCPConfig, create_backup_file: bool = True) -> None: """MCP設定をディスクに保存する。 必要に応じて親ディレクトリを作成し、設定をJSON形式で保存します。 Noneの値は除外され、読みやすいように2スペースでインデントされます。 Args: config: 保存するMCP設定 create_backup_file: 保存前にバックアップを作成するかどうか Raises: Exception: 保存に失敗した場合 """ try: # バックアップを作成 if create_backup_file and CONFIG_PATH.exists(): try: create_backup() except Exception as e: logger.warning(f"Failed to create backup, continuing with save: {e}") # 親ディレクトリが存在しない場合は作成 CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) # 一時ファイルに書き込んでからアトミックに置き換え temp_path = CONFIG_PATH.with_suffix(".tmp") with open(temp_path, "w") as f: json.dump(config.model_dump(exclude_none=True), f, indent=2) f.write("\n") # 最後に改行を追加 # アトミックに置き換え temp_path.replace(CONFIG_PATH) logger.info(f"Configuration saved successfully to {CONFIG_PATH}") except Exception as e: logger.error(f"Failed to save configuration: {e}") raise
- Helper function to load and validate the MCP configuration from the JSON file, returning empty on errors.def load_config() -> MCPConfig: """現在のMCP設定を読み込む。 設定ファイルが存在しない場合や読み込みエラーが発生した場合は、 空の設定を返します。 Returns: MCPConfig: 読み込まれた設定、またはデフォルトの空設定 """ if not CONFIG_PATH.exists(): # 設定ファイルが存在しない場合は空の設定を返す logger.info(f"Configuration file not found at {CONFIG_PATH}") return MCPConfig() try: with open(CONFIG_PATH, "r") as f: data = json.load(f) config = MCPConfig(**data) logger.debug(f"Loaded configuration with {len(config.mcpServers)} servers") return config except json.JSONDecodeError as e: logger.error(f"Failed to parse JSON configuration: {e}") # エラーが発生した場合も空の設定を返す(既存の設定を破壊しない) return MCPConfig() except ValidationError as e: logger.error(f"Configuration validation failed: {e}") return MCPConfig() except Exception as e: logger.error(f"Unexpected error loading configuration: {e}") return MCPConfig()