Repository: IBM/mcp-context-forge

Issue:
[Bug]: Unable to add multiple headers when adding a gateway through UI (draft)
<img width="2127" height="968" alt="Image" src="https://github.com/user-attachments/assets/69247782-bc96-4bb0-8be7-0cbbf8ae40a7" />

UI (and APIs / backend / database) should support multiple custom headers.


Discussion:
Here is the detailed plan to support multiple custom headers in mcpgateway:

1. __UI Changes (`mcpgateway/templates/admin.html`):__

   - __Current:__ The "Add New Gateway" form has single input fields for `auth_header_key` and `auth_header_value` under the "Custom Headers" authentication type.
   - __Change:__ Replace these two inputs with a dynamic list of header key-value pairs. Add "Add Header" and "Remove Header" buttons to allow users to add multiple headers. On form submission, serialize these headers as an array of objects (e.g., `[{"key": "...", "value": "..."}]`).
   - __Additional:__ Update JavaScript handling form submission (in `mcpgateway/static/admin.js`) to support this new structure.

2. __API Changes (`mcpgateway/admin.py`):__

   - __Current:__ The `admin_add_gateway` and `admin_edit_gateway` endpoints accept `auth_header_key` and `auth_header_value` as single string form fields.
   - __Change:__ Modify these endpoints to accept a JSON string or list of header objects for custom headers instead of single key-value pairs. Parse this JSON into a list of headers.
   - __Example:__ Replace `auth_header_key` and `auth_header_value` with a single `auth_headers` JSON field representing multiple headers.

3. __Backend Changes (`mcpgateway/services/gateway_service.py`):__

   - __Current:__ The `GatewayCreate` and `GatewayUpdate` schemas and the `register_gateway` and `update_gateway` methods handle `auth_header_key` and `auth_header_value` as single values.
   - __Change:__ Update the gateway schemas to replace `auth_header_key` and `auth_header_value` with a single field `auth_headers` that is a list of key-value pairs or a dictionary.
   - Modify `register_gateway` and `update_gateway` methods to handle multiple headers, storing them in `auth_value` or a new field accordingly.
   - Update the `_initialize_gateway` method and any other relevant logic to apply all custom headers when connecting to the gateway.

4. __Database Changes:__

   - __Current:__ The database stores `auth_header_key` and `auth_header_value` as separate columns or fields.

   - __Change:__ Migrate to storing multiple headers, either by:

     - Adding a JSON column `auth_headers` to store an array or dictionary of headers, or
     - Creating a new related table for headers linked to gateways.

   - Write migration scripts to convert existing single header data into the new format.

5. __Testing:__

   - Update and add tests in `tests/playwright/test_admin_ui.py`, `tests/playwright/test_api_endpoints.py`, and `tests/playwright/test_api_integration.py` to cover multiple headers in UI, API, and backend.
   - Test edge cases such as empty headers, duplicate keys, and invalid inputs.

6. __Documentation:__

   - Update relevant documentation files to describe the new multiple headers feature.




Patch:
diff --git a/CLAUDE.md b/CLAUDE.md
index 75df6b79..1c9dcfbb 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -228,7 +228,7 @@ pytest -m "not slow"
 # To test everything:
 
 make autoflake isort black pre-commit
-make doctest test smoketest lint-web flake8 pylint
+make interrogate doctest test smoketest lint-web flake8 bandit pylint
 
 # Rules
 - When using git commit always add a -s to sign commits
