|
| 1 | +"""Configuration management for MCP servers.""" |
| 2 | + |
| 3 | +# stdlib imports |
| 4 | +import json |
| 5 | +from pathlib import Path |
| 6 | +from typing import Annotated, Any, Literal |
| 7 | + |
| 8 | +# third party imports |
| 9 | +from pydantic import BaseModel, Field, model_validator |
| 10 | + |
| 11 | + |
| 12 | +class MCPServerConfig(BaseModel): |
| 13 | + """Base class for MCP server configurations.""" |
| 14 | + |
| 15 | + pass |
| 16 | + |
| 17 | + |
| 18 | +class StdioServerConfig(MCPServerConfig): |
| 19 | + """Configuration for stdio-based MCP servers.""" |
| 20 | + |
| 21 | + type: Literal["stdio"] = "stdio" |
| 22 | + command: str |
| 23 | + args: list[str] | None = None |
| 24 | + env: dict[str, str] | None = None |
| 25 | + |
| 26 | + |
| 27 | +class StreamableHttpConfig(MCPServerConfig): |
| 28 | + """Configuration for StreamableHTTP-based MCP servers.""" |
| 29 | + |
| 30 | + type: Literal["streamable_http"] = "streamable_http" |
| 31 | + url: str |
| 32 | + headers: dict[str, str] | None = None |
| 33 | + |
| 34 | + |
| 35 | +# Discriminated union for different server config types |
| 36 | +ServerConfigUnion = Annotated[StdioServerConfig | StreamableHttpConfig, Field(discriminator="type")] |
| 37 | + |
| 38 | + |
| 39 | +class MCPServersConfig(BaseModel): |
| 40 | + """Configuration for multiple MCP servers.""" |
| 41 | + |
| 42 | + servers: dict[str, ServerConfigUnion] = Field(alias="mcpServers") |
| 43 | + |
| 44 | + @model_validator(mode="before") |
| 45 | + @classmethod |
| 46 | + def infer_server_types(cls, data: Any) -> Any: |
| 47 | + """Automatically infer server types when 'type' field is omitted.""" |
| 48 | + if isinstance(data, dict) and "mcpServers" in data: |
| 49 | + for _server_name, server_config in data["mcpServers"].items(): # type: ignore |
| 50 | + if isinstance(server_config, dict) and "type" not in server_config: |
| 51 | + # Infer type based on distinguishing fields |
| 52 | + if "command" in server_config: |
| 53 | + server_config["type"] = "stdio" |
| 54 | + elif "url" in server_config: |
| 55 | + server_config["type"] = "streamable_http" |
| 56 | + return data |
| 57 | + |
| 58 | + @classmethod |
| 59 | + def from_file(cls, config_path: Path) -> "MCPServersConfig": |
| 60 | + """Load configuration from a JSON file.""" |
| 61 | + with open(config_path) as config_file: |
| 62 | + return cls.model_validate(json.load(config_file)) |
0 commit comments