|
| 1 | +# MCP Server Best Practices |
| 2 | + |
| 3 | +This document lays out the best practices for an individual MCP server. You may use `oci-compute-mcp-server` as an example. |
| 4 | + |
| 5 | +## Typical MCP Server Structure |
| 6 | + |
| 7 | +``` |
| 8 | +mcp-server-name/ |
| 9 | +├── LICENSE.txt # License information |
| 10 | +├── pyproject.toml # Project configuration |
| 11 | +├── README.md # Project description, setup instructions |
| 12 | +├── uv.lock # Dependency lockfile |
| 13 | +└── oracle/ # Source code directory |
| 14 | + ├── __init__.py # Package initialization |
| 15 | + └── mcp_server_name/ # Server package, notice the underscores |
| 16 | + ├── __init__.py # Package version and metadata |
| 17 | + ├── models.py # Pydantic models |
| 18 | + ├── server.py # Server implementation |
| 19 | + ├── consts.py # Constants definition |
| 20 | + ├── ... # Additional modules |
| 21 | + └── tests/ # Test directory |
| 22 | +``` |
| 23 | + |
| 24 | +## Code Organization |
| 25 | + |
| 26 | +1. **Separation of Concerns**: |
| 27 | + - `models.py`: Define data models and validation logic |
| 28 | + - `server.py`: Implement MCP server, tools, and resources |
| 29 | + - `consts.py`: Define constants used across the server |
| 30 | + - Additional modules for specific functionality (e.g., API clients) |
| 31 | + |
| 32 | +2. **Keep modules focused and limited to a single responsibility** |
| 33 | + |
| 34 | +3. **Use clear and consistent naming conventions** |
| 35 | + |
| 36 | +### Entry Points |
| 37 | + |
| 38 | +MCP servers should follow these guidelines for application entry points: |
| 39 | + |
| 40 | +1. **Single Entry Point**: Define the main entry point only in `server.py` |
| 41 | + - Do not create a separate `main.py` file |
| 42 | + - This maintains clarity about how the application starts |
| 43 | + |
| 44 | +2. **Main Function**: Implement a `main()` function in `server.py` that: |
| 45 | + - Handles command-line arguments |
| 46 | + - Sets up environment and logging |
| 47 | + - Initializes the MCP server |
| 48 | + |
| 49 | +Example: |
| 50 | + |
| 51 | +```python |
| 52 | +def main(): |
| 53 | + """Run the MCP server with CLI argument support.""" |
| 54 | + mcp.run() |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == '__main__': |
| 58 | + main() |
| 59 | +``` |
| 60 | + |
| 61 | +3. **Package Entry Point**: Configure the entry point in `pyproject.toml`: |
| 62 | + |
| 63 | +```toml |
| 64 | +[project.scripts] |
| 65 | +"oracle.mcp-server-name" = "oracle.mcp_server_name.server:main" |
| 66 | +``` |
| 67 | + |
| 68 | +## License and Copyright Headers |
| 69 | + |
| 70 | +Include license headers at the top of each source file: |
| 71 | + |
| 72 | +```python |
| 73 | +""" |
| 74 | +Copyright (c) 2025, Oracle and/or its affiliates. |
| 75 | +Licensed under the Universal Permissive License v1.0 as shown at |
| 76 | +https://oss.oracle.com/licenses/upl. |
| 77 | +""" |
| 78 | +``` |
| 79 | + |
| 80 | +## Type Definitions |
| 81 | + |
| 82 | +### General Rules |
| 83 | + |
| 84 | +1. Make all models Pydantic; this ensures serializability. You may refer to the OCI python SDK for reference to most OCI models. |
| 85 | +2. Define Literals for constrained values. |
| 86 | +3. Add comprehensive descriptions to each field. |
| 87 | + |
| 88 | +Pydantic model example for [NetworkSecurityGroup](src/oci-networking-mcp-server/oracle/oci_networking_mcp_server/models.py) |
| 89 | + |
| 90 | +```python |
| 91 | +from typing import Any, Dict, List, Literal, Optional |
| 92 | +from pydantic import BaseModel, Field |
| 93 | + |
| 94 | +class NetworkSecurityGroup(BaseModel): |
| 95 | + """ |
| 96 | + Pydantic model mirroring the fields of oci.core.models.NetworkSecurityGroup. |
| 97 | + """ |
| 98 | + |
| 99 | + compartment_id: Optional[str] = Field( |
| 100 | + None, |
| 101 | + description="The OCID of the compartment containing the network security group.", |
| 102 | + ) |
| 103 | + defined_tags: Optional[Dict[str, Dict[str, Any]]] = Field( |
| 104 | + None, |
| 105 | + description="Defined tags for this resource. Each key is predefined and scoped to a namespace.", |
| 106 | + ) |
| 107 | + display_name: Optional[str] = Field( |
| 108 | + None, description="A user-friendly name. Does not have to be unique." |
| 109 | + ) |
| 110 | + freeform_tags: Optional[Dict[str, str]] = Field( |
| 111 | + None, description="Free-form tags for this resource as simple key/value pairs." |
| 112 | + ) |
| 113 | + id: Optional[str] = Field( |
| 114 | + None, description="The OCID of the network security group." |
| 115 | + ) |
| 116 | + lifecycle_state: Optional[ |
| 117 | + Literal[ |
| 118 | + "PROVISIONING", |
| 119 | + "AVAILABLE", |
| 120 | + "TERMINATING", |
| 121 | + "TERMINATED", |
| 122 | + "UNKNOWN_ENUM_VALUE", |
| 123 | + ] |
| 124 | + ] = Field(None, description="The network security group's current state.") |
| 125 | + time_created: Optional[datetime] = Field( |
| 126 | + None, |
| 127 | + description="The date and time the network security group was created (RFC3339).", |
| 128 | + ) |
| 129 | + vcn_id: Optional[str] = Field( |
| 130 | + None, description="The OCID of the VCN the network security group belongs to." |
| 131 | + ) |
| 132 | +``` |
| 133 | + |
| 134 | +## Function Parameters with Pydantic Field |
| 135 | + |
| 136 | +MCP tool functions should use spread parameters with Pydantic's `Field` for detailed descriptions: |
| 137 | + |
| 138 | +Here is an example for [list_instances](src/oci-compute-mcp-server/oracle/oci_compute_mcp_server/server.py) |
| 139 | + |
| 140 | +```python |
| 141 | +@mcp.tool(description="List Instances in a given compartment") |
| 142 | +def list_instances( |
| 143 | + compartment_id: str = Field( |
| 144 | + ..., |
| 145 | + description="The OCID of the compartment" |
| 146 | + ), |
| 147 | + limit: Optional[int] = Field( |
| 148 | + None, |
| 149 | + description="The maximum amount of instances to return. If None, there is no limit.", |
| 150 | + ge=1 |
| 151 | + ), |
| 152 | + lifecycle_state: Optional[LifecycleState] = Field( |
| 153 | + None, |
| 154 | + description="The lifecycle state of the instance to filter on" |
| 155 | + ) |
| 156 | +) -> list[Instance]: |
| 157 | + instances: list[Instance] = [] |
| 158 | + |
| 159 | + try: |
| 160 | + client = get_compute_client() |
| 161 | + |
| 162 | + response: oci.response.Response = None |
| 163 | + has_next_page = True |
| 164 | + next_page: str = None |
| 165 | + |
| 166 | + while has_next_page and (limit is None or len(instances) < limit): |
| 167 | + kwargs = { |
| 168 | + "compartment_id": compartment_id, |
| 169 | + "page": next_page, |
| 170 | + "limit": limit, |
| 171 | + } |
| 172 | + |
| 173 | + if lifecycle_state is not None: |
| 174 | + kwargs["lifecycle_state"] = lifecycle_state |
| 175 | + |
| 176 | + response = client.list_instances(**kwargs) |
| 177 | + has_next_page = response.has_next_page |
| 178 | + next_page = response.next_page if hasattr(response, "next_page") else None |
| 179 | + |
| 180 | + data: list[oci.core.models.Instance] = response.data |
| 181 | + for d in data: |
| 182 | + instance = map_instance(d) |
| 183 | + instances.append(instance) |
| 184 | + |
| 185 | + logger.info(f"Found {len(instances)} Instances") |
| 186 | + return instances |
| 187 | + |
| 188 | + except Exception as e: |
| 189 | + logger.error(f"Error in list_instances tool: {str(e)}") |
| 190 | + raise e |
| 191 | +``` |
| 192 | + |
| 193 | +### Field Guidelines |
| 194 | + |
| 195 | +1. **Required parameters**: Use `...` as the default value to indicate a parameter is required |
| 196 | +2. **Optional parameters**: Provide sensible defaults and mark as `Optional` in the type hint |
| 197 | +3. **Descriptions**: Write clear, informative descriptions for each parameter |
| 198 | +4. **Validation**: Use Field constraints like `ge`, `le`, `min_length`, `max_length` |
| 199 | +5. **Literals**: Use `Literal` for parameters with a fixed set of valid values |
0 commit comments