diff --git a/docs/docs/using/multi-auth-headers.md b/docs/docs/using/multi-auth-headers.md
new file mode 100644
index 00000000..adaea274
--- /dev/null
+++ b/docs/docs/using/multi-auth-headers.md
@@ -0,0 +1,189 @@
+# Multiple Authentication Headers
+
+## Overview
+
+MCP Gateway now supports multiple custom authentication headers for gateway connections. This feature allows you to configure multiple header key-value pairs that will be sent with every request to your MCP servers.
+
+## Use Cases
+
+Multiple authentication headers are useful when:
+- Your MCP server requires multiple API keys or tokens
+- You need to send client identification along with authentication
+- Your service uses region-specific or version-specific headers
+- You're integrating with services that require complex header-based authentication
+
+## Configuration
+
+### Via Admin UI
+
+1. Navigate to the Admin Panel at `http://localhost:8000/admin/`
+2. Click on the "Gateways" tab
+3. When adding or editing a gateway:
+   - Select "Custom Headers" as the Authentication Type
+   - Click "Add Header" to add multiple header pairs
+   - Enter the header key (e.g., `X-API-Key`) and value for each header
+   - Click "Remove" next to any header to delete it
+   - Submit the form to save your configuration
+
+### Via API
+
+Send a POST request to `/admin/gateways` with the `auth_headers` field as a JSON array:
+
+```json
+{
+  "name": "My Gateway",
+  "url": "http://mcp-server.example.com",
+  "auth_type": "authheaders",
+  "auth_headers": [
+    {"key": "X-API-Key", "value": "secret-key-123"},
+    {"key": "X-Client-ID", "value": "client-456"},
+    {"key": "X-Region", "value": "us-east-1"}
+  ]
+}
+```
+
+### Via Python SDK
+
+```python
+from mcpgateway.schemas import GatewayCreate
+
+gateway = GatewayCreate(
+    name="My Gateway",
+    url="http://mcp-server.example.com",
+    auth_type="authheaders",
+    auth_headers=[
+        {"key": "X-API-Key", "value": "secret-key-123"},
+        {"key": "X-Client-ID", "value": "client-456"},
+        {"key": "X-Region", "value": "us-east-1"}
+    ]
+)
+```
+
+## Backward Compatibility
+
+The gateway still supports the legacy single-header format for backward compatibility:
+
+```json
+{
+  "name": "My Gateway",
+  "url": "http://mcp-server.example.com",
+  "auth_type": "authheaders",
+  "auth_header_key": "X-API-Key",
+  "auth_header_value": "secret-key-123"
+}
+```
+
+If both `auth_headers` (multi) and `auth_header_key`/`auth_header_value` (single) are provided, the multi-header format takes precedence.
+
+## Security Considerations
+
+### Encryption
+All authentication headers are encrypted before being stored in the database using AES-256-GCM encryption. The encryption key is derived from the `AUTH_ENCRYPTION_SECRET` environment variable.
+
+### Header Validation
+- Empty header keys are ignored
+- Duplicate header keys will use the last provided value
+- Header values can be empty strings if required by your authentication scheme
+- Special characters in header keys and values are supported
+
+### Best Practices
+1. **Use HTTPS**: Always use HTTPS URLs for your MCP servers to prevent header interception
+2. **Rotate Keys**: Regularly rotate your API keys and update them in the gateway configuration
+3. **Minimal Headers**: Only include headers that are strictly necessary for authentication
+4. **Environment Variables**: Store sensitive values in environment variables when deploying
+
+## Common Patterns
+
+### Multiple API Keys
+```json
+{
+  "auth_headers": [
+    {"key": "X-Primary-Key", "value": "primary-secret"},
+    {"key": "X-Secondary-Key", "value": "secondary-secret"}
+  ]
+}
+```
+
+### API Key with Client Identification
+```json
+{
+  "auth_headers": [
+    {"key": "X-API-Key", "value": "api-secret"},
+    {"key": "X-Client-ID", "value": "client-123"},
+    {"key": "X-Client-Secret", "value": "client-secret"}
+  ]
+}
+```
+
+### Regional Configuration
+```json
+{
+  "auth_headers": [
+    {"key": "X-API-Key", "value": "api-secret"},
+    {"key": "X-Region", "value": "eu-west-1"},
+    {"key": "X-Environment", "value": "production"}
+  ]
+}
+```
+
+## Troubleshooting
+
+### Headers Not Being Sent
+1. Check that your gateway is using `auth_type: "authheaders"`
+2. Verify headers are properly formatted in the JSON array
+3. Ensure the gateway is enabled and reachable
+4. Check server logs to confirm headers are being received
+
+### Case Sensitivity
+HTTP headers are case-insensitive by specification. Some HTTP clients or servers may normalize header names to lowercase. Your MCP server should handle headers in a case-insensitive manner.
+
+### Validation Errors
+If you receive validation errors when saving:
+- Ensure at least one header is provided when using "Custom Headers" authentication
+- Check that your JSON is properly formatted if using the API
+- Verify that header keys don't contain invalid characters
+
+### Testing Your Configuration
+Use the "Test" button in the Admin UI to verify your gateway connection with the configured headers. The test will attempt to connect to your MCP server and validate that authentication is working correctly.
+
+## Migration from Single Headers
+
+If you have existing gateways using single header authentication, they will continue to work without modification. To migrate to multi-headers:
+
+1. Edit your gateway in the Admin UI
+2. Your existing single header will be displayed
+3. Add additional headers as needed
+4. Save the configuration
+
+The system will automatically convert your configuration to the multi-header format while preserving your existing authentication.
+
+## API Reference
+
+### GatewayCreate Schema
+```python
+{
+    "name": str,
+    "url": str,
+    "auth_type": "authheaders",
+    "auth_headers": [
+        {"key": str, "value": str},
+        ...
+    ]
+}
+```
+
+### GatewayUpdate Schema
+```python
+{
+    "auth_type": "authheaders",
+    "auth_headers": [
+        {"key": str, "value": str},
+        ...
+    ]
+}
+```
+
+## Related Documentation
+- [Gateway Authentication](./authentication.md)
+- [Security Best Practices](../security/best-practices.md)
+- [API Documentation](../api/gateways.md)
diff --git a/mcpgateway/admin.py b/mcpgateway/admin.py
index 001c19a0..8cc8a360 100644
--- a/mcpgateway/admin.py
+++ b/mcpgateway/admin.py
@@ -2585,6 +2585,26 @@ async def admin_add_gateway(request: Request, db: Session = Depends(get_db), use
         tags_str = form.get("tags", "")
         tags = [tag.strip() for tag in tags_str.split(",") if tag.strip()] if tags_str else []
 
+        # Parse auth_headers JSON if present
+        auth_headers_json = form.get("auth_headers")
+        auth_headers = []
+        if auth_headers_json:
+            try:
+                auth_headers = json.loads(auth_headers_json)
+            except (json.JSONDecodeError, ValueError):
+                auth_headers = []
+
+        # Handle passthrough_headers
+        passthrough_headers = form.get("passthrough_headers")
+        if passthrough_headers and passthrough_headers.strip():
+            try:
+                passthrough_headers = json.loads(passthrough_headers)
+            except (json.JSONDecodeError, ValueError):
+                # Fallback to comma-separated parsing
+                passthrough_headers = [h.strip() for h in passthrough_headers.split(",") if h.strip()]
+        else:
+            passthrough_headers = None
+
         gateway = GatewayCreate(
             name=form["name"],
             url=form["url"],
@@ -2597,6 +2617,8 @@ async def admin_add_gateway(request: Request, db: Session = Depends(get_db), use
             auth_token=form.get("auth_token", ""),
             auth_header_key=form.get("auth_header_key", ""),
             auth_header_value=form.get("auth_header_value", ""),
+            auth_headers=auth_headers if auth_headers else None,
+            passthrough_headers=passthrough_headers,
         )
     except KeyError as e:
         # Convert KeyError to ValidationError-like response
@@ -2741,6 +2763,26 @@ async def admin_edit_gateway(
         tags_str = form.get("tags", "")
         tags = [tag.strip() for tag in tags_str.split(",") if tag.strip()] if tags_str else []
 
+        # Parse auth_headers JSON if present
+        auth_headers_json = form.get("auth_headers")
+        auth_headers = []
+        if auth_headers_json:
+            try:
+                auth_headers = json.loads(auth_headers_json)
+            except (json.JSONDecodeError, ValueError):
+                auth_headers = []
+
+        # Handle passthrough_headers
+        passthrough_headers = form.get("passthrough_headers")
+        if passthrough_headers and passthrough_headers.strip():
+            try:
+                passthrough_headers = json.loads(passthrough_headers)
+            except (json.JSONDecodeError, ValueError):
+                # Fallback to comma-separated parsing
+                passthrough_headers = [h.strip() for h in passthrough_headers.split(",") if h.strip()]
+        else:
+            passthrough_headers = None
+
         gateway = GatewayUpdate(  # Pydantic validation happens here
             name=form.get("name"),
             url=form["url"],
@@ -2753,6 +2795,8 @@ async def admin_edit_gateway(
             auth_token=form.get("auth_token", None),
             auth_header_key=form.get("auth_header_key", None),
             auth_header_value=form.get("auth_header_value", None),
+            auth_headers=auth_headers if auth_headers else None,
+            passthrough_headers=passthrough_headers,
         )
         await gateway_service.update_gateway(db, gateway_id, gateway)
         return JSONResponse(
diff --git a/mcpgateway/handlers/sampling.py b/mcpgateway/handlers/sampling.py
index bb6a4464..a8e805ff 100644
--- a/mcpgateway/handlers/sampling.py
+++ b/mcpgateway/handlers/sampling.py
@@ -218,7 +218,7 @@ async def create_message(self, db: Session, request: Dict[str, Any]) -> CreateMe
                 if not self._validate_message(msg):
                     raise SamplingError(f"Invalid message format: {msg}")
 
-            # TODO: Sample from selected model
+            # FIXME: Implement actual model sampling - currently returns mock response
             # For now return mock response
             response = self._mock_sample(messages=messages)
 
@@ -357,7 +357,7 @@ async def _add_context(self, _db: Session, messages: List[Dict[str, Any]], _cont
             >>> len(result)
             2
         """
-        # TODO: Implement context gathering based on type
+        # FIXME: Implement context gathering based on type - currently no-op
         # For now return original messages
         return messages
 
diff --git a/mcpgateway/schemas.py b/mcpgateway/schemas.py
index 60ad937e..28e4283c 100644
--- a/mcpgateway/schemas.py
+++ b/mcpgateway/schemas.py
@@ -1713,6 +1713,7 @@ class GatewayCreate(BaseModel):
         auth_token (Optional[str]): Token for bearer authentication.
         auth_header_key (Optional[str]): Key for custom headers authentication.
         auth_header_value (Optional[str]): Value for custom headers authentication.
+        auth_headers (Optional[List[Dict[str, str]]]): List of custom headers for authentication.
         auth_value (Optional[str]): Alias for authentication value, used for better access post-validation.
     """
 
@@ -1732,6 +1733,7 @@ class GatewayCreate(BaseModel):
     auth_token: Optional[str] = Field(None, description="Token for bearer authentication")
     auth_header_key: Optional[str] = Field(None, description="Key for custom headers authentication")
     auth_header_value: Optional[str] = Field(None, description="Value for custom headers authentication")
+    auth_headers: Optional[List[Dict[str, str]]] = Field(None, description="List of custom headers for authentication")
 
     # Adding `auth_value` as an alias for better access post-validation
     auth_value: Optional[str] = Field(None, validate_default=True)
@@ -1816,9 +1818,21 @@ def create_auth_value(cls, v, info):
         if (auth_type is None) or (auth_type == ""):
             return v  # If no auth_type is provided, no need to create auth_value
 
-        # Process the auth fields and generate auth_value based on auth_type
-        auth_value = cls._process_auth_fields(info)
+        # If custom headers, use all headers
+        if auth_type == "authheaders":
+            auth_headers = data.get("auth_headers")
+            if auth_headers and isinstance(auth_headers, list):
+                # Convert list of {key, value} to dict
+                header_dict = {h["key"]: h["value"] for h in auth_headers if h.get("key")}
+                return encode_auth(header_dict)
+            # Fallback to old single key/value
+            header_key = data.get("auth_header_key")
+            header_value = data.get("auth_header_value")
+            if header_key and header_value:
+                return encode_auth({header_key: header_value})
 
+        # Otherwise, use the default logic
+        auth_value = cls._process_auth_fields(info)
         return auth_value
 
     @field_validator("transport")
@@ -1885,12 +1899,21 @@ def _process_auth_fields(info: ValidationInfo) -> Optional[Dict[str, Any]]:
             return encode_auth({"Authorization": f"Bearer {token}"})
 
         if auth_type == "authheaders":
-            # For headers authentication, both key and value must be present
+            # Support both new multi-headers format and legacy single header format
+            auth_headers = data.get("auth_headers")
+            if auth_headers and isinstance(auth_headers, list):
+                # New multi-headers format
+                header_dict = {h["key"]: h["value"] for h in auth_headers if h.get("key")}
+                if not header_dict:
+                    raise ValueError("For 'headers' auth, at least one header must be provided.")
+                return encode_auth(header_dict)
+
+            # Legacy single header format (backward compatibility)
             header_key = data.get("auth_header_key")
             header_value = data.get("auth_header_value")
 
             if not header_key or not header_value:
-                raise ValueError("For 'headers' auth, both 'auth_header_key' and 'auth_header_value' must be provided.")
+                raise ValueError("For 'headers' auth, either 'auth_headers' list or both 'auth_header_key' and 'auth_header_value' must be provided.")
 
             return encode_auth({header_key: header_value})
 
@@ -1909,6 +1932,7 @@ class GatewayUpdate(BaseModelWithConfigDict):
     transport: str = Field(default="SSE", description="Transport used by MCP server: SSE or STREAMABLEHTTP")
 
     passthrough_headers: Optional[List[str]] = Field(default=None, description="List of headers allowed to be passed through from client to target")
+
     # Authorizations
     auth_type: Optional[str] = Field(None, description="auth_type: basic, bearer, headers or None")
     auth_username: Optional[str] = Field(None, description="username for basic authentication")
@@ -1916,6 +1940,7 @@ class GatewayUpdate(BaseModelWithConfigDict):
     auth_token: Optional[str] = Field(None, description="token for bearer authentication")
     auth_header_key: Optional[str] = Field(None, description="key for custom headers authentication")
     auth_header_value: Optional[str] = Field(None, description="value for custom headers authentication")
+    auth_headers: Optional[List[Dict[str, str]]] = Field(None, description="List of custom headers for authentication")
 
     # Adding `auth_value` as an alias for better access post-validation
     auth_value: Optional[str] = Field(None, validate_default=True)
@@ -2002,9 +2027,18 @@ def create_auth_value(cls, v, info):
         if (auth_type is None) or (auth_type == ""):
             return v  # If no auth_type is provided, no need to create auth_value
 
-        # Process the auth fields and generate auth_value based on auth_type
-        auth_value = cls._process_auth_fields(info)
+        # If custom headers, use all headers
+        if auth_type == "authheaders":
+            auth_headers = data.get("auth_headers")
+            if auth_headers and isinstance(auth_headers, list):
+                header_dict = {h["key"]: h["value"] for h in auth_headers if h.get("key")}
+                return encode_auth(header_dict)
+            header_key = data.get("auth_header_key")
+            header_value = data.get("auth_header_value")
+            if header_key and header_value:
+                return encode_auth({header_key: header_value})
 
+        auth_value = cls._process_auth_fields(info)
         return auth_value
 
     @staticmethod
@@ -2045,12 +2079,55 @@ def _process_auth_fields(values: Dict[str, Any]) -> Optional[Dict[str, Any]]:
             return encode_auth({"Authorization": f"Bearer {token}"})
 
         if auth_type == "authheaders":
-            # For headers authentication, both key and value must be present
+            # Support both new multi-headers format and legacy single header format
+            auth_headers = values.data.get("auth_headers")
+            if auth_headers and isinstance(auth_headers, list):
+                # New multi-headers format with enhanced validation
+                header_dict = {}
+                duplicate_keys = set()
+
+                for header in auth_headers:
+                    if not isinstance(header, dict):
+                        continue
+
+                    key = header.get("key")
+                    value = header.get("value", "")
+
+                    # Skip headers without keys
+                    if not key:
+                        continue
+
+                    # Track duplicate keys (last value wins)
+                    if key in header_dict:
+                        duplicate_keys.add(key)
+
+                    # Validate header key format (basic HTTP header validation)
+                    if not all(c.isalnum() or c in "-_" for c in key.replace(" ", "")):
+                        raise ValueError(f"Invalid header key format: '{key}'. Header keys should contain only alphanumeric characters, hyphens, and underscores.")
+
+                    # Store header (empty values are allowed)
+                    header_dict[key] = value
+
+                # Ensure at least one valid header
+                if not header_dict:
+                    raise ValueError("For 'headers' auth, at least one valid header with a key must be provided.")
+
+                # Warn about duplicate keys (optional - could log this instead)
+                if duplicate_keys:
+                    logging.warning(f"Duplicate header keys detected (last value used): {', '.join(duplicate_keys)}")
+
+                # Check for excessive headers (prevent abuse)
+                if len(header_dict) > 100:
+                    raise ValueError("Maximum of 100 headers allowed per gateway.")
+
+                return encode_auth(header_dict)
+
+            # Legacy single header format (backward compatibility)
             header_key = values.data.get("auth_header_key")
             header_value = values.data.get("auth_header_value")
 
             if not header_key or not header_value:
-                raise ValueError("For 'headers' auth, both 'auth_header_key' and 'auth_header_value' must be provided.")
+                raise ValueError("For 'headers' auth, either 'auth_headers' list or both 'auth_header_key' and 'auth_header_value' must be provided.")
 
             return encode_auth({header_key: header_value})
 
@@ -2196,9 +2273,9 @@ def _populate_auth(cls, values: Self) -> Dict[str, Any]:
             values.auth_token = auth.removeprefix("Bearer ")
 
         elif auth_type == "authheaders":
-            # must be exactly one header
-            if len(auth_value) != 1:
-                raise ValueError("authheaders requires exactly one key/value pair")
+            # For backward compatibility, populate first header in key/value fields
+            if len(auth_value) == 0:
+                raise ValueError("authheaders requires at least one key/value pair")
             k, v = next(iter(auth_value.items()))
             values.auth_header_key, values.auth_header_value = k, v
 
diff --git a/mcpgateway/services/gateway_service.py b/mcpgateway/services/gateway_service.py
index 5d665b46..26a1aa77 100644
--- a/mcpgateway/services/gateway_service.py
+++ b/mcpgateway/services/gateway_service.py
@@ -77,7 +77,7 @@
 from mcpgateway.services.tool_service import ToolService
 from mcpgateway.utils.create_slug import slugify
 from mcpgateway.utils.retry_manager import ResilientHttpClient
-from mcpgateway.utils.services_auth import decode_auth
+from mcpgateway.utils.services_auth import decode_auth, encode_auth
 
 # Initialize logging service first
 logging_service = LoggingService()
@@ -394,7 +394,12 @@ async def register_gateway(self, db: Session, gateway: GatewayCreate) -> Gateway
                 )
 
             auth_type = getattr(gateway, "auth_type", None)
+            # Support multiple custom headers
             auth_value = getattr(gateway, "auth_value", {})
+            if hasattr(gateway, "auth_headers") and gateway.auth_headers:
+                # Convert list of {key, value} to dict
+                header_dict = {h["key"]: h["value"] for h in gateway.auth_headers if h.get("key")}
+                auth_value = encode_auth(header_dict)  # Encode the dict for consistency
 
             capabilities, tools = await self._initialize_gateway(gateway.url, auth_value, gateway.transport)
 
@@ -577,15 +582,19 @@ async def update_gateway(self, db: Session, gateway_id: str, gateway_update: Gat
                         gateway.auth_value = ""
 
                     # if auth_type is not None and only then check auth_value
-                    if getattr(gateway, "auth_value", "") != "":
-                        token = gateway_update.auth_token
-                        password = gateway_update.auth_password
-                        header_value = gateway_update.auth_header_value
-
-                        if settings.masked_auth_value not in (token, password, header_value):
-                            # Check if values differ from existing ones
-                            if gateway.auth_value != gateway_update.auth_value:
-                                gateway.auth_value = gateway_update.auth_value
+                if getattr(gateway, "auth_value", "") != "":
+                    token = gateway_update.auth_token
+                    password = gateway_update.auth_password
+                    header_value = gateway_update.auth_header_value
+
+                    # Support multiple custom headers on update
+                    if hasattr(gateway_update, "auth_headers") and gateway_update.auth_headers:
+                        header_dict = {h["key"]: h["value"] for h in gateway_update.auth_headers if h.get("key")}
+                        gateway.auth_value = encode_auth(header_dict)  # Encode the dict for consistency
+                    elif settings.masked_auth_value not in (token, password, header_value):
+                        # Check if values differ from existing ones
+                        if gateway.auth_value != gateway_update.auth_value:
+                            gateway.auth_value = gateway_update.auth_value
 
                 # Try to reinitialize connection if URL changed
                 if gateway_update.url is not None:
diff --git a/mcpgateway/static/admin.js b/mcpgateway/static/admin.js
index 6d1d55e1..d52abd16 100644
--- a/mcpgateway/static/admin.js
+++ b/mcpgateway/static/admin.js
@@ -2856,9 +2856,19 @@ function handleAuthTypeSelection(
         case "bearer":
             bearerFields.style.display = "block";
             break;
-        case "authheaders":
+        case "authheaders": {
             headersFields.style.display = "block";
+            // Ensure at least one header row is present
+            const containerId =
+                headersFields.querySelector('[id$="-container"]')?.id;
+            if (containerId) {
+                const container = document.getElementById(containerId);
+                if (container && container.children.length === 0) {
+                    addAuthHeader(containerId);
+                }
+            }
             break;
+        }
         default:
             // All fields already hidden
             break;
@@ -4653,6 +4663,24 @@ async function handleGatewayFormSubmit(e) {
             );
         }
 
+        // Handle auth_headers JSON field
+        const authHeadersJson = formData.get("auth_headers");
+        if (authHeadersJson) {
+            try {
+                const authHeaders = JSON.parse(authHeadersJson);
+                if (Array.isArray(authHeaders) && authHeaders.length > 0) {
+                    // Remove the JSON string and add as parsed data for backend processing
+                    formData.delete("auth_headers");
+                    formData.append(
+                        "auth_headers",
+                        JSON.stringify(authHeaders),
+                    );
+                }
+            } catch (e) {
+                console.error("Invalid auth_headers JSON:", e);
+            }
+        }
+
         const response = await fetchWithTimeout(
             `${window.ROOT_PATH}/admin/gateways`,
             {
@@ -6238,4 +6266,218 @@ window.filterEntitiesByTags = filterEntitiesByTags;
 window.clearTagFilter = clearTagFilter;
 window.updateAvailableTags = updateAvailableTags;
 
+// ===================================================================
+// MULTI-HEADER AUTHENTICATION MANAGEMENT
+// ===================================================================
+
+/**
+ * Global counter for unique header IDs
+ */
+let headerCounter = 0;
+
+/**
+ * Add a new authentication header row to the specified container
+ * @param {string} containerId - ID of the container to add the header row to
+ */
+function addAuthHeader(containerId) {
+    const container = document.getElementById(containerId);
+    if (!container) {
+        console.error(`Container with ID ${containerId} not found`);
+        return;
+    }
+
+    const headerId = `auth-header-${++headerCounter}`;
+
+    const headerRow = document.createElement("div");
+    headerRow.className = "flex items-center space-x-2";
+    headerRow.id = headerId;
+
+    headerRow.innerHTML = `
+        <div class="flex-1">
+            <input
+                type="text"
+                placeholder="Header Key (e.g., X-API-Key)"
+                class="auth-header-key block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300 text-sm"
+                oninput="updateAuthHeadersJSON('${containerId}')"
+            />
+        </div>
+        <div class="flex-1">
+            <input
+                type="password"
+                placeholder="Header Value"
+                class="auth-header-value block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300 text-sm"
+                oninput="updateAuthHeadersJSON('${containerId}')"
+            />
+        </div>
+        <button
+            type="button"
+            onclick="removeAuthHeader('${headerId}', '${containerId}')"
+            class="inline-flex items-center px-2 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-red-700 bg-red-100 hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 dark:bg-red-900 dark:text-red-300 dark:hover:bg-red-800"
+            title="Remove header"
+        >
+            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
+            </svg>
+        </button>
+    `;
+
+    container.appendChild(headerRow);
+    updateAuthHeadersJSON(containerId);
+
+    // Focus on the key input of the new header
+    const keyInput = headerRow.querySelector(".auth-header-key");
+    if (keyInput) {
+        keyInput.focus();
+    }
+}
+
+/**
+ * Remove an authentication header row
+ * @param {string} headerId - ID of the header row to remove
+ * @param {string} containerId - ID of the container to update
+ */
+function removeAuthHeader(headerId, containerId) {
+    const headerRow = document.getElementById(headerId);
+    if (headerRow) {
+        headerRow.remove();
+        updateAuthHeadersJSON(containerId);
+    }
+}
+
+/**
+ * Update the JSON representation of authentication headers
+ * @param {string} containerId - ID of the container with headers
+ */
+function updateAuthHeadersJSON(containerId) {
+    const container = document.getElementById(containerId);
+    if (!container) {
+        return;
+    }
+
+    const headers = [];
+    const headerRows = container.querySelectorAll('[id^="auth-header-"]');
+    const duplicateKeys = new Set();
+    const seenKeys = new Set();
+    let hasValidationErrors = false;
+
+    headerRows.forEach((row) => {
+        const keyInput = row.querySelector(".auth-header-key");
+        const valueInput = row.querySelector(".auth-header-value");
+
+        if (keyInput && valueInput) {
+            const key = keyInput.value.trim();
+            const value = valueInput.value.trim();
+
+            // Skip completely empty rows
+            if (!key && !value) {
+                return;
+            }
+
+            // Require key but allow empty values
+            if (!key) {
+                keyInput.setCustomValidity("Header key is required");
+                keyInput.reportValidity();
+                hasValidationErrors = true;
+                return;
+            }
+
+            // Validate header key format (letters, numbers, hyphens, underscores)
+            if (!/^[a-zA-Z0-9\-_]+$/.test(key)) {
+                keyInput.setCustomValidity(
+                    "Header keys should contain only letters, numbers, hyphens, and underscores",
+                );
+                keyInput.reportValidity();
+                hasValidationErrors = true;
+                return;
+            } else {
+                keyInput.setCustomValidity("");
+            }
+
+            // Track duplicate keys
+            if (seenKeys.has(key.toLowerCase())) {
+                duplicateKeys.add(key);
+            }
+            seenKeys.add(key.toLowerCase());
+
+            headers.push({
+                key,
+                value, // Allow empty values
+            });
+        }
+    });
+
+    // Find the corresponding JSON input field
+    let jsonInput = null;
+    if (containerId === "auth-headers-container") {
+        jsonInput = document.getElementById("auth-headers-json");
+    } else if (containerId === "auth-headers-container-gw") {
+        jsonInput = document.getElementById("auth-headers-json-gw");
+    } else if (containerId === "edit-auth-headers-container") {
+        jsonInput = document.getElementById("edit-auth-headers-json");
+    } else if (containerId === "auth-headers-container-gw-edit") {
+        jsonInput = document.getElementById("auth-headers-json-gw-edit");
+    }
+
+    // Warn about duplicate keys in console
+    if (duplicateKeys.size > 0 && !hasValidationErrors) {
+        console.warn(
+            "Duplicate header keys detected (last value will be used):",
+            Array.from(duplicateKeys),
+        );
+    }
+
+    // Check for excessive headers
+    if (headers.length > 100) {
+        console.error("Maximum of 100 headers allowed per gateway");
+        return;
+    }
+
+    if (jsonInput) {
+        jsonInput.value = headers.length > 0 ? JSON.stringify(headers) : "";
+    }
+}
+
+/**
+ * Load existing authentication headers for editing
+ * @param {string} containerId - ID of the container to populate
+ * @param {Array} headers - Array of header objects with key and value properties
+ */
+function loadAuthHeaders(containerId, headers) {
+    const container = document.getElementById(containerId);
+    if (!container || !headers || !Array.isArray(headers)) {
+        return;
+    }
+
+    // Clear existing headers
+    container.innerHTML = "";
+
+    // Add each header
+    headers.forEach((header) => {
+        if (header.key && header.value) {
+            addAuthHeader(containerId);
+            // Find the last added header row and populate it
+            const headerRows = container.querySelectorAll(
+                '[id^="auth-header-"]',
+            );
+            const lastRow = headerRows[headerRows.length - 1];
+            if (lastRow) {
+                const keyInput = lastRow.querySelector(".auth-header-key");
+                const valueInput = lastRow.querySelector(".auth-header-value");
+                if (keyInput && valueInput) {
+                    keyInput.value = header.key;
+                    valueInput.value = header.value;
+                }
+            }
+        }
+    });
+
+    updateAuthHeadersJSON(containerId);
+}
+
+// Expose authentication header functions to global scope
+window.addAuthHeader = addAuthHeader;
+window.removeAuthHeader = removeAuthHeader;
+window.updateAuthHeadersJSON = updateAuthHeadersJSON;
+window.loadAuthHeaders = loadAuthHeaders;
+
 console.log("🛡️ ContextForge MCP Gateway admin.js initialized");
diff --git a/mcpgateway/templates/admin.html b/mcpgateway/templates/admin.html
index 03229ce3..873a0aa7 100644
--- a/mcpgateway/templates/admin.html
+++ b/mcpgateway/templates/admin.html
@@ -1131,26 +1131,26 @@ <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
                 </div>
               </div>
               <div id="auth-headers-fields" style="display: none">
-                <div>
-                  <label class="block text-sm font-medium text-gray-700"
-                    >Header Key</label
-                  >
-                  <input
-                    type="text"
-                    name="auth_header_key"
-                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
-                  />
-                </div>
-                <div>
-                  <label class="block text-sm font-medium text-gray-700"
-                    >Header Value</label
-                  >
-                  <input
-                    type="password"
-                    name="auth_header_value"
-                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
-                    placeholder="********"
-                  />
+                <div class="space-y-3">
+                  <div class="flex items-center justify-between">
+                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">
+                      Custom Headers
+                    </label>
+                    <button
+                      type="button"
+                      onclick="addAuthHeader('auth-headers-container')"
+                      class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
+                    >
+                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
+                      </svg>
+                      Add Header
+                    </button>
+                  </div>
+                  <div id="auth-headers-container" class="space-y-2">
+                    <!-- Headers will be added dynamically here -->
+                  </div>
+                  <input type="hidden" name="auth_headers" id="auth-headers-json" />
                 </div>
               </div>
             </div>
@@ -2193,26 +2193,26 @@ <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
                 </div>
               </div>
               <div id="auth-headers-fields-gw" style="display: none">
-                <div>
-                  <label class="block text-sm font-medium text-gray-700"
-                    >Header Key</label
-                  >
-                  <input
-                    type="text"
-                    name="auth_header_key"
-                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
-                  />
-                </div>
-                <div>
-                  <label class="block text-sm font-medium text-gray-700"
-                    >Header Value</label
-                  >
-                  <input
-                    type="password"
-                    name="auth_header_value"
-                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
-                    placeholder="********"
-                  />
+                <div class="space-y-3">
+                  <div class="flex items-center justify-between">
+                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">
+                      Custom Headers
+                    </label>
+                    <button
+                      type="button"
+                      onclick="addAuthHeader('auth-headers-container-gw')"
+                      class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
+                    >
+                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
+                      </svg>
+                      Add Header
+                    </button>
+                  </div>
+                  <div id="auth-headers-container-gw" class="space-y-2">
+                    <!-- Headers will be added dynamically here -->
+                  </div>
+                  <input type="hidden" name="auth_headers" id="auth-headers-json-gw" />
                 </div>
               </div>
               <div>
@@ -2794,30 +2794,26 @@ <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                     </div>
                   </div>
                   <div id="edit-auth-headers-fields" style="display: none">
-                    <div>
-                      <label
-                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
-                        >Header Key</label
-                      >
-                      <input
-                        type="text"
-                        name="auth_header_key"
-                        id="edit-auth-key"
-                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
-                      />
-                    </div>
-                    <div>
-                      <label
-                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
-                        >Header Value</label
-                      >
-                      <input
-                        type="password"
-                        name="auth_header_value"
-                        id="edit-auth-value"
-                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
-                        placeholder="********"
-                      />
+                    <div class="space-y-3">
+                      <div class="flex items-center justify-between">
+                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">
+                          Custom Headers
+                        </label>
+                        <button
+                          type="button"
+                          onclick="addAuthHeader('edit-auth-headers-container')"
+                          class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
+                        >
+                          <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
+                          </svg>
+                          Add Header
+                        </button>
+                      </div>
+                      <div id="edit-auth-headers-container" class="space-y-2">
+                        <!-- Headers will be added dynamically here -->
+                      </div>
+                      <input type="hidden" name="auth_headers" id="edit-auth-headers-json" />
                     </div>
                   </div>
                   <!-- Tags Section -->
@@ -3472,26 +3468,26 @@ <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                       </div>
                     </div>
                     <div id="auth-headers-fields-gw-edit" style="display: none">
-                      <div>
-                        <label class="block text-sm font-medium text-gray-700"
-                          >Header Key</label
-                        >
-                        <input
-                          type="text"
-                          name="auth_header_key"
-                          class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
-                        />
-                      </div>
-                      <div>
-                        <label class="block text-sm font-medium text-gray-700"
-                          >Header Value</label
-                        >
-                        <input
-                          type="password"
-                          name="auth_header_value"
-                          class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
-                          placeholder="********"
-                        />
+                      <div class="space-y-3">
+                        <div class="flex items-center justify-between">
+                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">
+                            Custom Headers
+                          </label>
+                          <button
+                            type="button"
+                            onclick="addAuthHeader('auth-headers-container-gw-edit')"
+                            class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
+                          >
+                            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
+                            </svg>
+                            Add Header
+                          </button>
+                        </div>
+                        <div id="auth-headers-container-gw-edit" class="space-y-2">
+                          <!-- Headers will be added dynamically here -->
+                        </div>
+                        <input type="hidden" name="auth_headers" id="auth-headers-json-gw-edit" />
                       </div>
                     </div>
                     <div>
diff --git a/mcpgateway/utils/error_formatter.py b/mcpgateway/utils/error_formatter.py
index 9591cb31..4b94be18 100644
--- a/mcpgateway/utils/error_formatter.py
+++ b/mcpgateway/utils/error_formatter.py
@@ -128,7 +128,8 @@ def format_validation_error(error: ValidationError) -> Dict[str, Any]:
         errors = []
 
         for err in error.errors():
-            field = err.get("loc", ["field"])[-1]
+            loc = err.get("loc", ["field"])
+            field = loc[-1] if loc else "field"
             msg = err.get("msg", "Invalid value")
 
             # Map technical messages to user-friendly ones


Test patch:
diff --git a/tests/e2e/test_main_apis.py b/tests/e2e/test_main_apis.py
index fdfa961a..3ff0e72b 100644
--- a/tests/e2e/test_main_apis.py
+++ b/tests/e2e/test_main_apis.py
@@ -39,26 +39,31 @@
 2. Test with sample MCP server(s) in test scripts
 """
 
+# Standard
+import base64
+
 # Standard Library
 import json
 import os
 import tempfile
 import time
-import base64
 from typing import AsyncGenerator
 from unittest.mock import MagicMock, patch
 
 # Third-Party
+from httpx import AsyncClient
+
+# --- Test Auth Header: Use a real JWT for authenticated requests ---
+import jwt
 import pytest
 import pytest_asyncio
-from httpx import AsyncClient
 from sqlalchemy import create_engine
 from sqlalchemy.orm import sessionmaker
 from sqlalchemy.pool import StaticPool
 
 # First-Party
-from mcpgateway.db import Base
 from mcpgateway.config import settings
+from mcpgateway.db import Base
 from mcpgateway.main import app, get_db
 
 # pytest.skip("Temporarily disabling this suite", allow_module_level=True)
@@ -67,17 +72,14 @@
 # Test Configuration
 # -------------------------
 
-# --- Test Auth Header: Use a real JWT for authenticated requests ---
-import jwt
 
 TEST_USER = "testuser"
 JWT_SECRET = "my-test-key"  # Must match mcpgateway.config.Settings.jwt_secret_key
-JWT_ALGORITHM = "HS256"     # Must match mcpgateway.config.Settings.jwt_algorithm
+JWT_ALGORITHM = "HS256"  # Must match mcpgateway.config.Settings.jwt_algorithm
+
 
 def generate_test_jwt():
-    payload = {
-        "sub": TEST_USER
-    }
+    payload = {"sub": TEST_USER}
     token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
     # PyJWT >=2 returns str, <2 returns bytes
     if isinstance(token, bytes):
@@ -87,7 +89,7 @@ def generate_test_jwt():
 
 # Helper function for generating test JWT
 def _generate_test_jwt():
-    payload = {"sub": "test_user","exp": int(time.time()) + 3600}
+    payload = {"sub": "test_user", "exp": int(time.time()) + 3600}
     secret = settings.jwt_secret_key
     algorithm = settings.jwt_algorithm
     token = jwt.encode(payload, secret, algorithm=algorithm)
@@ -99,6 +101,7 @@ def _generate_test_jwt():
 def generate_test_jwt():
     return _generate_test_jwt()
 
+
 TEST_AUTH_HEADER = {"Authorization": f"Bearer {generate_test_jwt()}"}
 
 
@@ -207,6 +210,7 @@ def basic_auth_header(username: str, password: str) -> dict:
     token = base64.b64encode(f"{username}:{password}".encode()).decode()
     return {"Authorization": f"Basic {token}"}
 
+
 # -------------------------
 # Test Utility APIs
 # -------------------------
@@ -214,14 +218,18 @@ class TestDocsAndRedoc:
     @classmethod
     def setup_class(cls):
         # Enable Basic Auth for docs endpoints during these tests
+        # First-Party
         from mcpgateway.config import settings
+
         cls._original_docs_allow_basic_auth = settings.docs_allow_basic_auth
         settings.docs_allow_basic_auth = True
 
     @classmethod
     def teardown_class(cls):
         # Restore original setting
+        # First-Party
         from mcpgateway.config import settings
+
         settings.docs_allow_basic_auth = cls._original_docs_allow_basic_auth
 
     async def test_docs_with_basic_auth(self, client: AsyncClient):
@@ -246,6 +254,7 @@ async def test_cors_preflight(self, client: AsyncClient):
         response = await client.options("/health", headers={"Origin": "http://localhost", "Access-Control-Request-Method": "GET"})
         assert response.status_code in [200, 204]
         assert "access-control-allow-origin" in response.headers
+
     """Test health check and readiness endpoints."""
 
     async def test_health_check(self, client: AsyncClient):
@@ -300,7 +309,8 @@ async def test_initialize_no_body(self, client: AsyncClient):
     async def test_notifications_missing_method(self, client: AsyncClient):
         """Test POST /protocol/notifications with missing method field."""
         response = await client.post("/protocol/notifications", json={}, headers=TEST_AUTH_HEADER)
-        assert response.status_code in [200,400, 422]
+        assert response.status_code in [200, 400, 422]
+
     """Test MCP protocol-related endpoints."""
 
     async def test_initialize(self, client: AsyncClient):
@@ -396,6 +406,7 @@ async def test_get_servers_no_auth(self, client: AsyncClient):
         """Test GET /servers without auth header (should fail if auth required)."""
         response = await client.get("/servers")
         assert response.status_code in [401, 403, 200]
+
     """Test server management endpoints."""
 
     async def test_list_servers_empty(self, client: AsyncClient, mock_auth):
@@ -535,6 +546,7 @@ async def test_server_name_conflict(self, client: AsyncClient, mock_auth):
         else:
             # Accept any error format as long as status is correct
             assert response.status_code == 409
+
     async def test_create_server_success_and_missing_fields(self, client: AsyncClient, mock_auth):
         """Test POST /servers - create server success and missing fields."""
         server_data = {"name": "test_server", "description": "A test server"}
@@ -562,6 +574,7 @@ async def test_update_server_success_and_invalid(self, client: AsyncClient, mock
         response = await client.put("/servers/invalid-id", json=update_data, headers=TEST_AUTH_HEADER)
         assert response.status_code in [400, 404]
 
+
 # -------------------------
 # Test Tool APIs
 # -------------------------
@@ -570,6 +583,7 @@ async def test_create_tool_no_body(self, client: AsyncClient, mock_auth):
         """Test POST /tools with no body (should fail validation)."""
         response = await client.post("/tools", headers=TEST_AUTH_HEADER)
         assert response.status_code in [400, 422]
+
     """Test tool management endpoints."""
 
     async def test_list_tools_empty(self, client: AsyncClient, mock_auth):
@@ -769,6 +783,7 @@ async def test_create_resource_no_body(self, client: AsyncClient, mock_auth):
         """Test POST /resources with no body (should fail validation)."""
         response = await client.post("/resources", headers=TEST_AUTH_HEADER)
         assert response.status_code in [400, 422]
+
     """Test resource management endpoints."""
 
     async def test_list_resources_empty(self, client: AsyncClient, mock_auth):
@@ -893,7 +908,7 @@ async def test_delete_resource(self, client: AsyncClient, mock_auth):
         response = await client.get(f"/resources/{resource_data['uri']}", headers=TEST_AUTH_HEADER)
         assert response.status_code == 404
 
-    #API should probably return 409 instead of 400 for non-existent resource
+    # API should probably return 409 instead of 400 for non-existent resource
     async def test_resource_uri_conflict(self, client: AsyncClient, mock_auth):
         """Test creating resource with duplicate URI."""
         resource_data = {"uri": "duplicate/resource", "name": "duplicate", "content": "test"}
@@ -933,6 +948,7 @@ async def test_delete_resource_invalid_uri(self, client: AsyncClient, mock_auth)
         """Test DELETE /resources/{uri:path} with invalid/nonexistent URI."""
         response = await client.delete("/resources/invalid/uri", headers=TEST_AUTH_HEADER)
         assert response.status_code in [400, 404]
+
     async def test_create_resource_success_and_missing_fields(self, client: AsyncClient, mock_auth):
         """Test POST /resources - create resource success and missing fields."""
         resource_data = {"uri": "test/create", "name": "create_test", "content": "test content"}
@@ -958,6 +974,7 @@ async def test_update_resource_success_and_invalid(self, client: AsyncClient, mo
         # Invalid uri
         response = await client.put("/resources/invalid/uri", json=update_data, headers=TEST_AUTH_HEADER)
         assert response.status_code in [400, 404]
+
     async def test_resource_uri_conflict(self, client: AsyncClient, mock_auth):
         """Test creating resource with duplicate URI."""
         resource_data = {"uri": "duplicate/resource", "name": "duplicate", "content": "test"}
@@ -985,6 +1002,7 @@ async def test_create_prompt_no_body(self, client: AsyncClient, mock_auth):
         """Test POST /prompts with no body (should fail validation)."""
         response = await client.post("/prompts", headers=TEST_AUTH_HEADER)
         assert response.status_code in [400, 422]
+
     """Test prompt management endpoints."""
 
     async def test_list_prompts_empty(self, client: AsyncClient, mock_auth):
@@ -1115,7 +1133,7 @@ async def test_delete_prompt(self, client: AsyncClient, mock_auth):
         assert response.status_code == 200
         assert response.json()["status"] == "success"
 
-    #API should probably return 409 instead of 400 for non-existent prompt
+    # API should probably return 409 instead of 400 for non-existent prompt
     async def test_prompt_name_conflict(self, client: AsyncClient, mock_auth):
         """Test creating prompt with duplicate name."""
         prompt_data = {"name": "duplicate_prompt", "template": "Test", "arguments": []}
@@ -1155,6 +1173,7 @@ async def test_delete_prompt_invalid_name(self, client: AsyncClient, mock_auth):
         """Test DELETE /prompts/{name} with invalid/nonexistent name."""
         response = await client.delete("/prompts/invalid_name", headers=TEST_AUTH_HEADER)
         assert response.status_code in [400, 404]
+
     async def test_update_prompt_not_found(self, client: AsyncClient, mock_auth):
         """Test PUT /prompts/{name} with non-existent prompt returns 404 or 400."""
         fake_name = "nonexistent_prompt"
@@ -1162,6 +1181,7 @@ async def test_update_prompt_not_found(self, client: AsyncClient, mock_auth):
         assert response.status_code in [400, 404]
         resp_json = response.json()
         assert "not found" in str(resp_json).lower() or "does not exist" in str(resp_json).lower()
+
     async def test_create_prompt_duplicate_name(self, client: AsyncClient, mock_auth):
         """Test POST /prompts with duplicate name returns 409 or 400."""
         prompt_data = {"name": "duplicate_prompt_case", "template": "Test", "arguments": []}
@@ -1219,6 +1239,7 @@ async def test_toggle_gateway_status(self, client: AsyncClient, mock_auth):
         # Mock a gateway for testing
         # In real tests, you'd need to register a gateway first
         # This is skipped as it requires external connectivity
+
     async def test_update_gateway_invalid_id(self, client: AsyncClient, mock_auth):
         """Test PUT /gateways/{gateway_id} with invalid/non-existent ID returns 404 or 400."""
         fake_id = "non-existent-gateway-id"
@@ -1226,6 +1247,8 @@ async def test_update_gateway_invalid_id(self, client: AsyncClient, mock_auth):
         assert response.status_code in [400, 404]
         resp_json = response.json()
         assert "not found" in str(resp_json).lower() or "does not exist" in str(resp_json).lower()
+
+
 # -------------------------
 # Test Root APIs
 # -------------------------
@@ -1234,6 +1257,7 @@ async def test_add_root_no_body(self, client: AsyncClient, mock_auth):
         """Test POST /roots with no body (should fail validation)."""
         response = await client.post("/roots", headers=TEST_AUTH_HEADER)
         assert response.status_code in [400, 422]
+
     """Test root management endpoints."""
 
     async def test_list_roots_empty(self, client: AsyncClient, mock_auth):
@@ -1289,6 +1313,7 @@ async def test_rpc_no_body(self, client: AsyncClient, mock_auth):
         """Test POST /rpc with no body (should fail validation)."""
         response = await client.post("/rpc", headers=TEST_AUTH_HEADER)
         assert response.status_code in [400, 422]
+
     """Test utility endpoints (RPC, logging, etc)."""
 
     async def test_rpc_ping(self, client: AsyncClient, mock_auth):
@@ -1347,6 +1372,7 @@ async def test_metrics_no_auth(self, client: AsyncClient):
         """Test GET /metrics without auth header (should not error, but may be protected)."""
         response = await client.get("/metrics")
         assert response.status_code in [200, 401, 403]
+
     """Test metrics collection endpoints."""
 
     async def test_get_metrics(self, client: AsyncClient, mock_auth):
@@ -1549,14 +1575,19 @@ async def test_empty_request_body(self, client: AsyncClient, mock_auth):
         # Should have validation errors for required fields
         errors = response.json()["detail"]
         assert any("Field required" in str(error) for error in errors)
+
     async def test_internal_server_error(self, client: AsyncClient, mock_auth):
         """Simulate internal server error by patching a dependency."""
+        # First-Party
         from mcpgateway.main import app, get_db
+
         def failing_db():
             def _gen():
                 raise Exception("Simulated DB failure")
                 yield
+
             return _gen()
+
         original_override = app.dependency_overrides.get(get_db)
         app.dependency_overrides[get_db] = failing_db
         try:
@@ -1586,6 +1617,7 @@ async def test_database_integrity_error(self, client: AsyncClient, mock_auth):
         assert response.status_code == 201
         response = await client.post("/servers", json=server_data, headers=TEST_AUTH_HEADER)
         assert response.status_code in [400, 409]
+
     async def test_root_path_returns_api_info(self, client: AsyncClient, mock_settings):
         """Test GET / returns API info when UI is disabled, or redirects if UI is enabled."""
         response = await client.get("/", follow_redirects=False)
@@ -1630,6 +1662,7 @@ async def test_create_and_use_resource(self, client: AsyncClient, mock_auth):
         get_resp = await client.get(f"/resources/{resource_data['uri']}", headers=TEST_AUTH_HEADER)
         assert get_resp.status_code == 200
         assert get_resp.json()["uri"] == resource_data["uri"]
+
     """Test complete integration scenarios."""
 
     async def test_create_virtual_server_with_tools(self, client: AsyncClient, mock_auth):
diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py
index f7f63223..e1bfaecf 100644
--- a/tests/integration/test_integration.py
+++ b/tests/integration/test_integration.py
@@ -90,7 +90,7 @@ def auth_headers() -> dict[str, str]:
     metrics=ToolMetrics(**MOCK_METRICS),
     gateway_slug="default",
     original_name_slug="test-tool",
-        tags=[],
+    tags=[],
 )
 
 MOCK_SERVER = ServerRead(
diff --git a/tests/integration/test_tag_endpoints.py b/tests/integration/test_tag_endpoints.py
index dc71b424..2121176e 100644
--- a/tests/integration/test_tag_endpoints.py
+++ b/tests/integration/test_tag_endpoints.py
@@ -1,10 +1,14 @@
 # -*- coding: utf-8 -*-
 """Integration tests for tag endpoints."""
 
+# Standard
 from unittest.mock import AsyncMock, patch
-import pytest
+
+# Third-Party
 from fastapi.testclient import TestClient
+import pytest
 
+# First-Party
 from mcpgateway.main import app, require_auth
 from mcpgateway.schemas import TaggedEntity, TagInfo, TagStats
 
@@ -22,18 +26,9 @@ def test_list_tags_all_entities(test_client):
     """Test listing all tags across all entity types."""
     # Mock the tag service to return test data
     mock_tags = [
-        TagInfo(
-            name="api",
-            stats=TagStats(tools=2, resources=1, prompts=0, servers=1, gateways=0, total=4)
-        ),
-        TagInfo(
-            name="data",
-            stats=TagStats(tools=2, resources=1, prompts=0, servers=0, gateways=0, total=3)
-        ),
-        TagInfo(
-            name="test",
-            stats=TagStats(tools=1, resources=0, prompts=1, servers=0, gateways=1, total=3)
-        ),
+        TagInfo(name="api", stats=TagStats(tools=2, resources=1, prompts=0, servers=1, gateways=0, total=4)),
+        TagInfo(name="data", stats=TagStats(tools=2, resources=1, prompts=0, servers=0, gateways=0, total=3)),
+        TagInfo(name="test", stats=TagStats(tools=1, resources=0, prompts=1, servers=0, gateways=1, total=3)),
     ]
 
     with patch("mcpgateway.main.tag_service.get_all_tags", AsyncMock(return_value=mock_tags)):
@@ -60,14 +55,8 @@ def test_list_tags_all_entities(test_client):
 def test_list_tags_filtered_by_tools(test_client):
     """Test listing tags filtered by tools only."""
     mock_tags = [
-        TagInfo(
-            name="api",
-            stats=TagStats(tools=2, resources=0, prompts=0, servers=0, gateways=0, total=2)
-        ),
-        TagInfo(
-            name="data",
-            stats=TagStats(tools=1, resources=0, prompts=0, servers=0, gateways=0, total=1)
-        ),
+        TagInfo(name="api", stats=TagStats(tools=2, resources=0, prompts=0, servers=0, gateways=0, total=2)),
+        TagInfo(name="data", stats=TagStats(tools=1, resources=0, prompts=0, servers=0, gateways=0, total=1)),
     ]
 
     with patch("mcpgateway.main.tag_service.get_all_tags", AsyncMock(return_value=mock_tags)):
@@ -85,14 +74,8 @@ def test_list_tags_filtered_by_tools(test_client):
 def test_list_tags_filtered_by_multiple_types(test_client):
     """Test listing tags filtered by multiple entity types."""
     mock_tags = [
-        TagInfo(
-            name="api",
-            stats=TagStats(tools=2, resources=1, prompts=0, servers=0, gateways=0, total=3)
-        ),
-        TagInfo(
-            name="resource",
-            stats=TagStats(tools=0, resources=2, prompts=0, servers=0, gateways=0, total=2)
-        ),
+        TagInfo(name="api", stats=TagStats(tools=2, resources=1, prompts=0, servers=0, gateways=0, total=3)),
+        TagInfo(name="resource", stats=TagStats(tools=0, resources=2, prompts=0, servers=0, gateways=0, total=2)),
     ]
 
     with patch("mcpgateway.main.tag_service.get_all_tags", AsyncMock(return_value=mock_tags)):
@@ -129,14 +112,8 @@ def test_list_tags_empty_database(test_client):
 def test_admin_list_tags(test_client):
     """Test admin endpoint for listing tags."""
     mock_tags = [
-        TagInfo(
-            name="api",
-            stats=TagStats(tools=2, resources=1, prompts=1, servers=1, gateways=0, total=5)
-        ),
-        TagInfo(
-            name="test",
-            stats=TagStats(tools=1, resources=0, prompts=0, servers=0, gateways=1, total=2)
-        ),
+        TagInfo(name="api", stats=TagStats(tools=2, resources=1, prompts=1, servers=1, gateways=0, total=5)),
+        TagInfo(name="test", stats=TagStats(tools=1, resources=0, prompts=0, servers=0, gateways=1, total=2)),
     ]
 
     # Need to patch the TagService instance created in admin.py
@@ -167,14 +144,8 @@ def test_admin_list_tags(test_client):
 def test_admin_list_tags_filtered(test_client):
     """Test admin endpoint with entity type filtering."""
     mock_tags = [
-        TagInfo(
-            name="server",
-            stats=TagStats(tools=0, resources=0, prompts=0, servers=2, gateways=0, total=2)
-        ),
-        TagInfo(
-            name="gateway",
-            stats=TagStats(tools=0, resources=0, prompts=0, servers=0, gateways=1, total=1)
-        ),
+        TagInfo(name="server", stats=TagStats(tools=0, resources=0, prompts=0, servers=2, gateways=0, total=2)),
+        TagInfo(name="gateway", stats=TagStats(tools=0, resources=0, prompts=0, servers=0, gateways=1, total=1)),
     ]
 
     with patch("mcpgateway.admin.TagService") as MockTagService:
@@ -201,11 +172,7 @@ def test_list_tags_with_entities(test_client):
     ]
 
     mock_tags = [
-        TagInfo(
-            name="api",
-            stats=TagStats(tools=1, resources=1, prompts=0, servers=0, gateways=0, total=2),
-            entities=mock_entities
-        ),
+        TagInfo(name="api", stats=TagStats(tools=1, resources=1, prompts=0, servers=0, gateways=0, total=2), entities=mock_entities),
     ]
 
     with patch("mcpgateway.main.tag_service.get_all_tags", AsyncMock(return_value=mock_tags)):
@@ -277,11 +244,7 @@ def test_list_tags_with_entities_filtered_by_type(test_client):
     ]
 
     mock_tags = [
-        TagInfo(
-            name="development",
-            stats=TagStats(tools=2, resources=0, prompts=0, servers=0, gateways=0, total=2),
-            entities=mock_entities
-        ),
+        TagInfo(name="development", stats=TagStats(tools=2, resources=0, prompts=0, servers=0, gateways=0, total=2), entities=mock_entities),
     ]
 
     with patch("mcpgateway.main.tag_service.get_all_tags", AsyncMock(return_value=mock_tags)):
@@ -339,14 +302,8 @@ def test_get_entities_by_tag_multiple_types(test_client):
 def test_list_tags_statistics_accuracy(test_client):
     """Test that tag statistics are calculated correctly."""
     mock_tags = [
-        TagInfo(
-            name="api",
-            stats=TagStats(tools=3, resources=2, prompts=1, servers=1, gateways=0, total=7)
-        ),
-        TagInfo(
-            name="database",
-            stats=TagStats(tools=2, resources=1, prompts=2, servers=0, gateways=1, total=6)
-        ),
+        TagInfo(name="api", stats=TagStats(tools=3, resources=2, prompts=1, servers=1, gateways=0, total=7)),
+        TagInfo(name="database", stats=TagStats(tools=2, resources=1, prompts=2, servers=0, gateways=1, total=6)),
     ]
 
     with patch("mcpgateway.main.tag_service.get_all_tags", AsyncMock(return_value=mock_tags)):
@@ -372,11 +329,7 @@ def test_admin_tags_with_entities(test_client):
     ]
 
     mock_tags = [
-        TagInfo(
-            name="admin",
-            stats=TagStats(tools=1, resources=0, prompts=0, servers=0, gateways=0, total=1),
-            entities=mock_entities
-        ),
+        TagInfo(name="admin", stats=TagStats(tools=1, resources=0, prompts=0, servers=0, gateways=0, total=1), entities=mock_entities),
     ]
 
     with patch("mcpgateway.admin.TagService") as MockTagService:
@@ -453,11 +406,7 @@ def test_get_entities_by_tag_case_sensitive(test_client):
 def test_list_tags_empty_include_entities_false(test_client):
     """Test that entities array is empty when include_entities=false."""
     mock_tags = [
-        TagInfo(
-            name="test",
-            stats=TagStats(tools=1, resources=0, prompts=0, servers=0, gateways=0, total=1),
-            entities=[]  # Should be empty when include_entities=False
-        ),
+        TagInfo(name="test", stats=TagStats(tools=1, resources=0, prompts=0, servers=0, gateways=0, total=1), entities=[]),  # Should be empty when include_entities=False
     ]
 
     with patch("mcpgateway.main.tag_service.get_all_tags", AsyncMock(return_value=mock_tags)):
diff --git a/tests/playwright/test_htmx_interactions.py b/tests/playwright/test_htmx_interactions.py
index bc06d850..a6e3bf51 100644
--- a/tests/playwright/test_htmx_interactions.py
+++ b/tests/playwright/test_htmx_interactions.py
@@ -229,7 +229,8 @@ def test_search_functionality_realtime(self, page: Page):
         # Check if the table has been filtered (this depends on implementation)
         # If search is implemented client-side, rows should be hidden
         # If server-side, a request would be made
-        filtered_rows = page.locator('[data-testid="server-item"]:visible').count()
+        # Check that filtering actually works (unused for now but validates functionality)
+        page.locator('[data-testid="server-item"]:visible').count()
 
         # Clear search
         search_input.fill("")
diff --git a/tests/security/test_input_validation.py b/tests/security/test_input_validation.py
index 160b6367..254bd864 100644
--- a/tests/security/test_input_validation.py
+++ b/tests/security/test_input_validation.py
@@ -1780,8 +1780,9 @@ def test_constant_time_operations(self):
         """Test that validation doesn't leak timing information."""
         logger.debug("Testing constant-time validation")
 
-        import time
+        # Standard
         import statistics
+        import time
 
         valid_times = []
         invalid_times = []
diff --git a/tests/test_readme.py b/tests/test_readme.py
index c5c5bed4..d997ae16 100644
--- a/tests/test_readme.py
+++ b/tests/test_readme.py
@@ -22,11 +22,11 @@
 examples = []
 readme_path = Path(__file__).parent / "README.md"
 if readme_path.exists():
-    with open(readme_path, "r") as f:
+    with open(readme_path, "r", encoding="utf-8") as f:
         readme = f.read()
 
     # Find and parse example code blocks
-    # TODO: Parse code blocks when they exist in README.md
+    # FIXME: Parse code blocks when they exist in README.md
     # For now, this is a placeholder file
 
 
diff --git a/tests/unit/mcpgateway/cache/test_resource_cache.py b/tests/unit/mcpgateway/cache/test_resource_cache.py
index 8495faa4..392cab19 100644
--- a/tests/unit/mcpgateway/cache/test_resource_cache.py
+++ b/tests/unit/mcpgateway/cache/test_resource_cache.py
@@ -10,7 +10,6 @@
 
 # Standard
 import asyncio
-import logging
 import time
 
 # Third-Party
@@ -41,11 +40,11 @@ def test_expiration(cache):
     """Test that cache entry expires after TTL."""
     # Use a more generous sleep duration to account for timing variability
     cache.set("foo", "bar")
-    
+
     # Sleep for 1.5 seconds (50% longer than TTL) to ensure expiration
     # This accounts for system load, clock precision, and floating point issues
     time.sleep(1.5)
-    
+
     # Entry should definitely be expired now
     assert cache.get("foo") is None
 
diff --git a/tests/unit/mcpgateway/plugins/framework/loader/test_plugin_loader.py b/tests/unit/mcpgateway/plugins/framework/loader/test_plugin_loader.py
index f5d52fb8..19a5297f 100644
--- a/tests/unit/mcpgateway/plugins/framework/loader/test_plugin_loader.py
+++ b/tests/unit/mcpgateway/plugins/framework/loader/test_plugin_loader.py
@@ -8,8 +8,10 @@
 Unit tests for config and plugin loaders.
 """
 
+# Third-Party
 import pytest
 
+# First-Party
 from mcpgateway.models import Message, PromptResult, Role, TextContent
 from mcpgateway.plugins.framework.loader.config import ConfigLoader
 from mcpgateway.plugins.framework.loader.plugin import PluginLoader
@@ -36,6 +38,7 @@ def test_config_loader_load():
     assert srconfig.words[0].search == "crap"
     assert srconfig.words[0].replace == "crud"
 
+
 @pytest.mark.asyncio
 async def test_plugin_loader_load():
     """Load a plugin with the plugin loader."""
@@ -51,26 +54,27 @@ async def test_plugin_loader_load():
     assert plugin.hooks[1] == "prompt_post_fetch"
 
     context = PluginContext(GlobalContext(request_id="1", server_id="2"))
-    prompt = PromptPrehookPayload(name="test_prompt", args = {"user": "What a crapshow!"})
+    prompt = PromptPrehookPayload(name="test_prompt", args={"user": "What a crapshow!"})
     result = await plugin.prompt_pre_fetch(prompt, context=context)
     assert len(result.modified_payload.args) == 1
     assert result.modified_payload.args["user"] == "What a yikesshow!"
 
-    message=Message(content=TextContent(type="text", text="What the crud?"), role=Role.USER)
+    message = Message(content=TextContent(type="text", text="What the crud?"), role=Role.USER)
     prompt_result = PromptResult(messages=[message])
 
     payload_result = PromptPosthookPayload(name="test_prompt", result=prompt_result)
 
     result = await plugin.prompt_post_fetch(payload_result, context)
     assert len(result.modified_payload.result.messages) == 1
-    assert result.modified_payload.result.messages[0].content.text == 'What the yikes?'
+    assert result.modified_payload.result.messages[0].content.text == "What the yikes?"
 
     await loader.shutdown()
 
+
 @pytest.mark.asyncio
 async def test_plugin_loader_invalid_plugin_load():
     """Load an invalid plugin with the plugin loader."""
     config = ConfigLoader.load_config(config="./tests/unit/mcpgateway/plugins/fixtures/configs/invalid_single_plugin.yaml", use_jinja=False)
     loader = PluginLoader()
     with pytest.raises(ModuleNotFoundError):
-        plugin = await loader.load_and_instantiate_plugin(config.plugins[0])
+        await loader.load_and_instantiate_plugin(config.plugins[0])
diff --git a/tests/unit/mcpgateway/plugins/framework/test_manager.py b/tests/unit/mcpgateway/plugins/framework/test_manager.py
index 6ebdc567..66ab6c5b 100644
--- a/tests/unit/mcpgateway/plugins/framework/test_manager.py
+++ b/tests/unit/mcpgateway/plugins/framework/test_manager.py
@@ -7,11 +7,13 @@
 
 Unit tests for plugin manager.
 """
+# Third-Party
 import pytest
 
+# First-Party
 from mcpgateway.models import Message, PromptResult, Role, TextContent
 from mcpgateway.plugins.framework.manager import PluginManager
-from mcpgateway.plugins.framework.plugin_types import GlobalContext, PromptPosthookPayload, PromptPrehookPayload, ToolPreInvokePayload, ToolPostInvokePayload
+from mcpgateway.plugins.framework.plugin_types import GlobalContext, PromptPosthookPayload, PromptPrehookPayload, ToolPostInvokePayload, ToolPreInvokePayload
 from plugins.regex_filter.search_replace import SearchReplaceConfig
 
 
@@ -31,13 +33,13 @@ async def test_manager_single_transformer_prompt_plugin():
     assert len(srconfig.words) == 2
     assert srconfig.words[0].search == "crap"
     assert srconfig.words[0].replace == "crud"
-    prompt = PromptPrehookPayload(name="test_prompt", args = {"user": "What a crapshow!"})
+    prompt = PromptPrehookPayload(name="test_prompt", args={"user": "What a crapshow!"})
     global_context = GlobalContext(request_id="1", server_id="2")
     result, contexts = await manager.prompt_pre_fetch(prompt, global_context=global_context)
     assert len(result.modified_payload.args) == 1
     assert result.modified_payload.args["user"] == "What a yikesshow!"
 
-    message=Message(content=TextContent(type="text", text=result.modified_payload.args["user"]), role=Role.USER)
+    message = Message(content=TextContent(type="text", text=result.modified_payload.args["user"]), role=Role.USER)
 
     prompt_result = PromptResult(messages=[message])
 
@@ -45,9 +47,10 @@ async def test_manager_single_transformer_prompt_plugin():
 
     result, _ = await manager.prompt_post_fetch(payload_result, global_context=global_context, local_contexts=contexts)
     assert len(result.modified_payload.result.messages) == 1
-    assert result.modified_payload.result.messages[0].content.text == 'What a yikesshow!'
+    assert result.modified_payload.result.messages[0].content.text == "What a yikesshow!"
     await manager.shutdown()
 
+
 @pytest.mark.asyncio
 async def test_manager_multiple_transformer_preprompt_plugin():
     manager = PluginManager("./tests/unit/mcpgateway/plugins/fixtures/configs/valid_multiple_plugins.yaml")
@@ -78,13 +81,13 @@ async def test_manager_multiple_transformer_preprompt_plugin():
     assert srconfig.words[0].replace == "crud"
     assert manager.plugin_count == 2
 
-    prompt = PromptPrehookPayload(name="test_prompt", args = {"user": "It's always happy at the crapshow."})
+    prompt = PromptPrehookPayload(name="test_prompt", args={"user": "It's always happy at the crapshow."})
     global_context = GlobalContext(request_id="1", server_id="2")
     result, contexts = await manager.prompt_pre_fetch(prompt, global_context=global_context)
     assert len(result.modified_payload.args) == 1
     assert result.modified_payload.args["user"] == "It's always gleeful at the yikesshow."
 
-    message=Message(content=TextContent(type="text", text="It's sad at the crud bakery."), role=Role.USER)
+    message = Message(content=TextContent(type="text", text="It's sad at the crud bakery."), role=Role.USER)
 
     prompt_result = PromptResult(messages=[message])
 
@@ -95,36 +98,39 @@ async def test_manager_multiple_transformer_preprompt_plugin():
     assert result.modified_payload.result.messages[0].content.text == "It's sullen at the yikes bakery."
     await manager.shutdown()
 
+
 @pytest.mark.asyncio
 async def test_manager_no_plugins():
     manager = PluginManager("./tests/unit/mcpgateway/plugins/fixtures/configs/valid_no_plugin.yaml")
     await manager.initialize()
     assert manager.initialized
-    prompt = PromptPrehookPayload(name="test_prompt", args = {"user": "It's always happy at the crapshow."})
+    prompt = PromptPrehookPayload(name="test_prompt", args={"user": "It's always happy at the crapshow."})
     global_context = GlobalContext(request_id="1", server_id="2")
     result, _ = await manager.prompt_pre_fetch(prompt, global_context=global_context)
     assert result.continue_processing
     assert not result.modified_payload
     await manager.shutdown()
 
+
 @pytest.mark.asyncio
 async def test_manager_filter_plugins():
     manager = PluginManager("./tests/unit/mcpgateway/plugins/fixtures/configs/valid_single_filter_plugin.yaml")
     await manager.initialize()
     assert manager.initialized
-    prompt = PromptPrehookPayload(name="test_prompt", args = {"user": "innovative"})
+    prompt = PromptPrehookPayload(name="test_prompt", args={"user": "innovative"})
     global_context = GlobalContext(request_id="1", server_id="2")
     result, _ = await manager.prompt_pre_fetch(prompt, global_context=global_context)
     assert not result.continue_processing
     assert result.violation
     await manager.shutdown()
 
+
 @pytest.mark.asyncio
 async def test_manager_multi_filter_plugins():
     manager = PluginManager("./tests/unit/mcpgateway/plugins/fixtures/configs/valid_multiple_plugins_filter.yaml")
     await manager.initialize()
     assert manager.initialized
-    prompt = PromptPrehookPayload(name="test_prompt", args = {"user": "innovative crapshow."})
+    prompt = PromptPrehookPayload(name="test_prompt", args={"user": "innovative crapshow."})
     global_context = GlobalContext(request_id="1", server_id="2")
     result, _ = await manager.prompt_pre_fetch(prompt, global_context=global_context)
     assert not result.continue_processing
diff --git a/tests/unit/mcpgateway/plugins/framework/test_registry.py b/tests/unit/mcpgateway/plugins/framework/test_registry.py
index cebe8d33..95c4e172 100644
--- a/tests/unit/mcpgateway/plugins/framework/test_registry.py
+++ b/tests/unit/mcpgateway/plugins/framework/test_registry.py
@@ -7,12 +7,15 @@
 
 Unit tests for plugin registry.
 """
+# Third-Party
 import pytest
 
+# First-Party
 from mcpgateway.plugins.framework.loader.config import ConfigLoader
 from mcpgateway.plugins.framework.loader.plugin import PluginLoader
 from mcpgateway.plugins.framework.registry import PluginInstanceRegistry
 
+
 @pytest.mark.asyncio
 async def test_registry_register():
     """Load a plugin with the plugin loader."""
diff --git a/tests/unit/mcpgateway/plugins/framework/test_utils.py b/tests/unit/mcpgateway/plugins/framework/test_utils.py
index 830b1fe0..77d92ee8 100644
--- a/tests/unit/mcpgateway/plugins/framework/test_utils.py
+++ b/tests/unit/mcpgateway/plugins/framework/test_utils.py
@@ -7,10 +7,10 @@
 
 Unit tests for utilities.
 """
-from mcpgateway.plugins.framework.utils import pre_prompt_matches, matches, post_prompt_matches
+# First-Party
 from mcpgateway.plugins.framework.models import PluginCondition
-from mcpgateway.plugins.framework.plugin_types import GlobalContext, PromptPosthookPayload, PromptPrehookPayload
-
+from mcpgateway.plugins.framework.plugin_types import GlobalContext, PromptPrehookPayload
+from mcpgateway.plugins.framework.utils import matches, pre_prompt_matches
 
 
 def test_server_ids():
diff --git a/tests/unit/mcpgateway/plugins/plugins/pii_filter/test_pii_filter.py b/tests/unit/mcpgateway/plugins/plugins/pii_filter/test_pii_filter.py
index 9eae9fbd..ef30286b 100644
--- a/tests/unit/mcpgateway/plugins/plugins/pii_filter/test_pii_filter.py
+++ b/tests/unit/mcpgateway/plugins/plugins/pii_filter/test_pii_filter.py
@@ -6,11 +6,12 @@
 Authors: Mihai Criveti
 """
 
+# Third-Party
 import pytest
-from typing import Dict, Any
 
+# First-Party
 from mcpgateway.models import Message, PromptResult, Role, TextContent
-from mcpgateway.plugins.framework.models import PluginConfig, PluginMode, HookType
+from mcpgateway.plugins.framework.models import HookType, PluginConfig, PluginMode
 from mcpgateway.plugins.framework.plugin_types import (
     GlobalContext,
     PluginContext,
@@ -20,11 +21,11 @@
 
 # Import the PII Filter plugin
 from plugins.pii_filter.pii_filter import (
-    PIIFilterPlugin,
-    PIIFilterConfig,
+    MaskingStrategy,
     PIIDetector,
+    PIIFilterConfig,
+    PIIFilterPlugin,
     PIIType,
-    MaskingStrategy,
 )
 
 
@@ -150,10 +151,7 @@ def test_aws_key_detection(self):
 
     def test_whitelist_functionality(self):
         """Test that whitelisted patterns are not detected."""
-        config = PIIFilterConfig(
-            detect_email=True,
-            whitelist_patterns=["test@example.com", "admin@localhost"]
-        )
+        config = PIIFilterConfig(detect_email=True, whitelist_patterns=["test@example.com", "admin@localhost"])
         detector = PIIDetector(config)
 
         # Whitelisted emails should not be detected
@@ -168,11 +166,7 @@ def test_whitelist_functionality(self):
 
     def test_masking_strategies(self):
         """Test different masking strategies."""
-        config = PIIFilterConfig(
-            detect_ssn=True,
-            detect_phone=False,  # Disable phone detection
-            detect_bank_account=False  # Disable bank account detection
-        )
+        config = PIIFilterConfig(detect_ssn=True, detect_phone=False, detect_bank_account=False)  # Disable phone detection  # Disable bank account detection
         detector = PIIDetector(config)
 
         # Test REDACT strategy (SSN uses PARTIAL by default in the pattern)
@@ -183,13 +177,7 @@ def test_masking_strategies(self):
         assert "123-45-6789" not in masked
 
         # Test PARTIAL strategy
-        config = PIIFilterConfig(
-            detect_email=True,
-            detect_ssn=False,  # Disable SSN for email test
-            detect_phone=False,
-            detect_bank_account=False,
-            default_mask_strategy=MaskingStrategy.PARTIAL
-        )
+        config = PIIFilterConfig(detect_email=True, detect_ssn=False, detect_phone=False, detect_bank_account=False, default_mask_strategy=MaskingStrategy.PARTIAL)  # Disable SSN for email test
         detector = PIIDetector(config)
         text = "Email: john.doe@example.com"
         detections = detector.detect(text)
@@ -199,10 +187,7 @@ def test_masking_strategies(self):
 
         # Test REMOVE strategy
         config = PIIFilterConfig(
-            detect_ssn=True,
-            detect_phone=False,  # Disable phone detection
-            detect_bank_account=False,  # Disable bank account detection
-            default_mask_strategy=MaskingStrategy.REMOVE
+            detect_ssn=True, detect_phone=False, detect_bank_account=False, default_mask_strategy=MaskingStrategy.REMOVE  # Disable phone detection  # Disable bank account detection
         )
         detector = PIIDetector(config)
         text = "SSN: 123-45-6789"
@@ -214,11 +199,7 @@ def test_masking_strategies(self):
 
     def test_multiple_pii_detection(self):
         """Test detection of multiple PII types in one text."""
-        config = PIIFilterConfig(
-            detect_ssn=True,
-            detect_email=True,
-            detect_phone=True
-        )
+        config = PIIFilterConfig(detect_ssn=True, detect_email=True, detect_phone=True)
         detector = PIIDetector(config)
 
         text = "Contact John at john@example.com or 555-123-4567. SSN: 123-45-6789"
@@ -257,7 +238,7 @@ def plugin_config(self) -> PluginConfig:
                 "block_on_detection": False,
                 "log_detections": True,
                 "include_detection_details": True,
-            }
+            },
         )
 
     @pytest.mark.asyncio
@@ -267,13 +248,7 @@ async def test_prompt_pre_fetch_with_pii(self, plugin_config):
         context = PluginContext(GlobalContext(request_id="test-1"))
 
         # Create payload with PII
-        payload = PromptPrehookPayload(
-            name="test_prompt",
-            args={
-                "user_input": "My email is john@example.com and SSN is 123-45-6789",
-                "safe_input": "This has no PII"
-            }
-        )
+        payload = PromptPrehookPayload(name="test_prompt", args={"user_input": "My email is john@example.com and SSN is 123-45-6789", "safe_input": "This has no PII"})
 
         result = await plugin.prompt_pre_fetch(payload, context)
 
@@ -296,10 +271,7 @@ async def test_prompt_pre_fetch_blocking(self, plugin_config):
         plugin = PIIFilterPlugin(plugin_config)
         context = PluginContext(GlobalContext(request_id="test-2"))
 
-        payload = PromptPrehookPayload(
-            name="test_prompt",
-            args={"input": "My SSN is 123-45-6789"}
-        )
+        payload = PromptPrehookPayload(name="test_prompt", args={"input": "My SSN is 123-45-6789"})
 
         result = await plugin.prompt_pre_fetch(payload, context)
 
@@ -317,26 +289,11 @@ async def test_prompt_post_fetch(self, plugin_config):
 
         # Create messages with PII
         messages = [
-            Message(
-                role=Role.USER,
-                content=TextContent(
-                    type="text",
-                    text="Contact me at john@example.com or 555-123-4567"
-                )
-            ),
-            Message(
-                role=Role.ASSISTANT,
-                content=TextContent(
-                    type="text",
-                    text="I'll reach you at the provided contact: AKIAIOSFODNN7EXAMPLE"
-                )
-            )
+            Message(role=Role.USER, content=TextContent(type="text", text="Contact me at john@example.com or 555-123-4567")),
+            Message(role=Role.ASSISTANT, content=TextContent(type="text", text="I'll reach you at the provided contact: AKIAIOSFODNN7EXAMPLE")),
         ]
 
-        payload = PromptPosthookPayload(
-            name="test_prompt",
-            result=PromptResult(messages=messages)
-        )
+        payload = PromptPosthookPayload(name="test_prompt", result=PromptResult(messages=messages))
 
         result = await plugin.prompt_post_fetch(payload, context)
 
@@ -359,10 +316,7 @@ async def test_no_pii_detection(self, plugin_config):
         plugin = PIIFilterPlugin(plugin_config)
         context = PluginContext(GlobalContext(request_id="test-4"))
 
-        payload = PromptPrehookPayload(
-            name="test_prompt",
-            args={"input": "This text has no sensitive information"}
-        )
+        payload = PromptPrehookPayload(name="test_prompt", args={"input": "This text has no sensitive information"})
 
         result = await plugin.prompt_pre_fetch(payload, context)
 
@@ -374,23 +328,12 @@ async def test_no_pii_detection(self, plugin_config):
     async def test_custom_patterns(self, plugin_config):
         """Test custom PII pattern detection."""
         # Add custom pattern
-        plugin_config.config["custom_patterns"] = [
-            {
-                "type": "custom",
-                "pattern": r"\bEMP\d{6}\b",
-                "description": "Employee ID",
-                "mask_strategy": "redact",
-                "enabled": True
-            }
-        ]
+        plugin_config.config["custom_patterns"] = [{"type": "custom", "pattern": r"\bEMP\d{6}\b", "description": "Employee ID", "mask_strategy": "redact", "enabled": True}]
 
         plugin = PIIFilterPlugin(plugin_config)
         context = PluginContext(GlobalContext(request_id="test-5"))
 
-        payload = PromptPrehookPayload(
-            name="test_prompt",
-            args={"input": "Employee ID: EMP123456"}
-        )
+        payload = PromptPrehookPayload(name="test_prompt", args={"input": "Employee ID: EMP123456"})
 
         result = await plugin.prompt_pre_fetch(payload, context)
 
@@ -408,10 +351,7 @@ async def test_permissive_mode(self, plugin_config):
         plugin = PIIFilterPlugin(plugin_config)
         context = PluginContext(GlobalContext(request_id="test-6"))
 
-        payload = PromptPrehookPayload(
-            name="test_prompt",
-            args={"input": "SSN: 123-45-6789"}
-        )
+        payload = PromptPrehookPayload(name="test_prompt", args={"input": "SSN: 123-45-6789"})
 
         result = await plugin.prompt_pre_fetch(payload, context)
 
@@ -425,6 +365,7 @@ async def test_permissive_mode(self, plugin_config):
 @pytest.mark.asyncio
 async def test_integration_with_manager():
     """Test the PII Filter plugin with the plugin manager."""
+    # First-Party
     from mcpgateway.plugins.framework.manager import PluginManager
 
     # Create a test configuration
@@ -440,38 +381,22 @@ async def test_integration_with_manager():
                 "tags": ["security", "pii"],
                 "mode": "enforce",
                 "priority": 10,
-                "conditions": [
-                    {
-                        "prompts": ["test_prompt"],
-                        "server_ids": [],
-                        "tenant_ids": []
-                    }
-                ],
-                "config": {
-                    "detect_ssn": True,
-                    "detect_email": True,
-                    "default_mask_strategy": "partial",
-                    "block_on_detection": False,
-                    "log_detections": True,
-                    "include_detection_details": True
-                }
+                "conditions": [{"prompts": ["test_prompt"], "server_ids": [], "tenant_ids": []}],
+                "config": {"detect_ssn": True, "detect_email": True, "default_mask_strategy": "partial", "block_on_detection": False, "log_detections": True, "include_detection_details": True},
             }
         ],
         "plugin_dirs": [],
-        "plugin_settings": {
-            "parallel_execution_within_band": False,
-            "plugin_timeout": 30,
-            "fail_on_plugin_error": False,
-            "enable_plugin_api": True,
-            "plugin_health_check_interval": 60
-        }
+        "plugin_settings": {"parallel_execution_within_band": False, "plugin_timeout": 30, "fail_on_plugin_error": False, "enable_plugin_api": True, "plugin_health_check_interval": 60},
     }
 
     # Save config to a temp file and initialize manager
+    # Standard
     import tempfile
+
+    # Third-Party
     import yaml
 
-    with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
+    with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f:
         yaml.dump(config_dict, f)
         config_path = f.name
 
@@ -480,10 +405,7 @@ async def test_integration_with_manager():
         await manager.initialize()
 
         # Test with PII in prompt
-        payload = PromptPrehookPayload(
-            name="test_prompt",
-            args={"input": "Email: test@example.com, SSN: 123-45-6789"}
-        )
+        payload = PromptPrehookPayload(name="test_prompt", args={"input": "Email: test@example.com, SSN: 123-45-6789"})
 
         global_context = GlobalContext(request_id="test-manager")
         result, contexts = await manager.prompt_pre_fetch(payload, global_context)
@@ -495,7 +417,9 @@ async def test_integration_with_manager():
 
         await manager.shutdown()
     finally:
+        # Standard
         import os
+
         os.unlink(config_path)
 
 
diff --git a/tests/unit/mcpgateway/services/test_gateway_service.py b/tests/unit/mcpgateway/services/test_gateway_service.py
index 988f7da6..aad63a34 100644
--- a/tests/unit/mcpgateway/services/test_gateway_service.py
+++ b/tests/unit/mcpgateway/services/test_gateway_service.py
@@ -278,15 +278,9 @@ async def test_register_gateway_with_auth(self, gateway_service, test_db, monkey
             lambda x: mock_model,
         )
 
-        gateway_create = GatewayCreate(
-            name="auth_gateway",
-            url="http://example.com/gateway",
-            description="Gateway with auth",
-            auth_type="bearer",
-            auth_token="test-token"
-        )
+        gateway_create = GatewayCreate(name="auth_gateway", url="http://example.com/gateway", description="Gateway with auth", auth_type="bearer", auth_token="test-token")
 
-        result = await gateway_service.register_gateway(test_db, gateway_create)
+        await gateway_service.register_gateway(test_db, gateway_create)
 
         test_db.add.assert_called_once()
         test_db.commit.assert_called_once()
@@ -306,16 +300,10 @@ async def test_register_gateway_with_tools(self, gateway_service, test_db, monke
         test_db.refresh = Mock()
 
         # Mock tools returned from gateway
+        # First-Party
         from mcpgateway.schemas import ToolCreate
-        mock_tools = [
-            ToolCreate(
-                name="test_tool",
-                description="A test tool",
-                integration_type="REST",
-                request_type="POST",
-                input_schema={"type": "object"}
-            )
-        ]
+
+        mock_tools = [ToolCreate(name="test_tool", description="A test tool", integration_type="REST", request_type="POST", input_schema={"type": "object"})]
 
         gateway_service._initialize_gateway = AsyncMock(
             return_value=(
@@ -344,7 +332,7 @@ async def test_register_gateway_with_tools(self, gateway_service, test_db, monke
             description="Gateway with tools",
         )
 
-        result = await gateway_service.register_gateway(test_db, gateway_create)
+        await gateway_service.register_gateway(test_db, gateway_create)
 
         test_db.add.assert_called_once()
         # Verify that tools were created and added to the gateway
@@ -386,9 +374,7 @@ async def test_register_gateway_database_error(self, gateway_service, test_db):
         test_db.commit = Mock(side_effect=Exception("Database error"))
         test_db.rollback = Mock()
 
-        gateway_service._initialize_gateway = AsyncMock(
-            return_value=({"tools": {"listChanged": True}}, [])
-        )
+        gateway_service._initialize_gateway = AsyncMock(return_value=({"tools": {"listChanged": True}}, []))
 
         gateway_create = GatewayCreate(
             name="test_gateway",
@@ -406,9 +392,7 @@ async def test_register_gateway_value_error(self, gateway_service, test_db):
         """Test ValueError during gateway registration."""
         test_db.execute = Mock(return_value=_make_execute_result(scalar=None))
 
-        gateway_service._initialize_gateway = AsyncMock(
-            side_effect=ValueError("Invalid gateway configuration")
-        )
+        gateway_service._initialize_gateway = AsyncMock(side_effect=ValueError("Invalid gateway configuration"))
 
         gateway_create = GatewayCreate(
             name="test_gateway",
@@ -426,9 +410,7 @@ async def test_register_gateway_runtime_error(self, gateway_service, test_db):
         """Test RuntimeError during gateway registration."""
         test_db.execute = Mock(return_value=_make_execute_result(scalar=None))
 
-        gateway_service._initialize_gateway = AsyncMock(
-            side_effect=RuntimeError("Runtime error occurred")
-        )
+        gateway_service._initialize_gateway = AsyncMock(side_effect=RuntimeError("Runtime error occurred"))
 
         gateway_create = GatewayCreate(
             name="test_gateway",
@@ -444,15 +426,14 @@ async def test_register_gateway_runtime_error(self, gateway_service, test_db):
     @pytest.mark.asyncio
     async def test_register_gateway_integrity_error(self, gateway_service, test_db):
         """Test IntegrityError during gateway registration."""
+        # Third-Party
         from sqlalchemy.exc import IntegrityError as SQLIntegrityError
 
         test_db.execute = Mock(return_value=_make_execute_result(scalar=None))
         test_db.add = Mock()
         test_db.commit = Mock(side_effect=SQLIntegrityError("statement", "params", "orig"))
 
-        gateway_service._initialize_gateway = AsyncMock(
-            return_value=({"tools": {"listChanged": True}}, [])
-        )
+        gateway_service._initialize_gateway = AsyncMock(return_value=({"tools": {"listChanged": True}}, []))
 
         gateway_create = GatewayCreate(
             name="test_gateway",
@@ -476,9 +457,7 @@ async def test_register_gateway_masked_auth_value(self, gateway_service, test_db
         test_db.commit = Mock()
         test_db.refresh = Mock()
 
-        gateway_service._initialize_gateway = AsyncMock(
-            return_value=({"tools": {"listChanged": True}}, [])
-        )
+        gateway_service._initialize_gateway = AsyncMock(return_value=({"tools": {"listChanged": True}}, []))
         gateway_service._notify_gateway_added = AsyncMock()
 
         mock_model = Mock()
@@ -493,14 +472,10 @@ async def test_register_gateway_masked_auth_value(self, gateway_service, test_db
         # Mock settings for masked auth value
         with patch("mcpgateway.services.gateway_service.settings.masked_auth_value", "***MASKED***"):
             gateway_create = GatewayCreate(
-                name="auth_gateway",
-                url="http://example.com/gateway",
-                description="Gateway with masked auth",
-                auth_type="bearer",
-                auth_token="***MASKED***"  # This should not update the auth_value
+                name="auth_gateway", url="http://example.com/gateway", description="Gateway with masked auth", auth_type="bearer", auth_token="***MASKED***"  # This should not update the auth_value
             )
 
-            result = await gateway_service.register_gateway(test_db, gateway_create)
+            await gateway_service.register_gateway(test_db, gateway_create)
 
         test_db.add.assert_called_once()
         test_db.commit.assert_called_once()
@@ -514,9 +489,7 @@ async def test_register_gateway_exception_rollback(self, gateway_service, test_d
         test_db.commit = Mock(side_effect=Exception("Commit failed"))
         test_db.rollback = Mock()
 
-        gateway_service._initialize_gateway = AsyncMock(
-            return_value=({"tools": {"listChanged": True}}, [])
-        )
+        gateway_service._initialize_gateway = AsyncMock(return_value=({"tools": {"listChanged": True}}, []))
 
         gateway_create = GatewayCreate(
             name="test_gateway",
@@ -550,20 +523,12 @@ async def test_register_gateway_with_existing_tools(self, gateway_service, test_
         test_db.refresh = Mock()
 
         # Mock tools returned from gateway
+        # First-Party
         from mcpgateway.schemas import ToolCreate
-        mock_tools = [
-            ToolCreate(
-                name="existing_tool",  # This tool already exists
-                description="An existing tool",
-                integration_type="REST",
-                request_type="POST",
-                input_schema={"type": "object"}
-            )
-        ]
 
-        gateway_service._initialize_gateway = AsyncMock(
-            return_value=({"tools": {"listChanged": True}}, mock_tools)
-        )
+        mock_tools = [ToolCreate(name="existing_tool", description="An existing tool", integration_type="REST", request_type="POST", input_schema={"type": "object"})]  # This tool already exists
+
+        gateway_service._initialize_gateway = AsyncMock(return_value=({"tools": {"listChanged": True}}, mock_tools))
         gateway_service._notify_gateway_added = AsyncMock()
 
         mock_model = Mock()
@@ -581,7 +546,7 @@ async def test_register_gateway_with_existing_tools(self, gateway_service, test_
             description="Gateway with existing tools",
         )
 
-        result = await gateway_service.register_gateway(test_db, gateway_create)
+        await gateway_service.register_gateway(test_db, gateway_create)
 
         test_db.add.assert_called_once()
         # Verify that a tool was created for the gateway (the service creates new tools, not reuse existing ones)
@@ -936,23 +901,18 @@ async def test_update_gateway_with_auth_update(self, gateway_service, mock_gatew
         test_db.commit = Mock()
         test_db.refresh = Mock()
 
-        gateway_service._initialize_gateway = AsyncMock(
-            return_value=({"tools": {"listChanged": True}}, [])
-        )
+        gateway_service._initialize_gateway = AsyncMock(return_value=({"tools": {"listChanged": True}}, []))
         gateway_service._notify_gateway_updated = AsyncMock()
 
         # Mock settings for auth value checking
         with patch("mcpgateway.services.gateway_service.settings.masked_auth_value", "***MASKED***"):
-            gateway_update = GatewayUpdate(
-                auth_type="bearer",
-                auth_token="new-token"
-            )
+            gateway_update = GatewayUpdate(auth_type="bearer", auth_token="new-token")
 
             mock_gateway_read = MagicMock()
             mock_gateway_read.masked.return_value = mock_gateway_read
 
             with patch("mcpgateway.services.gateway_service.GatewayRead.model_validate", return_value=mock_gateway_read):
-                result = await gateway_service.update_gateway(test_db, 1, gateway_update)
+                await gateway_service.update_gateway(test_db, 1, gateway_update)
 
             # Check that auth_type was updated
             assert mock_gateway.auth_type == "bearer"
@@ -969,9 +929,7 @@ async def test_update_gateway_clear_auth(self, gateway_service, mock_gateway, te
         test_db.commit = Mock()
         test_db.refresh = Mock()
 
-        gateway_service._initialize_gateway = AsyncMock(
-            return_value=({"tools": {"listChanged": True}}, [])
-        )
+        gateway_service._initialize_gateway = AsyncMock(return_value=({"tools": {"listChanged": True}}, []))
         gateway_service._notify_gateway_updated = AsyncMock()
 
         gateway_update = GatewayUpdate(auth_type="")
@@ -980,7 +938,7 @@ async def test_update_gateway_clear_auth(self, gateway_service, mock_gateway, te
         mock_gateway_read.masked.return_value = mock_gateway_read
 
         with patch("mcpgateway.services.gateway_service.GatewayRead.model_validate", return_value=mock_gateway_read):
-            result = await gateway_service.update_gateway(test_db, 1, gateway_update)
+            await gateway_service.update_gateway(test_db, 1, gateway_update)
 
         assert mock_gateway.auth_type == ""
         assert mock_gateway.auth_value == ""
@@ -1005,27 +963,15 @@ async def test_update_gateway_url_change_with_tools(self, gateway_service, mock_
         test_db.refresh = Mock()
 
         # Mock new tools from gateway
+        # First-Party
         from mcpgateway.schemas import ToolCreate
+
         new_tools = [
-            ToolCreate(
-                name="existing_tool",
-                description="Updated tool",
-                integration_type="REST",
-                request_type="POST",
-                input_schema={"type": "object"}
-            ),
-            ToolCreate(
-                name="new_tool",
-                description="Brand new tool",
-                integration_type="REST",
-                request_type="POST",
-                input_schema={"type": "object"}
-            )
+            ToolCreate(name="existing_tool", description="Updated tool", integration_type="REST", request_type="POST", input_schema={"type": "object"}),
+            ToolCreate(name="new_tool", description="Brand new tool", integration_type="REST", request_type="POST", input_schema={"type": "object"}),
         ]
 
-        gateway_service._initialize_gateway = AsyncMock(
-            return_value=({"tools": {"listChanged": True}}, new_tools)
-        )
+        gateway_service._initialize_gateway = AsyncMock(return_value=({"tools": {"listChanged": True}}, new_tools))
         gateway_service._notify_gateway_updated = AsyncMock()
 
         gateway_update = GatewayUpdate(url="http://example.com/new-url")
@@ -1034,7 +980,7 @@ async def test_update_gateway_url_change_with_tools(self, gateway_service, mock_
         mock_gateway_read.masked.return_value = mock_gateway_read
 
         with patch("mcpgateway.services.gateway_service.GatewayRead.model_validate", return_value=mock_gateway_read):
-            result = await gateway_service.update_gateway(test_db, 1, gateway_update)
+            await gateway_service.update_gateway(test_db, 1, gateway_update)
 
         assert mock_gateway.url == "http://example.com/new-url"
         gateway_service._initialize_gateway.assert_called_once()
@@ -1049,9 +995,7 @@ async def test_update_gateway_url_initialization_failure(self, gateway_service,
         test_db.refresh = Mock()
 
         # Mock initialization failure
-        gateway_service._initialize_gateway = AsyncMock(
-            side_effect=GatewayConnectionError("Connection failed")
-        )
+        gateway_service._initialize_gateway = AsyncMock(side_effect=GatewayConnectionError("Connection failed"))
         gateway_service._notify_gateway_updated = AsyncMock()
 
         gateway_update = GatewayUpdate(url="http://example.com/bad-url")
@@ -1061,7 +1005,7 @@ async def test_update_gateway_url_initialization_failure(self, gateway_service,
 
         # Should not raise exception, just log warning
         with patch("mcpgateway.services.gateway_service.GatewayRead.model_validate", return_value=mock_gateway_read):
-            result = await gateway_service.update_gateway(test_db, 1, gateway_update)
+            await gateway_service.update_gateway(test_db, 1, gateway_update)
 
         assert mock_gateway.url == "http://example.com/bad-url"
         test_db.commit.assert_called_once()
@@ -1083,7 +1027,7 @@ async def test_update_gateway_partial_update(self, gateway_service, mock_gateway
         mock_gateway_read.masked.return_value = mock_gateway_read
 
         with patch("mcpgateway.services.gateway_service.GatewayRead.model_validate", return_value=mock_gateway_read):
-            result = await gateway_service.update_gateway(test_db, 1, gateway_update)
+            await gateway_service.update_gateway(test_db, 1, gateway_update)
 
         # Only description should be updated
         assert mock_gateway.description == "New description only"
@@ -1142,18 +1086,13 @@ async def test_update_gateway_with_masked_auth(self, gateway_service, mock_gatew
 
         # Mock settings for masked auth value
         with patch("mcpgateway.services.gateway_service.settings.masked_auth_value", "***MASKED***"):
-            gateway_update = GatewayUpdate(
-                auth_type="bearer",
-                auth_token="***MASKED***",  # This should not update the auth_value
-                auth_password="***MASKED***",
-                auth_header_value="***MASKED***"
-            )
+            gateway_update = GatewayUpdate(auth_type="bearer", auth_token="***MASKED***", auth_password="***MASKED***", auth_header_value="***MASKED***")  # This should not update the auth_value
 
             mock_gateway_read = MagicMock()
             mock_gateway_read.masked.return_value = mock_gateway_read
 
             with patch("mcpgateway.services.gateway_service.GatewayRead.model_validate", return_value=mock_gateway_read):
-                result = await gateway_service.update_gateway(test_db, 1, gateway_update)
+                await gateway_service.update_gateway(test_db, 1, gateway_update)
 
             # Auth value should remain unmodified since all values were masked
             assert mock_gateway.auth_value == "existing-token"
@@ -1162,6 +1101,7 @@ async def test_update_gateway_with_masked_auth(self, gateway_service, mock_gatew
     @pytest.mark.asyncio
     async def test_update_gateway_integrity_error(self, gateway_service, mock_gateway, test_db):
         """Test IntegrityError during gateway update."""
+        # Third-Party
         from sqlalchemy.exc import IntegrityError as SQLIntegrityError
 
         test_db.get = Mock(return_value=mock_gateway)
@@ -1183,9 +1123,7 @@ async def test_update_gateway_with_transport_change(self, gateway_service, mock_
         test_db.commit = Mock()
         test_db.refresh = Mock()
 
-        gateway_service._initialize_gateway = AsyncMock(
-            return_value=({"tools": {"listChanged": True}}, [])
-        )
+        gateway_service._initialize_gateway = AsyncMock(return_value=({"tools": {"listChanged": True}}, []))
         gateway_service._notify_gateway_updated = AsyncMock()
 
         gateway_update = GatewayUpdate(transport="STREAMABLEHTTP")
@@ -1194,7 +1132,7 @@ async def test_update_gateway_with_transport_change(self, gateway_service, mock_
         mock_gateway_read.masked.return_value = mock_gateway_read
 
         with patch("mcpgateway.services.gateway_service.GatewayRead.model_validate", return_value=mock_gateway_read):
-            result = await gateway_service.update_gateway(test_db, 1, gateway_update)
+            await gateway_service.update_gateway(test_db, 1, gateway_update)
 
         assert mock_gateway.transport == "STREAMABLEHTTP"
         test_db.commit.assert_called_once()
@@ -1222,7 +1160,7 @@ async def test_update_gateway_without_auth_type_attr(self, gateway_service, test
         mock_gateway_read.masked.return_value = mock_gateway_read
 
         with patch("mcpgateway.services.gateway_service.GatewayRead.model_validate", return_value=mock_gateway_read):
-            result = await gateway_service.update_gateway(test_db, 1, gateway_update)
+            await gateway_service.update_gateway(test_db, 1, gateway_update)
 
         assert mock_gateway_no_auth.description == "New description"
         test_db.commit.assert_called_once()
diff --git a/tests/unit/mcpgateway/services/test_gateway_service_extended.py b/tests/unit/mcpgateway/services/test_gateway_service_extended.py
index b40b8bd0..f5a154dc 100644
--- a/tests/unit/mcpgateway/services/test_gateway_service_extended.py
+++ b/tests/unit/mcpgateway/services/test_gateway_service_extended.py
@@ -16,22 +16,15 @@
 # Standard
 import asyncio
 from datetime import datetime, timezone
-from unittest.mock import AsyncMock, MagicMock, Mock, patch
-from typing import Dict, Any
+from unittest.mock import AsyncMock, MagicMock, patch
 
 # Third-Party
-import httpx
 import pytest
 
 # First-Party
-from mcpgateway.db import Gateway as DbGateway
-from mcpgateway.db import Tool as DbTool
-from mcpgateway.schemas import GatewayCreate, GatewayUpdate, ToolCreate
+from mcpgateway.schemas import ToolCreate
 from mcpgateway.services.gateway_service import (
     GatewayConnectionError,
-    GatewayError,
-    GatewayNameConflictError,
-    GatewayNotFoundError,
     GatewayService,
 )
 
@@ -49,7 +42,9 @@ def _make_execute_result(*, scalar=None, scalars_list=None):
 @pytest.fixture(autouse=True)
 def _bypass_validation(monkeypatch):
     """Bypass Pydantic validation for mock objects."""
+    # First-Party
     from mcpgateway.schemas import GatewayRead
+
     monkeypatch.setattr(GatewayRead, "model_validate", staticmethod(lambda x: x))
 
 
@@ -61,9 +56,11 @@ async def test_initialize_gateway_sse_transport(self):
         """Test _initialize_gateway with SSE transport."""
         service = GatewayService()
 
-        with patch('mcpgateway.services.gateway_service.sse_client') as mock_sse_client, \
-             patch('mcpgateway.services.gateway_service.ClientSession') as mock_session, \
-             patch('mcpgateway.services.gateway_service.decode_auth') as mock_decode:
+        with (
+            patch("mcpgateway.services.gateway_service.sse_client") as mock_sse_client,
+            patch("mcpgateway.services.gateway_service.ClientSession") as mock_session,
+            patch("mcpgateway.services.gateway_service.decode_auth") as mock_decode,
+        ):
 
             # Setup mocks
             mock_decode.return_value = {"Authorization": "Bearer token"}
@@ -89,11 +86,7 @@ async def test_initialize_gateway_sse_transport(self):
 
             mock_tools_response = MagicMock()
             mock_tool = MagicMock()
-            mock_tool.model_dump.return_value = {
-                "name": "test_tool",
-                "description": "Test tool",
-                "inputSchema": {}
-            }
+            mock_tool.model_dump.return_value = {"name": "test_tool", "description": "Test tool", "inputSchema": {}}
             mock_tools_response.tools = [mock_tool]
             mock_session_instance.list_tools.return_value = mock_tools_response
 
@@ -101,11 +94,7 @@ async def test_initialize_gateway_sse_transport(self):
             service._validate_gateway_url = AsyncMock(return_value=True)
 
             # Execute
-            capabilities, tools = await service._initialize_gateway(
-                "http://test.example.com",
-                {"Authorization": "Bearer token"},
-                "SSE"
-            )
+            capabilities, tools = await service._initialize_gateway("http://test.example.com", {"Authorization": "Bearer token"}, "SSE")
 
             # Verify
             assert capabilities == {"protocolVersion": "0.1.0"}
@@ -117,9 +106,11 @@ async def test_initialize_gateway_streamablehttp_transport(self):
         """Test _initialize_gateway with StreamableHTTP transport."""
         service = GatewayService()
 
-        with patch('mcpgateway.services.gateway_service.streamablehttp_client') as mock_http_client, \
-             patch('mcpgateway.services.gateway_service.ClientSession') as mock_session, \
-             patch('mcpgateway.services.gateway_service.decode_auth') as mock_decode:
+        with (
+            patch("mcpgateway.services.gateway_service.streamablehttp_client") as mock_http_client,
+            patch("mcpgateway.services.gateway_service.ClientSession") as mock_session,
+            patch("mcpgateway.services.gateway_service.decode_auth") as mock_decode,
+        ):
 
             # Setup mocks
             mock_decode.return_value = {"Authorization": "Bearer token"}
@@ -145,20 +136,12 @@ async def test_initialize_gateway_streamablehttp_transport(self):
 
             mock_tools_response = MagicMock()
             mock_tool = MagicMock()
-            mock_tool.model_dump.return_value = {
-                "name": "test_tool",
-                "description": "Test tool",
-                "inputSchema": {}
-            }
+            mock_tool.model_dump.return_value = {"name": "test_tool", "description": "Test tool", "inputSchema": {}}
             mock_tools_response.tools = [mock_tool]
             mock_session_instance.list_tools.return_value = mock_tools_response
 
             # Execute
-            capabilities, tools = await service._initialize_gateway(
-                "http://test.example.com",
-                {"Authorization": "Bearer token"},
-                "streamablehttp"
-            )
+            capabilities, tools = await service._initialize_gateway("http://test.example.com", {"Authorization": "Bearer token"}, "streamablehttp")
 
             # Verify
             assert capabilities == {"protocolVersion": "0.1.0"}
@@ -170,17 +153,13 @@ async def test_initialize_gateway_connection_error(self):
         """Test _initialize_gateway with connection error."""
         service = GatewayService()
 
-        with patch('mcpgateway.services.gateway_service.sse_client') as mock_sse_client:
+        with patch("mcpgateway.services.gateway_service.sse_client") as mock_sse_client:
             # Make SSE client raise an exception
             mock_sse_client.side_effect = Exception("Connection failed")
 
             # Execute and expect error
             with pytest.raises(GatewayConnectionError) as exc_info:
-                await service._initialize_gateway(
-                    "http://test.example.com",
-                    None,
-                    "SSE"
-                )
+                await service._initialize_gateway("http://test.example.com", None, "SSE")
 
             assert "Failed to initialize gateway" in str(exc_info.value)
 
@@ -317,8 +296,8 @@ async def test_get_auth_headers(self):
         service = GatewayService()
 
         # Just test that the method exists and is callable
-        assert hasattr(service, '_get_auth_headers')
-        assert callable(getattr(service, '_get_auth_headers'))
+        assert hasattr(service, "_get_auth_headers")
+        assert callable(getattr(service, "_get_auth_headers"))
 
     @pytest.mark.asyncio
     async def test_run_health_checks(self):
@@ -352,7 +331,7 @@ async def test_run_health_checks(self):
         service._file_lock = mock_file_lock
 
         # Use cache_type="none" to avoid file lock complexity
-        with patch('mcpgateway.services.gateway_service.settings') as mock_settings:
+        with patch("mcpgateway.services.gateway_service.settings") as mock_settings:
             mock_settings.cache_type = "none"
 
             # Run health checks for a short time
@@ -374,8 +353,8 @@ async def test_handle_gateway_failure(self):
         service = GatewayService()
 
         # Just test that the method exists and is callable
-        assert hasattr(service, '_handle_gateway_failure')
-        assert callable(getattr(service, '_handle_gateway_failure'))
+        assert hasattr(service, "_handle_gateway_failure")
+        assert callable(getattr(service, "_handle_gateway_failure"))
 
     @pytest.mark.asyncio
     async def test_subscribe_events(self):
@@ -422,16 +401,16 @@ async def test_aggregate_capabilities(self):
         service = GatewayService()
 
         # Just test that the method exists and is callable
-        assert hasattr(service, 'aggregate_capabilities')
-        assert callable(getattr(service, 'aggregate_capabilities'))
+        assert hasattr(service, "aggregate_capabilities")
+        assert callable(getattr(service, "aggregate_capabilities"))
 
     def test_get_gateways(self):
         """Test _get_gateways method exists."""
         service = GatewayService()
 
         # Just test that the method exists and is callable
-        assert hasattr(service, '_get_gateways')
-        assert callable(getattr(service, '_get_gateways'))
+        assert hasattr(service, "_get_gateways")
+        assert callable(getattr(service, "_get_gateways"))
 
     @pytest.mark.asyncio
     async def test_validate_gateway_url_exists(self):
@@ -439,5 +418,5 @@ async def test_validate_gateway_url_exists(self):
         service = GatewayService()
 
         # Just test that the method exists and is callable
-        assert hasattr(service, '_validate_gateway_url')
-        assert callable(getattr(service, '_validate_gateway_url'))
+        assert hasattr(service, "_validate_gateway_url")
+        assert callable(getattr(service, "_validate_gateway_url"))
diff --git a/tests/unit/mcpgateway/services/test_logging_service_comprehensive.py b/tests/unit/mcpgateway/services/test_logging_service_comprehensive.py
index 124c53a9..c6034d02 100644
--- a/tests/unit/mcpgateway/services/test_logging_service_comprehensive.py
+++ b/tests/unit/mcpgateway/services/test_logging_service_comprehensive.py
@@ -7,20 +7,17 @@
 """
 
 # Standard
-import asyncio
 import logging
 import os
 import tempfile
-from pathlib import Path
-from unittest.mock import MagicMock, patch, PropertyMock
+from unittest.mock import MagicMock, patch
 
 # Third-Party
 import pytest
 
 # First-Party
 from mcpgateway.models import LogLevel
-from mcpgateway.services.logging_service import LoggingService, _get_file_handler, _get_text_handler
-
+from mcpgateway.services.logging_service import _get_file_handler, _get_text_handler, LoggingService
 
 # ---------------------------------------------------------------------------
 # Test file handler creation
@@ -64,12 +61,14 @@ async def test_file_handler_creation_without_rotation():
             mock_settings.log_filemode = "a"
 
             # Reset global handler
+            # First-Party
             import mcpgateway.services.logging_service as ls
+
             ls._file_handler = None
 
             handler = _get_file_handler()
             assert handler is not None
-            assert not hasattr(handler, 'maxBytes')  # Regular FileHandler doesn't have this
+            assert not hasattr(handler, "maxBytes")  # Regular FileHandler doesn't have this
 
 
 @pytest.mark.asyncio
@@ -79,7 +78,9 @@ async def test_file_handler_raises_when_disabled():
         mock_settings.log_to_file = False
 
         # Reset global handler
+        # First-Party
         import mcpgateway.services.logging_service as ls
+
         ls._file_handler = None
 
         with pytest.raises(ValueError, match="File logging is disabled"):
@@ -119,8 +120,8 @@ async def test_initialize_with_file_logging_enabled():
             root_logger = logging.getLogger()
             # Should have both text and file handlers
             handler_types = [type(h).__name__ for h in root_logger.handlers]
-            assert 'StreamHandler' in handler_types
-            assert 'RotatingFileHandler' in handler_types
+            assert "StreamHandler" in handler_types
+            assert "RotatingFileHandler" in handler_types
 
             await service.shutdown()
 
@@ -138,7 +139,7 @@ async def test_initialize_with_file_logging_disabled():
         root_logger = logging.getLogger()
         # Should only have text handler
         handler_types = [type(h).__name__ for h in root_logger.handlers]
-        assert 'StreamHandler' in handler_types
+        assert "StreamHandler" in handler_types
 
         await service.shutdown()
 
@@ -172,7 +173,7 @@ async def test_configure_uvicorn_loggers():
     service = LoggingService()
     service._configure_uvicorn_loggers()
 
-    uvicorn_loggers = ['uvicorn', 'uvicorn.access', 'uvicorn.error', 'uvicorn.asgi']
+    uvicorn_loggers = ["uvicorn", "uvicorn.access", "uvicorn.error", "uvicorn.asgi"]
     for logger_name in uvicorn_loggers:
         logger = logging.getLogger(logger_name)
         assert logger.propagate == True
@@ -185,7 +186,7 @@ async def test_configure_uvicorn_after_startup():
     """Test public method to reconfigure uvicorn loggers after startup."""
     service = LoggingService()
 
-    with patch.object(service, '_configure_uvicorn_loggers') as mock_config:
+    with patch.object(service, "_configure_uvicorn_loggers") as mock_config:
         service.configure_uvicorn_after_startup()
         mock_config.assert_called_once()
 
@@ -230,8 +231,7 @@ async def test_should_log_all_levels():
 
     for min_level, should_pass in test_cases:
         service._level = min_level
-        for level in [LogLevel.DEBUG, LogLevel.INFO, LogLevel.NOTICE, LogLevel.WARNING,
-                      LogLevel.ERROR, LogLevel.CRITICAL, LogLevel.ALERT, LogLevel.EMERGENCY]:
+        for level in [LogLevel.DEBUG, LogLevel.INFO, LogLevel.NOTICE, LogLevel.WARNING, LogLevel.ERROR, LogLevel.CRITICAL, LogLevel.ALERT, LogLevel.EMERGENCY]:
             if level in should_pass:
                 assert service._should_log(level), f"{level} should log at {min_level}"
             else:
@@ -248,7 +248,7 @@ async def test_notify_with_logger_name():
     """Test notify with a specific logger name."""
     service = LoggingService()
 
-    with patch.object(service, 'get_logger') as mock_get_logger:
+    with patch.object(service, "get_logger") as mock_get_logger:
         mock_logger = MagicMock()
         mock_get_logger.return_value = mock_logger
 
@@ -263,7 +263,7 @@ async def test_notify_without_logger_name():
     """Test notify without a specific logger name uses root logger."""
     service = LoggingService()
 
-    with patch.object(service, 'get_logger') as mock_get_logger:
+    with patch.object(service, "get_logger") as mock_get_logger:
         mock_logger = MagicMock()
         mock_get_logger.return_value = mock_logger
 
@@ -364,7 +364,9 @@ async def test_dual_logging_integration():
             mock_settings.log_filemode = "w"
 
             # Reset global handlers
+            # First-Party
             import mcpgateway.services.logging_service as ls
+
             ls._file_handler = None
             ls._text_handler = None
 
@@ -379,13 +381,13 @@ async def test_dual_logging_integration():
             # Configure uvicorn loggers
             service.configure_uvicorn_after_startup()
             uvicorn_logger = logging.getLogger("uvicorn.access")
-            uvicorn_logger.info("127.0.0.1:8000 - \"GET /test HTTP/1.1\" 200")
+            uvicorn_logger.info('127.0.0.1:8000 - "GET /test HTTP/1.1" 200')
 
             await service.shutdown()
 
             # Check file was created and contains expected content
             assert os.path.exists(log_file)
-            with open(log_file, 'r') as f:
+            with open(log_file, "r") as f:
                 content = f.read()
                 assert "Integration test message" in content
                 assert "Integration error message" in content
@@ -414,8 +416,7 @@ async def test_notify_with_all_log_levels():
 
     # Test all levels including NOTICE, ALERT, EMERGENCY
     # which are now mapped to appropriate Python levels
-    for level in [LogLevel.DEBUG, LogLevel.INFO, LogLevel.NOTICE, LogLevel.WARNING,
-                  LogLevel.ERROR, LogLevel.CRITICAL, LogLevel.ALERT, LogLevel.EMERGENCY]:
+    for level in [LogLevel.DEBUG, LogLevel.INFO, LogLevel.NOTICE, LogLevel.WARNING, LogLevel.ERROR, LogLevel.CRITICAL, LogLevel.ALERT, LogLevel.EMERGENCY]:
         await service.notify(f"Test {level}", level)
         # Should not raise any exceptions now that we have proper mapping
 
@@ -434,7 +435,9 @@ async def test_file_handler_creates_directory():
             mock_settings.log_filemode = "a"
 
             # Reset global handler
+            # First-Party
             import mcpgateway.services.logging_service as ls
+
             ls._file_handler = None
 
             handler = _get_file_handler()
diff --git a/tests/unit/mcpgateway/services/test_tag_service.py b/tests/unit/mcpgateway/services/test_tag_service.py
index 56ca7133..1195b7bd 100644
--- a/tests/unit/mcpgateway/services/test_tag_service.py
+++ b/tests/unit/mcpgateway/services/test_tag_service.py
@@ -1,12 +1,15 @@
 # -*- coding: utf-8 -*-
 """Tests for Tag Service."""
 
+# Standard
+from unittest.mock import MagicMock
+
+# Third-Party
 import pytest
 from sqlalchemy.orm import Session
-from unittest.mock import MagicMock, patch
 
+# First-Party
 from mcpgateway.services.tag_service import TagService
-from mcpgateway.schemas import TaggedEntity, TagInfo, TagStats
 
 
 @pytest.fixture
@@ -39,11 +42,13 @@ async def test_get_all_tags_with_tools(tag_service, mock_db):
     """Test getting tags from tools only."""
     # Mock database query for tools
     mock_result = MagicMock()
-    mock_result.__iter__ = lambda self: iter([
-        (["api", "data"],),
-        (["api", "auth"],),
-        (["data"],),
-    ])
+    mock_result.__iter__ = lambda self: iter(
+        [
+            (["api", "data"],),
+            (["api", "auth"],),
+            (["data"],),
+        ]
+    )
     mock_db.execute.return_value = mock_result
 
     tags = await tag_service.get_all_tags(mock_db, entity_types=["tools"])
@@ -108,19 +113,31 @@ async def test_get_all_tags_multiple_entity_types(tag_service, mock_db):
     call_count = 0
     results = [
         # Tools results
-        MagicMock(__iter__=lambda self: iter([
-            (["api", "tool"],),
-            (["api"],),
-        ])),
+        MagicMock(
+            __iter__=lambda self: iter(
+                [
+                    (["api", "tool"],),
+                    (["api"],),
+                ]
+            )
+        ),
         # Resources results
-        MagicMock(__iter__=lambda self: iter([
-            (["api", "resource"],),
-            (["data"],),
-        ])),
+        MagicMock(
+            __iter__=lambda self: iter(
+                [
+                    (["api", "resource"],),
+                    (["data"],),
+                ]
+            )
+        ),
         # Prompts results
-        MagicMock(__iter__=lambda self: iter([
-            (["prompt", "api"],),
-        ])),
+        MagicMock(
+            __iter__=lambda self: iter(
+                [
+                    (["prompt", "api"],),
+                ]
+            )
+        ),
     ]
 
     def side_effect(*args):
@@ -148,12 +165,14 @@ async def test_get_all_tags_with_empty_tags(tag_service, mock_db):
     """Test handling entities with empty tag arrays."""
     # Mock database query with some empty tag arrays
     mock_result = MagicMock()
-    mock_result.__iter__ = lambda self: iter([
-        (["api"],),
-        ([],),  # Empty tags array
-        (None,),  # Null tags
-        (["data"],),
-    ])
+    mock_result.__iter__ = lambda self: iter(
+        [
+            (["api"],),
+            ([],),  # Empty tags array
+            (None,),  # Null tags
+            (["data"],),
+        ]
+    )
     mock_db.execute.return_value = mock_result
 
     tags = await tag_service.get_all_tags(mock_db, entity_types=["tools"])
@@ -182,10 +201,12 @@ async def test_get_all_tags_sorted(tag_service, mock_db):
     """Test that tags are returned in sorted order."""
     # Mock database query
     mock_result = MagicMock()
-    mock_result.__iter__ = lambda self: iter([
-        (["zebra", "beta", "alpha"],),
-        (["gamma", "alpha"],),
-    ])
+    mock_result.__iter__ = lambda self: iter(
+        [
+            (["zebra", "beta", "alpha"],),
+            (["gamma", "alpha"],),
+        ]
+    )
     mock_db.execute.return_value = mock_result
 
     tags = await tag_service.get_all_tags(mock_db, entity_types=["tools"])
@@ -356,9 +377,9 @@ async def test_get_tag_counts(tag_service, mock_db):
     call_count = 0
     tag_counts = [
         [2, 1, 3],  # tools: 3 entities with 2, 1, 3 tags = 6 total
-        [1, 2],     # resources: 2 entities with 1, 2 tags = 3 total
-        [4],        # prompts: 1 entity with 4 tags = 4 total
-        [],         # servers: no entities = 0 total
+        [1, 2],  # resources: 2 entities with 1, 2 tags = 3 total
+        [4],  # prompts: 1 entity with 4 tags = 4 total
+        [],  # servers: no entities = 0 total
         [1, 1, 1],  # gateways: 3 entities with 1 tag each = 3 total
     ]
 
@@ -384,6 +405,7 @@ def side_effect(*args):
 @pytest.mark.asyncio
 async def test_update_stats(tag_service):
     """Test the _update_stats helper method."""
+    # First-Party
     from mcpgateway.schemas import TagStats
 
     stats = TagStats(tools=0, resources=0, prompts=0, servers=0, gateways=0, total=0)
diff --git a/tests/unit/mcpgateway/services/test_tool_service.py b/tests/unit/mcpgateway/services/test_tool_service.py
index df9c4ee8..511558f3 100644
--- a/tests/unit/mcpgateway/services/test_tool_service.py
+++ b/tests/unit/mcpgateway/services/test_tool_service.py
@@ -1032,9 +1032,7 @@ async def test_update_tool_extra_fields(self, tool_service, mock_tool, test_db):
         test_db.refresh = AsyncMock()
 
         # Create update request
-        tool_update = ToolUpdate(
-            integration_type="REST", request_type="POST", headers={"key": "value"}, input_schema={"key2": "value2"}, annotations={"key3": "value3"}, jsonpath_filter="test_filter"
-        )
+        tool_update = ToolUpdate(integration_type="REST", request_type="POST", headers={"key": "value"}, input_schema={"key2": "value2"}, annotations={"key3": "value3"}, jsonpath_filter="test_filter")
 
         # The service wraps the exception in ToolError
         result = await tool_service.update_tool(test_db, "999", tool_update)
diff --git a/tests/unit/mcpgateway/test_admin.py b/tests/unit/mcpgateway/test_admin.py
index 4b3ccaa8..d711caa6 100644
--- a/tests/unit/mcpgateway/test_admin.py
+++ b/tests/unit/mcpgateway/test_admin.py
@@ -388,14 +388,14 @@ async def test_admin_add_tool_with_tool_error(self, mock_register_tool, mock_req
         """Test adding tool with ToolError."""
         mock_register_tool.side_effect = ToolError("Tool service error")
         mock_form = {
-        "name": "test-tool",
-        "url": "http://example.com",
-        "description": "Test tool",
-        "requestType": "GET",
-        "integrationType": "REST",
-        "headers": "{}",  # must be a valid JSON string
-        "input_schema": "{}",
-         }
+            "name": "test-tool",
+            "url": "http://example.com",
+            "description": "Test tool",
+            "requestType": "GET",
+            "integrationType": "REST",
+            "headers": "{}",  # must be a valid JSON string
+            "input_schema": "{}",
+        }
 
         mock_request.form = AsyncMock(return_value=mock_form)
 
@@ -434,14 +434,9 @@ async def test_admin_edit_tool_all_error_paths(self, mock_update_tool, mock_requ
         from sqlalchemy.exc import IntegrityError
         from starlette.datastructures import FormData
 
-        mock_request.form = AsyncMock(return_value=FormData([
-        ("name", "Tool_Name_1"),
-        ("url", "http://example.com"),
-        ("requestType", "GET"),
-        ("integrationType", "REST"),
-        ("headers", "{}"),
-        ("input_schema", "{}")
-        ]))
+        mock_request.form = AsyncMock(
+            return_value=FormData([("name", "Tool_Name_1"), ("url", "http://example.com"), ("requestType", "GET"), ("integrationType", "REST"), ("headers", "{}"), ("input_schema", "{}")])
+        )
         mock_update_tool.side_effect = IntegrityError("Integrity constraint", {}, Exception("Duplicate key"))
         result = await admin_edit_tool(tool_id, mock_request, mock_db, "test-user")
 
@@ -453,7 +448,6 @@ async def test_admin_edit_tool_all_error_paths(self, mock_update_tool, mock_requ
         assert result.status_code == 500
         assert b"Tool configuration error" in result.body
 
-
         # Generic Exception should return 500 with JSON body
         mock_update_tool.side_effect = Exception("Unexpected error")
         result = await admin_edit_tool(tool_id, mock_request, mock_db, "test-user")
@@ -477,7 +471,7 @@ async def test_admin_edit_tool_with_empty_optional_fields(self, mock_update_tool
                 "jsonpathFilter": "",
                 "auth_type": "",
                 "requestType": "GET",
-                "integrationType": "REST"
+                "integrationType": "REST",
             }
         )
         mock_request.form = AsyncMock(return_value=form_data)
diff --git a/tests/unit/mcpgateway/test_main.py b/tests/unit/mcpgateway/test_main.py
index 6c650718..6fb929f5 100644
--- a/tests/unit/mcpgateway/test_main.py
+++ b/tests/unit/mcpgateway/test_main.py
@@ -11,16 +11,15 @@
 
 # Standard
 from copy import deepcopy
+import datetime
 import json
 import os
-import datetime
 from unittest.mock import ANY, MagicMock, patch
 
 # Third-Party
-import pytest
-import jwt
 from fastapi.testclient import TestClient
-
+import jwt
+import pytest
 
 # First-Party
 from mcpgateway.config import settings
@@ -179,6 +178,7 @@ def test_client(app):
     yield client
     app.dependency_overrides.pop(require_auth, None)
 
+
 @pytest.fixture
 def mock_jwt_token():
     """Create a valid JWT token for testing."""
@@ -348,7 +348,9 @@ class TestServerEndpoints:
     @patch("mcpgateway.main.server_service.update_server")
     def test_update_server_not_found(self, mock_update, test_client, auth_headers):
         """Test update_server returns 404 if server not found."""
+        # First-Party
         from mcpgateway.services.server_service import ServerNotFoundError
+
         mock_update.side_effect = ServerNotFoundError("Server not found")
         req = {"description": "Updated description"}
         response = test_client.put("/servers/999", json=req, headers=auth_headers)
@@ -361,6 +363,7 @@ def test_create_server_validation_error(self, mock_create, test_client, auth_hea
         req = {"description": "Missing name"}
         response = test_client.post("/servers/", json=req, headers=auth_headers)
         assert response.status_code == 422
+
     """Tests for virtual server management: CRUD operations, status toggles, etc."""
 
     @patch("mcpgateway.main.server_service.list_servers")
@@ -467,7 +470,9 @@ class TestToolEndpoints:
     @patch("mcpgateway.main.tool_service.update_tool")
     def test_update_tool_not_found(self, mock_update, test_client, auth_headers):
         """Test update_tool returns 404 if tool not found."""
+        # First-Party
         from mcpgateway.services.tool_service import ToolNotFoundError
+
         mock_update.side_effect = ToolNotFoundError("Tool not found")
         req = {"description": "Updated description"}
         response = test_client.put("/tools/999", json=req, headers=auth_headers)
@@ -480,6 +485,7 @@ def test_create_tool_validation_error(self, mock_create, test_client, auth_heade
         req = {"description": "Missing name and url"}
         response = test_client.post("/tools/", json=req, headers=auth_headers)
         assert response.status_code == 422
+
     """Tests for tool management: registration, invocation, updates, etc."""
 
     @patch("mcpgateway.main.tool_service.list_tools")
@@ -543,7 +549,9 @@ class TestResourceEndpoints:
     @patch("mcpgateway.main.resource_service.update_resource")
     def test_update_resource_not_found(self, mock_update, test_client, auth_headers):
         """Test update_resource returns 404 if resource not found."""
+        # First-Party
         from mcpgateway.services.resource_service import ResourceNotFoundError
+
         mock_update.side_effect = ResourceNotFoundError("Resource not found")
         req = {"description": "Updated description"}
         response = test_client.put("/resources/nonexistent", json=req, headers=auth_headers)
@@ -556,6 +564,7 @@ def test_create_resource_validation_error(self, mock_create, test_client, auth_h
         req = {"description": "Missing uri and name"}
         response = test_client.post("/resources/", json=req, headers=auth_headers)
         assert response.status_code == 422
+
     """Tests for resource management: reading, creation, caching, etc."""
 
     @patch("mcpgateway.main.resource_service.list_resources")
@@ -647,14 +656,19 @@ class TestPromptEndpoints:
     @patch("mcpgateway.main.prompt_service.delete_prompt")
     def test_delete_prompt_not_found(self, mock_delete, test_client, auth_headers):
         """Test delete_prompt returns 404 if prompt not found."""
+        # First-Party
         from mcpgateway.services.prompt_service import PromptNotFoundError
+
         mock_delete.side_effect = PromptNotFoundError("Prompt not found")
         response = test_client.delete("/prompts/nonexistent", headers=auth_headers)
         assert response.status_code == 404
+
     @patch("mcpgateway.main.prompt_service.update_prompt")
     def test_update_prompt_not_found(self, mock_update, test_client, auth_headers):
         """Test update_prompt returns 404 if prompt not found."""
+        # First-Party
         from mcpgateway.services.prompt_service import PromptNotFoundError
+
         mock_update.side_effect = PromptNotFoundError("Prompt not found")
         req = {"description": "Updated description"}
         response = test_client.put("/prompts/nonexistent", json=req, headers=auth_headers)
@@ -667,6 +681,7 @@ def test_create_prompt_validation_error(self, mock_create, test_client, auth_hea
         req = {"description": "Missing name and template"}
         response = test_client.post("/prompts/", json=req, headers=auth_headers)
         assert response.status_code == 422
+
     @patch("mcpgateway.main.prompt_service.get_prompt")
     def test_get_prompt_no_args(self, mock_get, test_client, auth_headers):
         """Test getting a prompt without arguments."""
@@ -704,6 +719,7 @@ def test_toggle_prompt_status(self, mock_toggle, test_client, auth_headers):
         assert response.status_code == 200
         assert response.json()["status"] == "success"
         mock_toggle.assert_called_once()
+
     """Tests for prompt template management: creation, rendering, arguments, etc."""
 
     @patch("mcpgateway.main.prompt_service.list_prompts")
@@ -841,6 +857,7 @@ def test_toggle_gateway_status(self, mock_toggle, test_client, auth_headers):
         assert response.status_code == 200
         assert response.json()["status"] == "success"
         mock_toggle.assert_called_once()
+
     """Tests for gateway federation: registration, discovery, forwarding, etc."""
 
     @patch("mcpgateway.main.gateway_service.list_gateways")
@@ -1203,7 +1220,9 @@ def test_docs_with_invalid_jwt(self, test_client):
     def test_docs_with_expired_jwt(self, test_client):
         """Test /docs with an expired JWT returns 401."""
         expired_payload = {"sub": "test_user", "exp": datetime.datetime.utcnow() - datetime.timedelta(hours=1)}
+        # First-Party
         from mcpgateway.config import settings
+
         expired_token = jwt.encode(expired_payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
         headers = {"Authorization": f"Bearer {expired_token}"}
         response = test_client.get("/docs", headers=headers)
diff --git a/tests/unit/mcpgateway/test_multi_auth_headers.py b/tests/unit/mcpgateway/test_multi_auth_headers.py
new file mode 100644
index 00000000..5f0ca657
--- /dev/null
+++ b/tests/unit/mcpgateway/test_multi_auth_headers.py
@@ -0,0 +1,171 @@
+# -*- coding: utf-8 -*-
+"""Test multi-header authentication functionality."""
+
+# Standard
+from unittest.mock import AsyncMock, MagicMock, patch
+
+# Third-Party
+from fastapi import Request
+from pydantic import ValidationError
+import pytest
+from starlette.datastructures import FormData
+
+# First-Party
+from mcpgateway.admin import admin_add_gateway
+from mcpgateway.schemas import GatewayCreate, GatewayUpdate
+from mcpgateway.utils.services_auth import decode_auth
+
+
+class TestMultiAuthHeaders:
+    """Test cases for multi-header authentication feature."""
+
+    @pytest.mark.asyncio
+    async def test_gateway_create_with_valid_multi_headers(self):
+        """Test creating gateway with valid multi-auth headers."""
+        auth_headers = [{"key": "X-API-Key", "value": "secret123"}, {"key": "X-Client-ID", "value": "client456"}, {"key": "X-Region", "value": "us-east-1"}]
+
+        gateway = GatewayCreate(name="Test Gateway", url="http://example.com", auth_type="authheaders", auth_headers=auth_headers)
+
+        assert gateway.auth_value is not None
+        decoded = decode_auth(gateway.auth_value)
+        assert decoded["X-API-Key"] == "secret123"
+        assert decoded["X-Client-ID"] == "client456"
+        assert decoded["X-Region"] == "us-east-1"
+
+    @pytest.mark.asyncio
+    async def test_gateway_create_with_empty_headers_list(self):
+        """Test creating gateway with empty auth_headers list."""
+        with pytest.raises(ValidationError) as exc_info:
+            GatewayCreate(name="Test Gateway", url="http://example.com", auth_type="authheaders", auth_headers=[])
+
+        assert "either 'auth_headers' list or both" in str(exc_info.value).lower()
+
+    @pytest.mark.asyncio
+    async def test_gateway_create_with_duplicate_header_keys(self):
+        """Test handling of duplicate header keys (last value wins)."""
+        auth_headers = [{"key": "X-API-Key", "value": "first_value"}, {"key": "X-API-Key", "value": "second_value"}, {"key": "X-Client-ID", "value": "client123"}]
+
+        gateway = GatewayCreate(name="Test Gateway", url="http://example.com", auth_type="authheaders", auth_headers=auth_headers)
+
+        decoded = decode_auth(gateway.auth_value)
+        assert decoded["X-API-Key"] == "second_value"  # Last value should win
+        assert decoded["X-Client-ID"] == "client123"
+
+    @pytest.mark.asyncio
+    async def test_gateway_create_with_empty_header_values(self):
+        """Test creating gateway with empty header values."""
+        auth_headers = [{"key": "X-API-Key", "value": ""}, {"key": "X-Client-ID", "value": "client123"}]
+
+        gateway = GatewayCreate(name="Test Gateway", url="http://example.com", auth_type="authheaders", auth_headers=auth_headers)
+
+        decoded = decode_auth(gateway.auth_value)
+        assert decoded["X-API-Key"] == ""  # Empty values should be allowed
+        assert decoded["X-Client-ID"] == "client123"
+
+    @pytest.mark.asyncio
+    async def test_gateway_create_with_missing_key_in_header(self):
+        """Test creating gateway with missing key in header object."""
+        auth_headers = [{"value": "secret123"}, {"key": "X-Client-ID", "value": "client123"}]  # Missing 'key' field
+
+        gateway = GatewayCreate(name="Test Gateway", url="http://example.com", auth_type="authheaders", auth_headers=auth_headers)
+
+        decoded = decode_auth(gateway.auth_value)
+        assert "X-Client-ID" in decoded
+        assert len(decoded) == 1  # Only valid header should be included
+
+    @pytest.mark.asyncio
+    async def test_backward_compatibility_single_headers(self):
+        """Test backward compatibility with single header fields."""
+        gateway = GatewayCreate(name="Test Gateway", url="http://example.com", auth_type="authheaders", auth_header_key="X-API-Key", auth_header_value="secret123")
+
+        decoded = decode_auth(gateway.auth_value)
+        assert decoded["X-API-Key"] == "secret123"
+
+    @pytest.mark.asyncio
+    async def test_multi_headers_priority_over_single(self):
+        """Test that multi-headers take priority over single header fields."""
+        auth_headers = [{"key": "X-Multi-Header", "value": "multi_value"}]
+
+        gateway = GatewayCreate(
+            name="Test Gateway",
+            url="http://example.com",
+            auth_type="authheaders",
+            auth_headers=auth_headers,
+            auth_header_key="X-Single-Header",  # Should be ignored
+            auth_header_value="single_value",  # Should be ignored
+        )
+
+        decoded = decode_auth(gateway.auth_value)
+        assert "X-Multi-Header" in decoded
+        assert "X-Single-Header" not in decoded
+
+    @pytest.mark.asyncio
+    async def test_gateway_update_add_multi_headers(self):
+        """Test updating gateway to add multi-headers."""
+        auth_headers = [{"key": "X-New-Header", "value": "new_value"}]
+
+        gateway = GatewayUpdate(auth_type="authheaders", auth_headers=auth_headers)
+
+        assert gateway.auth_value is not None
+        decoded = decode_auth(gateway.auth_value)
+        assert decoded["X-New-Header"] == "new_value"
+
+    @pytest.mark.asyncio
+    async def test_special_characters_in_headers(self):
+        """Test headers with special characters."""
+        auth_headers = [{"key": "X-Special-!@#", "value": "value-with-特殊字符"}, {"key": "Content-Type", "value": "application/json; charset=utf-8"}]
+
+        gateway = GatewayCreate(name="Test Gateway", url="http://example.com", auth_type="authheaders", auth_headers=auth_headers)
+
+        decoded = decode_auth(gateway.auth_value)
+        assert decoded["X-Special-!@#"] == "value-with-特殊字符"
+        assert decoded["Content-Type"] == "application/json; charset=utf-8"
+
+    @pytest.mark.asyncio
+    async def test_case_sensitivity_preservation(self):
+        """Test that header key case is preserved."""
+        auth_headers = [{"key": "X-API-Key", "value": "value1"}, {"key": "x-api-key", "value": "value2"}, {"key": "X-Api-Key", "value": "value3"}]
+
+        gateway = GatewayCreate(name="Test Gateway", url="http://example.com", auth_type="authheaders", auth_headers=auth_headers)
+
+        decoded = decode_auth(gateway.auth_value)
+        # All three variations should be preserved as separate keys
+        assert len(decoded) == 3
+
+    @pytest.mark.asyncio
+    async def test_admin_endpoint_with_invalid_json(self):
+        """Test admin endpoint handling of invalid JSON."""
+        mock_db = MagicMock()
+        mock_user = "test_user"
+
+        form_data = FormData([("name", "Test Gateway"), ("url", "http://example.com"), ("auth_type", "authheaders"), ("auth_headers", "{invalid json}")])
+
+        mock_request = MagicMock(spec=Request)
+        mock_request.form = AsyncMock(return_value=form_data)
+
+        with patch("mcpgateway.admin.gateway_service.register_gateway", AsyncMock()):
+            response = await admin_add_gateway(mock_request, mock_db, mock_user)
+            # Should handle invalid JSON gracefully
+            assert response.status_code in [200, 422]
+
+    @pytest.mark.asyncio
+    async def test_large_number_of_headers(self):
+        """Test handling of large number of headers."""
+        auth_headers = [{"key": f"X-Header-{i}", "value": f"value-{i}"} for i in range(100)]
+
+        gateway = GatewayCreate(name="Test Gateway", url="http://example.com", auth_type="authheaders", auth_headers=auth_headers)
+
+        decoded = decode_auth(gateway.auth_value)
+        assert len(decoded) == 100
+        assert decoded["X-Header-50"] == "value-50"
+
+    @pytest.mark.asyncio
+    async def test_authorization_header_in_multi_headers(self):
+        """Test including Authorization header in multi-headers."""
+        auth_headers = [{"key": "Authorization", "value": "Bearer token123"}, {"key": "X-API-Key", "value": "secret"}]
+
+        gateway = GatewayCreate(name="Test Gateway", url="http://example.com", auth_type="authheaders", auth_headers=auth_headers)
+
+        decoded = decode_auth(gateway.auth_value)
+        assert decoded["Authorization"] == "Bearer token123"
+        assert decoded["X-API-Key"] == "secret"
diff --git a/tests/unit/mcpgateway/utils/test_passthrough_headers.py b/tests/unit/mcpgateway/utils/test_passthrough_headers.py
index 1cb37cbf..eca1644a 100644
--- a/tests/unit/mcpgateway/utils/test_passthrough_headers.py
+++ b/tests/unit/mcpgateway/utils/test_passthrough_headers.py
@@ -14,18 +14,16 @@
 import logging
 from unittest.mock import Mock, patch
 
-# Third-Party
-import pytest
-
 # First-Party
-from mcpgateway.db import Gateway as DbGateway, GlobalConfig
+from mcpgateway.db import Gateway as DbGateway
+from mcpgateway.db import GlobalConfig
 from mcpgateway.utils.passthrough_headers import get_passthrough_headers
 
 
 class TestPassthroughHeaders:
     """Test suite for HTTP header passthrough functionality."""
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_basic_header_passthrough_global_config(self, mock_settings):
         """Test basic header passthrough with global configuration."""
         mock_settings.enable_header_passthrough = True
@@ -36,23 +34,15 @@ def test_basic_header_passthrough_global_config(self, mock_settings):
         mock_global_config.passthrough_headers = ["X-Tenant-Id", "X-Trace-Id"]
         mock_db.query.return_value.first.return_value = mock_global_config
 
-        request_headers = {
-            "x-tenant-id": "acme-corp",
-            "x-trace-id": "trace-456",
-            "user-agent": "TestClient/1.0"  # Not in allowed headers
-        }
+        request_headers = {"x-tenant-id": "acme-corp", "x-trace-id": "trace-456", "user-agent": "TestClient/1.0"}  # Not in allowed headers
         base_headers = {"Content-Type": "application/json"}
 
         result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
-        expected = {
-            "Content-Type": "application/json",
-            "X-Tenant-Id": "acme-corp",
-            "X-Trace-Id": "trace-456"
-        }
+        expected = {"Content-Type": "application/json", "X-Tenant-Id": "acme-corp", "X-Trace-Id": "trace-456"}
         assert result == expected
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_gateway_specific_override(self, mock_settings):
         """Test that gateway-specific headers override global configuration."""
         mock_settings.enable_header_passthrough = True
@@ -67,22 +57,15 @@ def test_gateway_specific_override(self, mock_settings):
         mock_gateway.passthrough_headers = ["X-Custom-Header"]
         mock_gateway.auth_type = None
 
-        request_headers = {
-            "x-custom-header": "custom-value",
-            "x-tenant-id": "should-be-ignored",  # Not in gateway config
-            "x-trace-id": "also-ignored"
-        }
+        request_headers = {"x-custom-header": "custom-value", "x-tenant-id": "should-be-ignored", "x-trace-id": "also-ignored"}  # Not in gateway config
         base_headers = {"Content-Type": "application/json"}
 
         result = get_passthrough_headers(request_headers, base_headers, mock_db, mock_gateway)
 
-        expected = {
-            "Content-Type": "application/json",
-            "X-Custom-Header": "custom-value"
-        }
+        expected = {"Content-Type": "application/json", "X-Custom-Header": "custom-value"}
         assert result == expected
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_authorization_conflict_basic_auth(self, mock_settings, caplog):
         """Test that Authorization header is blocked when gateway uses basic auth."""
         mock_settings.enable_header_passthrough = True
@@ -97,27 +80,20 @@ def test_authorization_conflict_basic_auth(self, mock_settings, caplog):
         mock_gateway.auth_type = "basic"
         mock_gateway.name = "test-gateway"
 
-        request_headers = {
-            "authorization": "Bearer should-be-blocked",
-            "x-tenant-id": "acme-corp"
-        }
+        request_headers = {"authorization": "Bearer should-be-blocked", "x-tenant-id": "acme-corp"}
         base_headers = {"Content-Type": "application/json"}
 
         with caplog.at_level(logging.WARNING):
             result = get_passthrough_headers(request_headers, base_headers, mock_db, mock_gateway)
 
         # Authorization should be blocked, X-Tenant-Id should pass through
-        expected = {
-            "Content-Type": "application/json",
-            "X-Tenant-Id": "acme-corp"
-        }
+        expected = {"Content-Type": "application/json", "X-Tenant-Id": "acme-corp"}
         assert result == expected
 
         # Check warning was logged
-        assert any("Skipping Authorization header passthrough due to basic auth" in record.message
-                  for record in caplog.records)
+        assert any("Skipping Authorization header passthrough due to basic auth" in record.message for record in caplog.records)
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_authorization_conflict_bearer_auth(self, mock_settings, caplog):
         """Test that Authorization header is blocked when gateway uses bearer auth."""
         mock_settings.enable_header_passthrough = True
@@ -143,10 +119,9 @@ def test_authorization_conflict_bearer_auth(self, mock_settings, caplog):
         assert result == expected
 
         # Check warning was logged
-        assert any("Skipping Authorization header passthrough due to bearer auth" in record.message
-                  for record in caplog.records)
+        assert any("Skipping Authorization header passthrough due to bearer auth" in record.message for record in caplog.records)
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_base_header_conflict_prevention(self, mock_settings, caplog):
         """Test that request headers don't override base headers."""
         mock_settings.enable_header_passthrough = True
@@ -156,27 +131,20 @@ def test_base_header_conflict_prevention(self, mock_settings, caplog):
         mock_global_config.passthrough_headers = ["Content-Type", "X-Tenant-Id"]
         mock_db.query.return_value.first.return_value = mock_global_config
 
-        request_headers = {
-            "content-type": "text/plain",  # Conflicts with base header
-            "x-tenant-id": "acme-corp"     # Should pass through
-        }
+        request_headers = {"content-type": "text/plain", "x-tenant-id": "acme-corp"}  # Conflicts with base header  # Should pass through
         base_headers = {"Content-Type": "application/json"}
 
         with caplog.at_level(logging.WARNING):
             result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
         # Base header preserved, tenant ID added
-        expected = {
-            "Content-Type": "application/json",
-            "X-Tenant-Id": "acme-corp"
-        }
+        expected = {"Content-Type": "application/json", "X-Tenant-Id": "acme-corp"}
         assert result == expected
 
         # Check conflict warning was logged
-        assert any("conflicts with pre-defined headers" in record.message
-                  for record in caplog.records)
+        assert any("conflicts with pre-defined headers" in record.message for record in caplog.records)
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_case_insensitive_header_matching(self, mock_settings):
         """Test that header matching works with lowercase request headers."""
         mock_settings.enable_header_passthrough = True
@@ -187,22 +155,16 @@ def test_case_insensitive_header_matching(self, mock_settings):
         mock_db.query.return_value.first.return_value = mock_global_config
 
         # Request headers are expected to be normalized to lowercase
-        request_headers = {
-            "x-tenant-id": "mixed-case-value",  # Lowercase key
-            "authorization": "bearer lowercase-header"
-        }
+        request_headers = {"x-tenant-id": "mixed-case-value", "authorization": "bearer lowercase-header"}  # Lowercase key
         base_headers = {}
 
         result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
         # Headers should preserve config case in output keys
-        expected = {
-            "X-Tenant-ID": "mixed-case-value",
-            "Authorization": "bearer lowercase-header"
-        }
+        expected = {"X-Tenant-ID": "mixed-case-value", "Authorization": "bearer lowercase-header"}
         assert result == expected
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_missing_request_headers(self, mock_settings, caplog):
         """Test behavior when configured headers are missing from request."""
         mock_settings.enable_header_passthrough = True
@@ -219,10 +181,7 @@ def test_missing_request_headers(self, mock_settings, caplog):
             result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
         # Only present header should be included
-        expected = {
-            "Content-Type": "application/json",
-            "X-Present": "present-value"
-        }
+        expected = {"Content-Type": "application/json", "X-Present": "present-value"}
         assert result == expected
 
         # Check debug message for missing header
@@ -230,10 +189,9 @@ def test_missing_request_headers(self, mock_settings, caplog):
             # Re-run to capture debug messages
             result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
-        assert any("X-Missing not found in request headers" in record.message
-                  for record in caplog.records)
+        assert any("X-Missing not found in request headers" in record.message for record in caplog.records)
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_empty_allowed_headers(self, mock_settings):
         """Test behavior with empty allowed headers configuration."""
         mock_settings.enable_header_passthrough = True
@@ -263,7 +221,7 @@ def test_none_allowed_headers(self):
         base_headers = {"Content-Type": "application/json"}
 
         # Mock settings fallback
-        with patch('mcpgateway.utils.passthrough_headers.settings') as mock_settings:
+        with patch("mcpgateway.utils.passthrough_headers.settings") as mock_settings:
             mock_settings.default_passthrough_headers = ["X-Default"]
 
             result = get_passthrough_headers(request_headers, base_headers, mock_db)
@@ -281,15 +239,12 @@ def test_no_global_config_fallback_to_settings(self):
         base_headers = {"Content-Type": "application/json"}
 
         # Mock settings fallback
-        with patch('mcpgateway.utils.passthrough_headers.settings') as mock_settings:
+        with patch("mcpgateway.utils.passthrough_headers.settings") as mock_settings:
             mock_settings.default_passthrough_headers = ["X-Default"]
 
             result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
-        expected = {
-            "Content-Type": "application/json",
-            "X-Default": "default-value"
-        }
+        expected = {"Content-Type": "application/json", "X-Default": "default-value"}
         assert result == expected
 
     def test_empty_request_headers(self):
@@ -324,7 +279,7 @@ def test_none_request_headers(self):
         expected = {"Content-Type": "application/json"}
         assert result == expected
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_base_headers_not_modified(self, mock_settings):
         """Test that original base_headers dictionary is not modified."""
         mock_settings.enable_header_passthrough = True
@@ -347,7 +302,7 @@ def test_base_headers_not_modified(self, mock_settings):
         assert "Content-Type" in result
         assert "X-Tenant-Id" in result
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_multiple_auth_type_conflicts(self, mock_settings, caplog):
         """Test various auth type conflict scenarios."""
         mock_settings.enable_header_passthrough = True
@@ -376,13 +331,12 @@ def test_multiple_auth_type_conflicts(self, mock_settings, caplog):
             if auth_type in ["basic", "bearer"]:
                 # Authorization should be blocked
                 assert "Authorization" not in result
-                assert any("Skipping Authorization header passthrough" in record.message
-                          for record in caplog.records)
+                assert any("Skipping Authorization header passthrough" in record.message for record in caplog.records)
             else:
                 # Authorization should pass through
                 assert result.get("Authorization") == "Bearer token"
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_complex_mixed_scenario(self, mock_settings):
         """Test complex scenario with multiple headers, conflicts, and overrides."""
         mock_settings.enable_header_passthrough = True
@@ -398,28 +352,20 @@ def test_complex_mixed_scenario(self, mock_settings):
         mock_gateway.name = "complex-gateway"
 
         request_headers = {
-            "authorization": "Bearer token",    # Blocked by basic auth
-            "x-global": "global-value",        # Not in gateway config, ignored
-            "x-gateway": "gateway-value",      # Should pass through
-            "x-conflict": "conflict-value",    # Should pass through (in both configs)
-            "x-random": "random-value"         # Not configured, ignored
-        }
-        base_headers = {
-            "Content-Type": "application/json",
-            "User-Agent": "MCPGateway/1.0"
+            "authorization": "Bearer token",  # Blocked by basic auth
+            "x-global": "global-value",  # Not in gateway config, ignored
+            "x-gateway": "gateway-value",  # Should pass through
+            "x-conflict": "conflict-value",  # Should pass through (in both configs)
+            "x-random": "random-value",  # Not configured, ignored
         }
+        base_headers = {"Content-Type": "application/json", "User-Agent": "MCPGateway/1.0"}
 
         result = get_passthrough_headers(request_headers, base_headers, mock_db, mock_gateway)
 
-        expected = {
-            "Content-Type": "application/json",
-            "User-Agent": "MCPGateway/1.0",
-            "X-Gateway": "gateway-value",
-            "X-Conflict": "conflict-value"
-        }
+        expected = {"Content-Type": "application/json", "User-Agent": "MCPGateway/1.0", "X-Gateway": "gateway-value", "X-Conflict": "conflict-value"}
         assert result == expected
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_database_query_called_correctly(self, mock_settings):
         """Test that database is queried correctly for GlobalConfig."""
         mock_settings.enable_header_passthrough = True
@@ -435,7 +381,7 @@ def test_database_query_called_correctly(self, mock_settings):
         mock_db.query.assert_called_once_with(GlobalConfig)
         mock_db.query.return_value.first.assert_called_once()
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_logging_levels(self, mock_settings, caplog):
         """Test that appropriate log levels are used for different scenarios."""
         mock_settings.enable_header_passthrough = True
@@ -450,10 +396,7 @@ def test_logging_levels(self, mock_settings, caplog):
         mock_gateway.auth_type = "basic"
         mock_gateway.name = "test-gateway"
 
-        request_headers = {
-            "authorization": "Bearer token",  # Will be blocked by basic auth
-            "x-conflict": "request-value"     # Will conflict with base header
-        }
+        request_headers = {"authorization": "Bearer token", "x-conflict": "request-value"}  # Will be blocked by basic auth  # Will conflict with base header
         base_headers = {"X-Conflict": "base-value"}  # Conflicts with x-conflict
 
         with caplog.at_level(logging.WARNING):
diff --git a/tests/unit/mcpgateway/utils/test_passthrough_headers_fixed.py b/tests/unit/mcpgateway/utils/test_passthrough_headers_fixed.py
index 4bcf95b0..5aa68f57 100644
--- a/tests/unit/mcpgateway/utils/test_passthrough_headers_fixed.py
+++ b/tests/unit/mcpgateway/utils/test_passthrough_headers_fixed.py
@@ -14,18 +14,16 @@
 import logging
 from unittest.mock import Mock, patch
 
-# Third-Party
-import pytest
-
 # First-Party
-from mcpgateway.db import Gateway as DbGateway, GlobalConfig
+from mcpgateway.db import Gateway as DbGateway
+from mcpgateway.db import GlobalConfig
 from mcpgateway.utils.passthrough_headers import get_passthrough_headers
 
 
 class TestPassthroughHeaders:
     """Test suite for HTTP header passthrough functionality."""
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_basic_header_passthrough_global_config(self, mock_settings):
         """Test basic header passthrough with global configuration."""
         mock_settings.enable_header_passthrough = True
@@ -36,23 +34,15 @@ def test_basic_header_passthrough_global_config(self, mock_settings):
         mock_global_config.passthrough_headers = ["X-Tenant-Id", "X-Trace-Id"]
         mock_db.query.return_value.first.return_value = mock_global_config
 
-        request_headers = {
-            "x-tenant-id": "acme-corp",
-            "x-trace-id": "trace-456",
-            "user-agent": "TestClient/1.0"  # Not in allowed headers
-        }
+        request_headers = {"x-tenant-id": "acme-corp", "x-trace-id": "trace-456", "user-agent": "TestClient/1.0"}  # Not in allowed headers
         base_headers = {"Content-Type": "application/json"}
 
         result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
-        expected = {
-            "Content-Type": "application/json",
-            "X-Tenant-Id": "acme-corp",
-            "X-Trace-Id": "trace-456"
-        }
+        expected = {"Content-Type": "application/json", "X-Tenant-Id": "acme-corp", "X-Trace-Id": "trace-456"}
         assert result == expected
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_gateway_specific_override(self, mock_settings):
         """Test that gateway-specific headers override global configuration."""
         mock_settings.enable_header_passthrough = True
@@ -67,22 +57,15 @@ def test_gateway_specific_override(self, mock_settings):
         mock_gateway.passthrough_headers = ["X-Custom-Header"]
         mock_gateway.auth_type = None
 
-        request_headers = {
-            "x-custom-header": "custom-value",
-            "x-tenant-id": "should-be-ignored",  # Not in gateway config
-            "x-trace-id": "also-ignored"
-        }
+        request_headers = {"x-custom-header": "custom-value", "x-tenant-id": "should-be-ignored", "x-trace-id": "also-ignored"}  # Not in gateway config
         base_headers = {"Content-Type": "application/json"}
 
         result = get_passthrough_headers(request_headers, base_headers, mock_db, mock_gateway)
 
-        expected = {
-            "Content-Type": "application/json",
-            "X-Custom-Header": "custom-value"
-        }
+        expected = {"Content-Type": "application/json", "X-Custom-Header": "custom-value"}
         assert result == expected
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_authorization_conflict_basic_auth(self, mock_settings, caplog):
         """Test that Authorization header is blocked when gateway uses basic auth."""
         mock_settings.enable_header_passthrough = True
@@ -97,27 +80,20 @@ def test_authorization_conflict_basic_auth(self, mock_settings, caplog):
         mock_gateway.auth_type = "basic"
         mock_gateway.name = "test-gateway"
 
-        request_headers = {
-            "authorization": "Bearer should-be-blocked",
-            "x-tenant-id": "acme-corp"
-        }
+        request_headers = {"authorization": "Bearer should-be-blocked", "x-tenant-id": "acme-corp"}
         base_headers = {"Content-Type": "application/json"}
 
         with caplog.at_level(logging.WARNING):
             result = get_passthrough_headers(request_headers, base_headers, mock_db, mock_gateway)
 
         # Authorization should be blocked, X-Tenant-Id should pass through
-        expected = {
-            "Content-Type": "application/json",
-            "X-Tenant-Id": "acme-corp"
-        }
+        expected = {"Content-Type": "application/json", "X-Tenant-Id": "acme-corp"}
         assert result == expected
 
         # Check warning was logged
-        assert any("Skipping Authorization header passthrough due to basic auth" in record.message
-                  for record in caplog.records)
+        assert any("Skipping Authorization header passthrough due to basic auth" in record.message for record in caplog.records)
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_authorization_conflict_bearer_auth(self, mock_settings, caplog):
         """Test that Authorization header is blocked when gateway uses bearer auth."""
         mock_settings.enable_header_passthrough = True
@@ -143,8 +119,7 @@ def test_authorization_conflict_bearer_auth(self, mock_settings, caplog):
         assert result == expected
 
         # Check warning was logged
-        assert any("Skipping Authorization header passthrough due to bearer auth" in record.message
-                  for record in caplog.records)
+        assert any("Skipping Authorization header passthrough due to bearer auth" in record.message for record in caplog.records)
 
     def test_feature_disabled_by_default(self):
         """Test that feature is disabled by default."""
@@ -160,7 +135,7 @@ def test_feature_disabled_by_default(self):
         # Database should not be queried when feature is disabled
         mock_db.query.assert_not_called()
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_case_insensitive_header_matching(self, mock_settings):
         """Test that header matching works with lowercase request headers."""
         mock_settings.enable_header_passthrough = True
@@ -171,17 +146,11 @@ def test_case_insensitive_header_matching(self, mock_settings):
         mock_db.query.return_value.first.return_value = mock_global_config
 
         # Request headers are expected to be normalized to lowercase
-        request_headers = {
-            "x-tenant-id": "mixed-case-value",  # Lowercase key
-            "authorization": "bearer lowercase-header"
-        }
+        request_headers = {"x-tenant-id": "mixed-case-value", "authorization": "bearer lowercase-header"}  # Lowercase key
         base_headers = {}
 
         result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
         # Headers should preserve config case in output keys
-        expected = {
-            "X-Tenant-ID": "mixed-case-value",
-            "Authorization": "bearer lowercase-header"
-        }
+        expected = {"X-Tenant-ID": "mixed-case-value", "Authorization": "bearer lowercase-header"}
         assert result == expected
diff --git a/tests/unit/mcpgateway/utils/test_passthrough_headers_security.py b/tests/unit/mcpgateway/utils/test_passthrough_headers_security.py
index 0b27b67d..eafd8273 100644
--- a/tests/unit/mcpgateway/utils/test_passthrough_headers_security.py
+++ b/tests/unit/mcpgateway/utils/test_passthrough_headers_security.py
@@ -6,22 +6,22 @@
 Authors: Mihai Criveti
 """
 
-import pytest
+# Standard
 from unittest.mock import Mock, patch
 
+# First-Party
 from mcpgateway.utils.passthrough_headers import (
     get_passthrough_headers,
+    MAX_HEADER_VALUE_LENGTH,
     sanitize_header_value,
     validate_header_name,
-    HEADER_NAME_REGEX,
-    MAX_HEADER_VALUE_LENGTH,
 )
 
 
 class TestHeaderSecurity:
     """Test security features of header passthrough."""
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_feature_flag_disabled_by_default(self, mock_settings):
         """Test that the feature is disabled by default for security."""
         mock_settings.enable_header_passthrough = False
@@ -72,14 +72,14 @@ def test_validate_header_name_injection_prevention(self):
         """Test that header name validation prevents injection."""
         malicious_names = [
             "Valid-Name\r\nX-Injected: value",  # Newline injection
-            "Name With Spaces",                  # Spaces not allowed
-            "Name_With_Underscores",            # Underscores not allowed
-            "Name.With.Dots",                   # Dots not allowed
-            "Name:With:Colons",                 # Colons not allowed
-            "Name/With/Slashes",                # Slashes not allowed
-            "Name@With@Symbols",                # Special chars not allowed
-            "",                                 # Empty string
-            "Name\x00WithNull",                 # Null byte
+            "Name With Spaces",  # Spaces not allowed
+            "Name_With_Underscores",  # Underscores not allowed
+            "Name.With.Dots",  # Dots not allowed
+            "Name:With:Colons",  # Colons not allowed
+            "Name/With/Slashes",  # Slashes not allowed
+            "Name@With@Symbols",  # Special chars not allowed
+            "",  # Empty string
+            "Name\x00WithNull",  # Null byte
         ]
 
         for malicious_name in malicious_names:
@@ -100,7 +100,7 @@ def test_validate_header_name_allows_safe_names(self):
         for safe_name in safe_names:
             assert validate_header_name(safe_name), f"Should allow: {safe_name!r}"
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_header_validation_applied_in_passthrough(self, mock_settings, caplog):
         """Test that header validation is applied during passthrough."""
         mock_settings.enable_header_passthrough = True
@@ -109,27 +109,23 @@ def test_header_validation_applied_in_passthrough(self, mock_settings, caplog):
         mock_db.query.return_value.first.return_value = None  # No global config
         mock_settings.default_passthrough_headers = ["Invalid Header Name", "Valid-Header"]
 
-        request_headers = {
-            "invalid header name": "should-be-rejected",
-            "valid-header": "should-pass"
-        }
+        request_headers = {"invalid header name": "should-be-rejected", "valid-header": "should-pass"}
         base_headers = {"Content-Type": "application/json"}
 
+        # Standard
         import logging
+
         with caplog.at_level(logging.WARNING):
             result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
         # Only valid header should pass through
-        expected = {
-            "Content-Type": "application/json",
-            "Valid-Header": "should-pass"
-        }
+        expected = {"Content-Type": "application/json", "Valid-Header": "should-pass"}
         assert result == expected
 
         # Should log warning about invalid header name
         assert any("Invalid header name" in record.message for record in caplog.records)
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_header_sanitization_applied_in_passthrough(self, mock_settings, caplog):
         """Test that header sanitization is applied during passthrough."""
         mock_settings.enable_header_passthrough = True
@@ -139,21 +135,16 @@ def test_header_sanitization_applied_in_passthrough(self, mock_settings, caplog)
         mock_settings.default_passthrough_headers = ["X-Test"]
 
         # Request with dangerous header value
-        request_headers = {
-            "x-test": "value\r\nwith\x01dangerous\x02chars"
-        }
+        request_headers = {"x-test": "value\r\nwith\x01dangerous\x02chars"}
         base_headers = {"Content-Type": "application/json"}
 
         result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
         # Header value should be sanitized
-        expected = {
-            "Content-Type": "application/json",
-            "X-Test": "valuewithdangerouschars"  # Sanitized
-        }
+        expected = {"Content-Type": "application/json", "X-Test": "valuewithdangerouschars"}  # Sanitized
         assert result == expected
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_empty_sanitized_header_skipped(self, mock_settings, caplog):
         """Test that headers that become empty after sanitization are skipped."""
         mock_settings.enable_header_passthrough = True
@@ -163,12 +154,12 @@ def test_empty_sanitized_header_skipped(self, mock_settings, caplog):
         mock_settings.default_passthrough_headers = ["X-Test"]
 
         # Header with only dangerous characters
-        request_headers = {
-            "x-test": "\r\n\x01\x02\x03   "  # Only control chars and whitespace
-        }
+        request_headers = {"x-test": "\r\n\x01\x02\x03   "}  # Only control chars and whitespace
         base_headers = {"Content-Type": "application/json"}
 
+        # Standard
         import logging
+
         with caplog.at_level(logging.WARNING):
             result = get_passthrough_headers(request_headers, base_headers, mock_db)
 
@@ -182,7 +173,7 @@ def test_empty_sanitized_header_skipped(self, mock_settings, caplog):
     def test_sanitization_exception_handling(self, caplog):
         """Test that sanitization handles edge cases gracefully."""
         # Test with non-string input (should not happen in practice)
-        with patch('mcpgateway.utils.passthrough_headers.sanitize_header_value') as mock_sanitize:
+        with patch("mcpgateway.utils.passthrough_headers.sanitize_header_value") as mock_sanitize:
             mock_sanitize.side_effect = Exception("Test error")
 
             mock_settings = Mock()
@@ -192,14 +183,12 @@ def test_sanitization_exception_handling(self, caplog):
             mock_db = Mock()
             mock_db.query.return_value.first.return_value = None
 
-            with patch('mcpgateway.utils.passthrough_headers.settings', mock_settings):
+            with patch("mcpgateway.utils.passthrough_headers.settings", mock_settings):
+                # Standard
                 import logging
+
                 with caplog.at_level(logging.WARNING):
-                    result = get_passthrough_headers(
-                        {"x-test": "value"},
-                        {"Content-Type": "application/json"},
-                        mock_db
-                    )
+                    result = get_passthrough_headers({"x-test": "value"}, {"Content-Type": "application/json"}, mock_db)
 
                 # Should skip the header due to sanitization error
                 expected = {"Content-Type": "application/json"}
@@ -209,15 +198,17 @@ def test_regex_pattern_security(self):
         """Test that the regex pattern is secure against ReDoS attacks."""
         # Test with potentially problematic input
         problematic_inputs = [
-            "A" * 1000,                    # Very long string
-            "A-" * 500,                    # Repeated pattern
-            "A" + "-" * 1000 + "B",       # Long middle section
+            "A" * 1000,  # Very long string
+            "A-" * 500,  # Repeated pattern
+            "A" + "-" * 1000 + "B",  # Long middle section
         ]
 
+        # Standard
         import time
+
         for test_input in problematic_inputs:
             start_time = time.time()
-            result = validate_header_name(test_input)
+            validate_header_name(test_input)
             end_time = time.time()
 
             # Should complete quickly (less than 1 second)
@@ -226,7 +217,7 @@ def test_regex_pattern_security(self):
             # Our regex doesn't restrict length, so long valid patterns will pass
             # This is by design - length limiting is handled by sanitization
 
-    @patch('mcpgateway.utils.passthrough_headers.settings')
+    @patch("mcpgateway.utils.passthrough_headers.settings")
     def test_authorization_header_security(self, mock_settings, caplog):
         """Test security around Authorization header handling."""
         mock_settings.enable_header_passthrough = True
@@ -244,7 +235,9 @@ def test_authorization_header_security(self, mock_settings, caplog):
         request_headers = {"authorization": "Bearer potentially-leaked-token"}
         base_headers = {}
 
+        # Standard
         import logging
+
         with caplog.at_level(logging.WARNING):
             result = get_passthrough_headers(request_headers, base_headers, mock_db, mock_gateway)
 
@@ -272,12 +265,8 @@ def test_case_sensitivity_security(self):
             mock_db = Mock()
             mock_db.query.return_value.first.return_value = None
 
-            with patch('mcpgateway.utils.passthrough_headers.settings', mock_settings):
-                result = get_passthrough_headers(
-                    {request_case: "test-value"},
-                    {},
-                    mock_db
-                )
+            with patch("mcpgateway.utils.passthrough_headers.settings", mock_settings):
+                result = get_passthrough_headers({request_case: "test-value"}, {}, mock_db)
 
                 # Should match and use config case
                 assert config_case in result
@@ -296,7 +285,7 @@ def test_memory_safety_with_large_inputs(self):
         mock_db = Mock()
         mock_db.query.return_value.first.return_value = None
 
-        with patch('mcpgateway.utils.passthrough_headers.settings', mock_settings):
+        with patch("mcpgateway.utils.passthrough_headers.settings", mock_settings):
             # Should handle large inputs without crashing
             result = get_passthrough_headers(large_request_headers, {}, mock_db)
 
@@ -328,33 +317,37 @@ class TestConfigSecurity:
 
     def test_environment_variable_json_parsing(self):
         """Test JSON parsing of environment variables."""
-        from mcpgateway.config import Settings
-        import os
+        # Standard
         import json
 
+        # First-Party
+        from mcpgateway.config import Settings
+
         # Test with valid JSON
         test_headers = ["X-Test-1", "X-Test-2"]
         # Test JSON parsing through direct instantiation
-        with patch('os.environ.get', return_value=json.dumps(test_headers)):
+        with patch("os.environ.get", return_value=json.dumps(test_headers)):
             settings = Settings()
             assert settings.default_passthrough_headers == test_headers
 
     def test_environment_variable_csv_fallback(self):
         """Test CSV fallback for environment variables."""
+        # First-Party
         from mcpgateway.config import Settings
-        import os
 
         # Test CSV parsing by simulating the __init__ logic directly
         # since pydantic tries JSON first and fails
-        settings = Settings()
+        Settings()
 
         # Manually call the parsing logic that would be triggered by env var
-        with patch('os.environ.get', return_value='X-Test-1,X-Test-2,X-Test-3'):
+        with patch("os.environ.get", return_value="X-Test-1,X-Test-2,X-Test-3"):
             # Simulate what happens in Settings.__init__
-            default_value = 'X-Test-1,X-Test-2,X-Test-3'
+            default_value = "X-Test-1,X-Test-2,X-Test-3"
             try:
                 # Try JSON parsing first - this should fail
+                # Standard
                 import json
+
                 parsed = json.loads(default_value)
             except json.JSONDecodeError:
                 # Fallback to comma-separated parsing - this should work
@@ -364,15 +357,17 @@ def test_environment_variable_csv_fallback(self):
 
     def test_environment_variable_security_validation(self):
         """Test that environment variable parsing validates header names."""
-        from mcpgateway.config import Settings
-        import os
+        # Standard
         import json
 
+        # First-Party
+        from mcpgateway.config import Settings
+
         # Test with malicious header names
         malicious_headers = ["Valid-Header", "Invalid Header Name", "Another@Bad#Name"]
 
         # Test with malicious headers through direct instantiation
-        with patch.dict('os.environ', {'DEFAULT_PASSTHROUGH_HEADERS': json.dumps(malicious_headers)}, clear=False):
+        with patch.dict("os.environ", {"DEFAULT_PASSTHROUGH_HEADERS": json.dumps(malicious_headers)}, clear=False):
             settings = Settings()
 
             # Should include all headers (validation happens during use, not config)
diff --git a/tests/unit/mcpgateway/utils/test_redis_isready.py b/tests/unit/mcpgateway/utils/test_redis_isready.py
index 28ac47c1..a5749246 100644
--- a/tests/unit/mcpgateway/utils/test_redis_isready.py
+++ b/tests/unit/mcpgateway/utils/test_redis_isready.py
@@ -325,7 +325,7 @@ def fail(**kwargs):
 
     monkeypatch.setattr(redis_isready_mod, "wait_for_redis_ready", fail)
     monkeypatch.setattr(redis_isready_mod.settings, "cache_type", "redis")
-    with pytest.raises(SystemExit) as exc:
+    with pytest.raises(SystemExit):
         try:
             redis_isready_mod.main()
         except RuntimeError:
diff --git a/tests/unit/mcpgateway/validation/test_tags.py b/tests/unit/mcpgateway/validation/test_tags.py
index d509be5e..a8a97d39 100644
--- a/tests/unit/mcpgateway/validation/test_tags.py
+++ b/tests/unit/mcpgateway/validation/test_tags.py
@@ -6,8 +6,8 @@
 Authors: Mihai Criveti
 """
 
-import pytest
 
+# First-Party
 from mcpgateway.validation.tags import TagValidator, validate_tags_field