add_server
Add a new MCP server configuration to AWS Q Developer or Claude Desktop by specifying name, command, and optional arguments or environment variables.
Instructions
新しいMCPサーバー設定を追加する。
既に同名のサーバーが存在する場合はエラーを返します。
Args:
name: 新しいサーバーの名前
command: 実行するコマンド
args: コマンドライン引数(オプション)
env: 環境変数(オプション)
Returns:
Dict[str, Any]: 成功メッセージと追加されたサーバー情報、またはエラー情報
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| name | Yes | ||
| command | Yes | ||
| args | No | ||
| env | No |
Implementation Reference
- The core handler function for the 'add_server' MCP tool. It loads the current MCP configuration, checks for duplicate names, creates a new ServerConfig instance, adds it to the configuration, saves the updated config to disk (with backup), and returns success or error details.@mcp.tool(name="add_server") async def add_server( name: str, command: str, args: Optional[list[str]] = None, env: Optional[Dict[str, str]] = None ) -> Dict[str, Any]: """新しいMCPサーバー設定を追加する。 既に同名のサーバーが存在する場合はエラーを返します。 Args: name: 新しいサーバーの名前 command: 実行するコマンド args: コマンドライン引数(オプション) env: 環境変数(オプション) Returns: Dict[str, Any]: 成功メッセージと追加されたサーバー情報、またはエラー情報 """ config = load_config() if name in config.mcpServers: # 同名のサーバーが既に存在する場合はエラーを返す logger.warning(f"Attempted to add duplicate server: {name}") return { "error": f"Server '{name}' already exists", "hint": "Use update_server to modify existing configuration", } # 新しいサーバー設定を作成 server_config = ServerConfig(command=command, args=args or [], env=env) # 設定に追加して保存 config.mcpServers[name] = server_config try: save_config(config) logger.info(f"Successfully added server: {name}") return { "message": f"Server '{name}' added successfully", "server": { "name": name, "command": server_config.command, "args": server_config.args, "env": server_config.env, }, } except Exception as e: logger.error(f"Failed to save configuration after adding server {name}: {e}") return {"error": f"Failed to save configuration: {str(e)}", "hint": "Check file permissions and disk space"}
- Pydantic BaseModel defining the schema for individual server configurations, directly instantiated in add_server for validation and structure.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 BaseModel defining the overall MCP configuration structure, containing a dictionary of server names to ServerConfig instances, used for loading and saving the config file.class MCPConfig(BaseModel): """mcp.json設定ファイルの構造を表すモデル。 Attributes: mcpServers: サーバー名をキーとし、ServerConfigを値とする辞書 """ mcpServers: Dict[str, ServerConfig] = Field(default_factory=dict)
- Helper function to load and parse the MCP configuration file into an MCPConfig model instance, handling errors gracefully by returning an empty config.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()
- Helper function to save the MCPConfig to the JSON file atomically, optionally creating a timestamped backup first, ensuring data integrity.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