diff --git a/src/mcp/client/auth/utils.py b/src/mcp/client/auth/utils.py index d75324f2f..7e67c6e02 100644 --- a/src/mcp/client/auth/utils.py +++ b/src/mcp/client/auth/utils.py @@ -243,7 +243,7 @@ async def handle_registration_response(response: Response) -> OAuthClientInforma # self.context.client_info = client_info # await self.context.storage.set_client_info(client_info) except ValidationError as e: # pragma: no cover - raise OAuthRegistrationError(f"Invalid registration response: {e}") + raise OAuthRegistrationError(f"Invalid registration response: {e}") from e def is_valid_client_metadata_url(url: str | None) -> bool: @@ -336,4 +336,4 @@ async def handle_token_response_scopes( token_response = OAuthToken.model_validate_json(content) return token_response except ValidationError as e: # pragma: no cover - raise OAuthTokenError(f"Invalid token response: {e}") + raise OAuthTokenError(f"Invalid token response: {e}") from e diff --git a/src/mcp/client/session.py b/src/mcp/client/session.py index 0cea454a7..ef52d4332 100644 --- a/src/mcp/client/session.py +++ b/src/mcp/client/session.py @@ -343,9 +343,9 @@ async def _validate_tool_result(self, name: str, result: types.CallToolResult) - try: validate(result.structured_content, output_schema) except ValidationError as e: - raise RuntimeError(f"Invalid structured content returned by tool {name}: {e}") + raise RuntimeError(f"Invalid structured content returned by tool {name}: {e}") from e except SchemaError as e: # pragma: no cover - raise RuntimeError(f"Invalid schema for tool {name}: {e}") # pragma: no cover + raise RuntimeError(f"Invalid schema for tool {name}: {e}") from e # pragma: no cover async def list_prompts(self, *, params: types.PaginatedRequestParams | None = None) -> types.ListPromptsResult: """Send a prompts/list request. diff --git a/src/mcp/server/auth/middleware/client_auth.py b/src/mcp/server/auth/middleware/client_auth.py index 2832f8352..001cddc74 100644 --- a/src/mcp/server/auth/middleware/client_auth.py +++ b/src/mcp/server/auth/middleware/client_auth.py @@ -80,8 +80,8 @@ async def authenticate_request(self, request: Request) -> OAuthClientInformation if basic_client_id != client_id: raise AuthenticationError("Client ID mismatch in Basic auth") - except (ValueError, UnicodeDecodeError, binascii.Error): - raise AuthenticationError("Invalid Basic authentication header") + except (ValueError, UnicodeDecodeError, binascii.Error) as exc: + raise AuthenticationError("Invalid Basic authentication header") from exc elif client.token_endpoint_auth_method == "client_secret_post": raw_form_data = form_data.get("client_secret") diff --git a/src/mcp/server/mcpserver/prompts/base.py b/src/mcp/server/mcpserver/prompts/base.py index e5b2af7d8..b0e67c119 100644 --- a/src/mcp/server/mcpserver/prompts/base.py +++ b/src/mcp/server/mcpserver/prompts/base.py @@ -181,9 +181,9 @@ async def render( else: # pragma: no cover content = pydantic_core.to_json(msg, fallback=str, indent=2).decode() messages.append(Message(role="user", content=content)) - except Exception: # pragma: no cover - raise ValueError(f"Could not convert prompt result to message: {msg}") + except Exception as e: # pragma: no cover + raise ValueError(f"Could not convert prompt result to message: {msg}") from e return messages except Exception as e: # pragma: no cover - raise ValueError(f"Error rendering prompt {self.name}: {e}") + raise ValueError(f"Error rendering prompt {self.name}: {e}") from e diff --git a/src/mcp/server/mcpserver/resources/resource_manager.py b/src/mcp/server/mcpserver/resources/resource_manager.py index 766cf51ae..e9d0ddfc2 100644 --- a/src/mcp/server/mcpserver/resources/resource_manager.py +++ b/src/mcp/server/mcpserver/resources/resource_manager.py @@ -93,7 +93,7 @@ async def get_resource(self, uri: AnyUrl | str, context: Context[LifespanContext try: return await template.create_resource(uri_str, params, context=context) except Exception as e: # pragma: no cover - raise ValueError(f"Error creating resource from template: {e}") + raise ValueError(f"Error creating resource from template: {e}") from e raise ValueError(f"Unknown resource: {uri}") diff --git a/src/mcp/server/mcpserver/resources/templates.py b/src/mcp/server/mcpserver/resources/templates.py index f1ee29a37..edde0c4c4 100644 --- a/src/mcp/server/mcpserver/resources/templates.py +++ b/src/mcp/server/mcpserver/resources/templates.py @@ -130,4 +130,4 @@ async def create_resource( fn=lambda: result, # Capture result in closure ) except Exception as e: - raise ValueError(f"Error creating resource from template: {e}") + raise ValueError(f"Error creating resource from template: {e}") from e diff --git a/src/mcp/server/mcpserver/resources/types.py b/src/mcp/server/mcpserver/resources/types.py index d9e472e36..bb3c2edf7 100644 --- a/src/mcp/server/mcpserver/resources/types.py +++ b/src/mcp/server/mcpserver/resources/types.py @@ -72,7 +72,7 @@ async def read(self) -> str | bytes: else: return pydantic_core.to_json(result, fallback=str, indent=2).decode() except Exception as e: - raise ValueError(f"Error reading resource {self.uri}: {e}") + raise ValueError(f"Error reading resource {self.uri}: {e}") from e @classmethod def from_function( @@ -148,7 +148,7 @@ async def read(self) -> str | bytes: return await anyio.to_thread.run_sync(self.path.read_bytes) return await anyio.to_thread.run_sync(self.path.read_text) except Exception as e: - raise ValueError(f"Error reading file {self.path}: {e}") + raise ValueError(f"Error reading file {self.path}: {e}") from e class HttpResource(Resource): @@ -193,7 +193,7 @@ def list_files(self) -> list[Path]: # pragma: no cover return list(self.path.glob(self.pattern)) if not self.recursive else list(self.path.rglob(self.pattern)) return list(self.path.glob("*")) if not self.recursive else list(self.path.rglob("*")) except Exception as e: - raise ValueError(f"Error listing directory {self.path}: {e}") + raise ValueError(f"Error listing directory {self.path}: {e}") from e async def read(self) -> str: # Always returns JSON string # pragma: no cover """Read the directory listing.""" @@ -202,4 +202,4 @@ async def read(self) -> str: # Always returns JSON string # pragma: no cover file_list = [str(f.relative_to(self.path)) for f in files if f.is_file()] return json.dumps({"files": file_list}, indent=2) except Exception as e: - raise ValueError(f"Error reading directory {self.path}: {e}") + raise ValueError(f"Error reading directory {self.path}: {e}") from e