Skip to content

Commit 775a985

Browse files
authored
Merge pull request #5479 from modelcontextprotocol/v2/chore/5468-python-ruff-0-17
chore(python): adopt ruff 0.17 and clear its new lint findings
2 parents 6ab7e7c + e04e527 commit 775a985

26 files changed

Lines changed: 191 additions & 163 deletions

‎src/fetch/pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ build-backend = "hatchling.build"
4040
[tool.uv]
4141
dev-dependencies = [
4242
"pyright>=1.1.389",
43-
"ruff>=0.7.3",
43+
"ruff>=0.17.3",
4444
"pytest>=8.0.0",
4545
"pytest-asyncio>=0.21.0",
4646
"pytest-cov>=7.1.0",

‎src/fetch/src/mcp_server_fetch/server.py‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,31 +29,30 @@
2929
import zlib
3030
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
3131
from contextlib import asynccontextmanager
32-
from typing import Annotated, Any, Tuple
3332
from importlib.metadata import version
33+
from typing import Annotated, Any
3434
from urllib.parse import urlparse, urlunparse
3535

3636
import httpx
37-
from pydantic import TypeAdapter, ValidationError
3837
import markdownify
3938
import readabilipy.simple_json
40-
from .readability_js import extract_article
4139
from bs4 import BeautifulSoup, Tag
42-
from .allowlist import normalize_allowed_hosts, refuse_unlisted_destination
4340
from mcp.server import MCPServer, ServerRequestContext
4441
from mcp.server.context import CallNext, HandlerResult, ServerMiddleware
4542
from mcp.server.mcpserver.exceptions import ToolError
4643
from mcp.shared.exceptions import MCPError
44+
from mcp.types import INVALID_PARAMS, ToolAnnotations
45+
from protego import Protego
46+
from pydantic import AnyUrl, Field, TypeAdapter, ValidationError
47+
48+
from .allowlist import normalize_allowed_hosts, refuse_unlisted_destination
49+
from .readability_js import extract_article
4750
from .timeout import (
4851
DEFAULT_TIMEOUT_MS,
4952
MAX_TIMEOUT_MS,
5053
MIN_TIMEOUT_MS,
5154
timeout_ms_from_env,
5255
)
53-
from mcp.types import INVALID_PARAMS, ToolAnnotations
54-
from protego import Protego
55-
from pydantic import AnyUrl, Field
56-
5756
from .title import with_page_title
5857

5958
# The version this server reports in serverInfo, read from the installed
@@ -751,7 +750,7 @@ async def fetch_url(
751750
allowed_hosts: tuple[str, ...] = (),
752751
check_robots_txt: bool = False,
753752
use_readability_js: bool = True,
754-
) -> Tuple[str, str]:
753+
) -> tuple[str, str]:
755754
"""
756755
Fetch the URL and return the content in a form ready for the LLM, as well as a prefix string with status information.
757756

‎src/fetch/tests/harness.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@
1818
import ipaddress
1919
import socket
2020
import tempfile
21+
from collections.abc import AsyncIterator, Callable
2122
from contextlib import asynccontextmanager
2223
from dataclasses import dataclass, field
2324
from pathlib import Path
24-
from typing import Any, AsyncIterator, Callable, Union
25+
from typing import Any
2526
from unittest.mock import patch
2627

2728
import anyio
@@ -41,7 +42,7 @@
4142
import mcp_server_fetch.server as server_module
4243
from mcp_server_fetch import readability_js
4344

44-
Responder = Union[httpx.Response, Callable[[httpx.Request], httpx.Response]]
45+
Responder = httpx.Response | Callable[[httpx.Request], httpx.Response]
4546

4647
# A globally routable address (documentation ranges are not global, so they
4748
# would be refused by the private-address guard).
@@ -178,7 +179,7 @@ def private_tempdir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
178179

179180
async def raw_request(
180181
method: str, params: dict[str, Any]
181-
) -> Union[JSONRPCResponse, JSONRPCError]:
182+
) -> JSONRPCResponse | JSONRPCError:
182183
"""Send one request exactly as given, bypassing the client's own checks.
183184
184185
`ClientSession` validates what it sends, so a malformed request (a list as
@@ -194,7 +195,7 @@ async def raw_request(
194195
async def fake_stdio_server() -> AsyncIterator[Any]:
195196
yield server_streams
196197

197-
async def receive(request_id: int) -> Union[JSONRPCResponse, JSONRPCError]:
198+
async def receive(request_id: int) -> JSONRPCResponse | JSONRPCError:
198199
async for item in client_read:
199200
assert isinstance(item, SessionMessage)
200201
message = item.message

‎src/fetch/tests/test_allowed_hosts.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import httpx
1616
import pytest
17-
from mcp.types import CallToolResult
17+
from mcp.types import CallToolResult, TextContent
1818

1919
import mcp_server_fetch
2020
from mcp_server_fetch.allowlist import (
@@ -268,8 +268,9 @@ async def test_prompt_refuses_unlisted_host_and_its_redirects(web: FakeWeb) -> N
268268
direct = await session.get_prompt("fetch", {"url": OTHER})
269269
redirected = await session.get_prompt("fetch", {"url": PAGE})
270270
for prompt in (direct, redirected):
271-
text = prompt.messages[0].content
272-
assert getattr(text, "text") == refused(OTHER, "other.example.org")
271+
content = prompt.messages[0].content
272+
assert isinstance(content, TextContent)
273+
assert content.text == refused(OTHER, "other.example.org")
273274
assert web.urls() == [PAGE]
274275

275276

‎src/fetch/tests/test_entrypoints.py‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
import os
1111
import runpy
1212
import sys
13+
from collections.abc import Iterator
1314
from pathlib import Path
15+
from typing import TextIO
1416
from unittest.mock import AsyncMock, MagicMock
1517

1618
import pytest
@@ -99,15 +101,24 @@ def console_script() -> Path:
99101
return bin_dir / name
100102

101103

102-
async def test_console_script_serves_over_stdio() -> None:
104+
@pytest.fixture
105+
def devnull() -> Iterator[TextIO]:
106+
# The server's stderr sink, opened here rather than in the async test,
107+
# where a blocking open() would stall the event loop (ruff ASYNC230).
108+
with open(os.devnull, "w") as sink:
109+
yield sink
110+
111+
112+
async def test_console_script_serves_over_stdio(devnull: TextIO) -> None:
103113
# The one subprocess smoke: the installed console script boots and answers
104114
# tools/list over real stdio. Everything else runs in-process.
105115
script = console_script()
106116
assert script.exists(), f"console script not installed at {script}"
107117
params = StdioServerParameters(command=str(script), args=[])
108-
with open(os.devnull, "w") as devnull:
109-
async with stdio_client(params, errlog=devnull) as (read, write):
110-
async with ClientSession(read, write) as session:
111-
await session.initialize()
112-
tools = await session.list_tools()
118+
async with (
119+
stdio_client(params, errlog=devnull) as (read, write),
120+
ClientSession(read, write) as session,
121+
):
122+
await session.initialize()
123+
tools = await session.list_tools()
113124
assert [t.name for t in tools.tools] == ["fetch"]

‎src/fetch/tests/test_html_charset.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ async def test_a_declaration_past_the_first_1024_bytes_is_ignored(
182182
body = (
183183
f"<html><head>{padding}<meta charset=windows-1251></head>"
184184
f"<body><p>{JAPANESE}</p></body></html>"
185-
).encode("utf-8")
185+
).encode()
186186
assert JAPANESE in await fetch(web, page(body), raw=True)
187187

188188

‎src/fetch/tests/test_protocol.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -726,14 +726,18 @@ async def test_url_is_normalized_by_pydantic(web: FakeWeb) -> None:
726726
(
727727
0,
728728
10,
729-
"abcdefghij\n\n<error>Content truncated. Call the fetch tool with a "
730-
"start_index of 10 to get more content.</error>",
729+
(
730+
"abcdefghij\n\n<error>Content truncated. Call the fetch tool with a "
731+
"start_index of 10 to get more content.</error>"
732+
),
731733
),
732734
(
733735
10,
734736
10,
735-
"klmnopqrst\n\n<error>Content truncated. Call the fetch tool with a "
736-
"start_index of 20 to get more content.</error>",
737+
(
738+
"klmnopqrst\n\n<error>Content truncated. Call the fetch tool with a "
739+
"start_index of 20 to get more content.</error>"
740+
),
737741
),
738742
# A window that ends exactly at the end: full length, nothing remains.
739743
(16, 10, "qrstuvwxyz"),

‎src/fetch/uv.lock‎

Lines changed: 22 additions & 22 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/git/pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ build-backend = "hatchling.build"
3636
[dependency-groups]
3737
dev = [
3838
"pyright>=1.1.407",
39-
"ruff>=0.7.3",
39+
"ruff>=0.17.3",
4040
"pytest>=8.0.0",
4141
"pytest-cov>=7.1.0",
4242
"pytest-asyncio>=1.4.0",

‎src/git/src/mcp_server_git/__init__.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
import click
2-
from pathlib import Path
31
import logging
42
import sys
3+
from pathlib import Path
4+
5+
import click
6+
57
from .server import serve
68

79

@@ -21,7 +23,7 @@ def main(repository: Path | None, verbose: bool) -> None:
2123
"""MCP Git Server - Git functionality for MCP"""
2224
import asyncio
2325

24-
logging_level = logging.WARN
26+
logging_level = logging.WARNING
2527
if verbose == 1:
2628
logging_level = logging.INFO
2729
elif verbose >= 2:

0 commit comments

Comments
 (0)