codeocean-mcp-server 0.13.0__tar.gz → 0.14.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/CHANGELOG.md +9 -0
  2. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/PKG-INFO +3 -1
  3. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/README.md +2 -0
  4. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/pyproject.toml +2 -2
  5. codeocean_mcp_server-0.14.0/src/codeocean_mcp_server/file_utils.py +77 -0
  6. codeocean_mcp_server-0.14.0/src/codeocean_mcp_server/logging_config.py +70 -0
  7. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/src/codeocean_mcp_server/server.py +2 -1
  8. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/src/codeocean_mcp_server/tools/computations.py +12 -5
  9. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/src/codeocean_mcp_server/tools/data_assets.py +12 -5
  10. codeocean_mcp_server-0.14.0/tests/test_file_utils.py +172 -0
  11. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/tests/test_logging_config.py +36 -5
  12. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/uv.lock +1 -1
  13. codeocean_mcp_server-0.13.0/src/codeocean_mcp_server/file_utils.py +0 -21
  14. codeocean_mcp_server-0.13.0/src/codeocean_mcp_server/logging_config.py +0 -67
  15. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/.gitignore +0 -0
  16. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/.python-version +0 -0
  17. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/LICENSE +0 -0
  18. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/RELEASE.md +0 -0
  19. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/src/codeocean_mcp_server/__init__.py +0 -0
  20. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/src/codeocean_mcp_server/client.py +0 -0
  21. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/src/codeocean_mcp_server/models.py +0 -0
  22. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/src/codeocean_mcp_server/search.py +0 -0
  23. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/src/codeocean_mcp_server/tools/__init__.py +0 -0
  24. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/src/codeocean_mcp_server/tools/capsules.py +0 -0
  25. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/src/codeocean_mcp_server/tools/custom_metadata.py +0 -0
  26. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/tests/bedrock_call.py +0 -0
  27. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/tests/bedrock_tools_converter.py +0 -0
  28. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/tests/conftest.py +0 -0
  29. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/tests/mcp_client.py +0 -0
  30. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/tests/test_http_transport.py +0 -0
  31. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/tests/test_multi_tool_calling.py +0 -0
  32. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/tests/test_search.py +0 -0
  33. {codeocean_mcp_server-0.13.0 → codeocean_mcp_server-0.14.0}/tests/test_tool_calling.py +0 -0
@@ -1,6 +1,15 @@
1
1
  CHANGELOG
2
2
  =========
3
3
 
4
+ ## 0.14.0 (2026-11-18)
5
+
6
+ - [#53](https://github.com/codeocean/codeocean-mcp-server/pull/53) feat: read file tails and pages with offset/limit
7
+ - [#51](https://github.com/codeocean/codeocean-mcp-server/pull/51) fix: keep the build off hatchling 1.32.1
8
+
9
+ ## 0.13.1 (2026-09-16)
10
+
11
+ - [#49](https://github.com/codeocean/codeocean-mcp-server/pull/49) feat: take the log level from `LOG_LEVEL`
12
+
4
13
  ## 0.13.0 (2026-09-16)
5
14
 
6
15
  - [#46](https://github.com/codeocean/codeocean-mcp-server/pull/46) fix: bump mcp to 1.29.x and refresh locked dependencies
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeocean-mcp-server
3
- Version: 0.13.0
3
+ Version: 0.14.0
4
4
  Summary: Code Ocean MCP Server
5
5
  Project-URL: Homepage, https://github.com/codeocean/codeocean-mcp-server
6
6
  Project-URL: Issues, https://github.com/codeocean/codeocean-mcp-server/issues
@@ -249,3 +249,5 @@ This will start a web server where you can:
249
249
  The MCP server supports custom log formatting through the `LOG_FORMAT` environment variable. This allows you to control the format of log messages output by the server.
250
250
  **Example Format Strings:** `"%(asctime)s %(levelname)s [%(name)s] %(message)s"`.
251
251
  If `LOG_FORMAT` is not set, the server uses FastMCP's default logging configuration.
252
+
253
+ The `LOG_LEVEL` environment variable sets the level the server logs at: `DEBUG`, `INFO` (the default), `WARNING`, `ERROR` or `CRITICAL`. Raising it drops the record the server writes for every request it serves, which is worth doing when the server runs alongside a caller that logs those requests itself.
@@ -230,3 +230,5 @@ This will start a web server where you can:
230
230
  The MCP server supports custom log formatting through the `LOG_FORMAT` environment variable. This allows you to control the format of log messages output by the server.
231
231
  **Example Format Strings:** `"%(asctime)s %(levelname)s [%(name)s] %(message)s"`.
232
232
  If `LOG_FORMAT` is not set, the server uses FastMCP's default logging configuration.
233
+
234
+ The `LOG_LEVEL` environment variable sets the level the server logs at: `DEBUG`, `INFO` (the default), `WARNING`, `ERROR` or `CRITICAL`. Raising it drops the record the server writes for every request it serves, which is worth doing when the server runs alongside a caller that logs those requests itself.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codeocean-mcp-server"
3
- version = "0.13.0"
3
+ version = "0.14.0"
4
4
  authors = [{ name = "Code Ocean", email = "dev@codeocean.com" }]
5
5
  description = "Code Ocean MCP Server"
6
6
  readme = "README.md"
@@ -37,7 +37,7 @@ Changelog = "https://github.com/codeocean/codeocean-mcp-server/blob/main/CHANGEL
37
37
  codeocean-mcp-server = "codeocean_mcp_server.server:main"
38
38
 
39
39
  [build-system]
40
- requires = ["hatchling"]
40
+ requires = ["hatchling!=1.32.1"]
41
41
  build-backend = "hatchling.build"
42
42
 
43
43
  [tool.hatch.build.targets.sdist]
@@ -0,0 +1,77 @@
1
+ """File utilities for downloading and reading files."""
2
+
3
+ import codecs
4
+ import re
5
+ from typing import Optional
6
+
7
+ import requests
8
+ from pydantic import BaseModel
9
+
10
+ # Constants
11
+ MAX_FILE_CONTENT_LENGTH = 50_000 # Maximum number of bytes to read per call
12
+ DOWNLOAD_TIMEOUT = 30
13
+
14
+
15
+ class FileContent(BaseModel):
16
+ """Reads up to 50,000 bytes per call, trimmed to whole lines.
17
+
18
+ A negative `offset` reads from the end of the file (use it for logs and errors): the last `abs(offset)`
19
+ bytes, at most `limit`. `next_offset` is where to continue reading (null at end of file).
20
+ """
21
+
22
+ content: str
23
+ offset: int
24
+ next_offset: Optional[int] = None
25
+ total_bytes: Optional[int] = None
26
+
27
+
28
+ def download_and_read_file(url: str, offset: int = 0, limit: int = MAX_FILE_CONTENT_LENGTH) -> FileContent:
29
+ """Read up to `limit` bytes of the file at `url`, from `offset`, or from the end when `offset` is negative.
30
+
31
+ A tail is trimmed to start on a whole line; a non-negative offset starts exactly where asked, so paging
32
+ with `next_offset` loses nothing. A partial last line is dropped when the range doesn't reach the end of
33
+ the file. A single line longer than the range is returned as-is. A binary file is reported, not returned.
34
+ A failed download raises, so the tool call fails instead of returning the error as content.
35
+ """
36
+ limit = max(1, min(limit, MAX_FILE_CONTENT_LENGTH))
37
+ byte_range = f"bytes=-{min(-offset, limit)}" if offset < 0 else f"bytes={offset}-{offset + limit - 1}"
38
+ with requests.get(url, headers={"Range": byte_range}, timeout=DOWNLOAD_TIMEOUT, stream=True) as response:
39
+ if response.status_code == 416:
40
+ return FileContent(content="", offset=max(offset, 0))
41
+ response.raise_for_status()
42
+
43
+ content_range = re.fullmatch(r"bytes (\d+)-\d+/(\d+)", response.headers.get("Content-Range", ""))
44
+ if response.status_code == 206 and content_range:
45
+ start, total = int(content_range[1]), int(content_range[2])
46
+ elif response.status_code == 206:
47
+ start, total = max(offset, 0), None
48
+ else: # server ignored Range
49
+ start, total = 0, int(response.headers["Content-Length"]) if "Content-Length" in response.headers else None
50
+ data = response.raw.read(limit)
51
+ if total is not None:
52
+ at_end = start + len(data) >= total
53
+ else: # a 206 tail runs to the end of the file even when its start is unknown
54
+ at_end = len(data) < limit or (offset < 0 and response.status_code == 206)
55
+
56
+ if b"\0" in data:
57
+ size = f"{total:,} bytes" if total is not None else "unknown size"
58
+ content = f"Binary file ({size}), not shown. Download it from its file URLs instead."
59
+ return FileContent(content=content, offset=start, total_bytes=total)
60
+
61
+ # A tail starts after its first newline; a tail inside the last line is kept as-is.
62
+ first_newline = data.find(b"\n", 0, len(data) - 1)
63
+ if offset < 0 and start > 0 and first_newline != -1:
64
+ data, start = data[first_newline + 1 :], start + first_newline + 1
65
+
66
+ if not at_end and not data.endswith(b"\n") and b"\n" in data:
67
+ data = data[: data.rfind(b"\n") + 1]
68
+
69
+ # Text without a declared charset is read as UTF-8, not requests' ISO-8859-1 default.
70
+ has_charset = "charset" in response.headers.get("Content-Type", "")
71
+ encoding = response.encoding if has_charset and response.encoding else "utf-8"
72
+ # A character cut off at the end of the range stays unread for the next page.
73
+ decoder = codecs.getincrementaldecoder(encoding)(errors="ignore")
74
+ content = decoder.decode(data, final=at_end)
75
+ end = start + len(data) - len(decoder.getstate()[0])
76
+
77
+ return FileContent(content=content, offset=start, next_offset=None if at_end else end, total_bytes=total)
@@ -0,0 +1,70 @@
1
+ import logging
2
+ import os
3
+ import sys
4
+
5
+
6
+ def log_level() -> str:
7
+ """Return the level to log at, from the LOG_LEVEL environment variable.
8
+
9
+ FastMCP has to be constructed with it as well: it configures uvicorn's loggers from its own level,
10
+ which it takes as a constructor argument that wins over its FASTMCP_LOG_LEVEL environment variable.
11
+
12
+ Environment variables:
13
+ LOG_LEVEL: DEBUG, INFO, WARNING, ERROR or CRITICAL (optional, defaults to INFO)
14
+ """
15
+ return os.getenv("LOG_LEVEL", "").strip().upper() or "INFO"
16
+
17
+
18
+ def configure_logging(transport: str = "stdio") -> None:
19
+ """Configure the root logger from the LOG_LEVEL and LOG_FORMAT environment variables.
20
+
21
+ LOG_LEVEL sets the root logger's level. LOG_FORMAT gives the root logger a stderr handler
22
+ with that format and, for a transport uvicorn serves, applies the same format to uvicorn's
23
+ own loggers. With neither set, logging is left as it is, for whoever embeds the server, or
24
+ else FastMCP with its defaults, to configure. Must be called before FastMCP is constructed.
25
+
26
+ Args:
27
+ transport: The transport the server is about to serve on.
28
+
29
+ Environment variables:
30
+ LOG_LEVEL: DEBUG, INFO, WARNING, ERROR or CRITICAL (optional, defaults to INFO)
31
+ LOG_FORMAT: Python logging format string (optional)
32
+
33
+ Examples:
34
+ - "%(asctime)s agent %(levelname)s [%(name)s] %(message)s"
35
+ - "%(levelname)s: %(message)s"
36
+ - "[%(name)s] %(message)s"
37
+
38
+ Note:
39
+ A malformed format string fails here, at startup. One that names a field records do not
40
+ have fails with a ValueError when the first record is formatted instead.
41
+
42
+ """
43
+ log_format = os.getenv("LOG_FORMAT", "").strip()
44
+
45
+ # The level is applied when either variable is set: a handler of our own leaves FastMCP's own
46
+ # logging.basicConfig() with nothing to do, so the level would otherwise stay at the default.
47
+ if log_format or "LOG_LEVEL" in os.environ:
48
+ logging.root.setLevel(log_level())
49
+
50
+ if not log_format:
51
+ return
52
+
53
+ handler = logging.StreamHandler(sys.stderr)
54
+ handler.setFormatter(logging.Formatter(log_format))
55
+ logging.root.addHandler(handler)
56
+
57
+ if transport == "stdio":
58
+ return
59
+
60
+ # Serving over HTTP, uvicorn logs through its own loggers, which it gives handlers that do not
61
+ # propagate to the root logger. It configures them from this dictionary, which FastMCP leaves
62
+ # at its default value, so its contents have to be replaced to be reached at all. The import
63
+ # is local because uvicorn, like in FastMCP itself, is only needed for the transports it serves.
64
+ from uvicorn.config import LOGGING_CONFIG
65
+
66
+ LOGGING_CONFIG["formatters"]["default"]["fmt"] = log_format
67
+ # Access records carry the request in fields of their own rather than in the message.
68
+ LOGGING_CONFIG["formatters"]["access"]["fmt"] = log_format.replace(
69
+ "%(message)s", '%(client_addr)s - "%(request_line)s" %(status_code)s'
70
+ )
@@ -9,7 +9,7 @@ from codeocean import CodeOcean
9
9
  from mcp.server.fastmcp import FastMCP
10
10
 
11
11
  from codeocean_mcp_server.client import RequestScopedClient
12
- from codeocean_mcp_server.logging_config import configure_logging
12
+ from codeocean_mcp_server.logging_config import configure_logging, log_level
13
13
  from codeocean_mcp_server.tools import (
14
14
  capsules,
15
15
  computations,
@@ -80,6 +80,7 @@ def main():
80
80
  host=args.host,
81
81
  port=args.port,
82
82
  stateless_http=True,
83
+ log_level=log_level(),
83
84
  )
84
85
 
85
86
  if stdio:
@@ -8,7 +8,7 @@ from codeocean.computation import (
8
8
  from codeocean.data_asset import DataAssetAttachParams, DataAssetAttachResults
9
9
  from mcp.server.fastmcp import FastMCP
10
10
 
11
- from codeocean_mcp_server.file_utils import download_and_read_file
11
+ from codeocean_mcp_server.file_utils import MAX_FILE_CONTENT_LENGTH, FileContent, download_and_read_file
12
12
  from codeocean_mcp_server.models import dataclass_to_pydantic
13
13
 
14
14
  RunParamsModel = dataclass_to_pydantic(RunParams)
@@ -56,11 +56,18 @@ def add_tools(mcp: FastMCP, client: CodeOcean): # noqa: C901
56
56
  """Get view and download URLs for a specific result file from computation."""
57
57
  return client.computations.get_result_file_urls(computation_id, file_path)
58
58
 
59
- @mcp.tool(description=("Use when you want to read the content of a file from a computation"))
60
- def download_and_read_a_file_from_computation(computation_id: str, file_path: str) -> str:
61
- """Download a file using the provided URL and return its content."""
59
+ @mcp.tool(
60
+ description="Use when you want to read the content of a file from a computation. " + str(FileContent.__doc__)
61
+ )
62
+ def download_and_read_a_file_from_computation(
63
+ computation_id: str,
64
+ file_path: str,
65
+ offset: int = 0,
66
+ limit: int = MAX_FILE_CONTENT_LENGTH,
67
+ ) -> FileContent:
68
+ """Read a byte range of a file, from the end when offset is negative."""
62
69
  file_urls = client.computations.get_result_file_urls(computation_id, file_path)
63
- return download_and_read_file(file_urls.download_url)
70
+ return download_and_read_file(file_urls.download_url, offset, limit)
64
71
 
65
72
  @mcp.tool(description=client.computations.rename_computation.__doc__)
66
73
  def rename_computation(computation_id: str, name: str) -> None:
@@ -12,7 +12,7 @@ from codeocean.data_asset import (
12
12
  )
13
13
  from mcp.server.fastmcp import FastMCP
14
14
 
15
- from codeocean_mcp_server.file_utils import download_and_read_file
15
+ from codeocean_mcp_server.file_utils import MAX_FILE_CONTENT_LENGTH, FileContent, download_and_read_file
16
16
  from codeocean_mcp_server.models import dataclass_to_pydantic
17
17
  from codeocean_mcp_server.search import DataAssetSearchResults
18
18
 
@@ -57,11 +57,18 @@ def add_tools(mcp: FastMCP, client: CodeOcean):
57
57
  """Get view and download URLs for a specific file in a data asset."""
58
58
  return client.data_assets.get_data_asset_file_urls(data_asset_id, file_path)
59
59
 
60
- @mcp.tool(description=("Use when you want to read the content of a file from a data asset"))
61
- def download_and_read_a_file_from_data_asset(data_asset_id: str, file_path: str) -> str:
62
- """Download a file using the provided URL and return its content."""
60
+ @mcp.tool(
61
+ description="Use when you want to read the content of a file from a data asset. " + str(FileContent.__doc__)
62
+ )
63
+ def download_and_read_a_file_from_data_asset(
64
+ data_asset_id: str,
65
+ file_path: str,
66
+ offset: int = 0,
67
+ limit: int = MAX_FILE_CONTENT_LENGTH,
68
+ ) -> FileContent:
69
+ """Read a byte range of a file, from the end when offset is negative."""
63
70
  file_urls = client.data_assets.get_data_asset_file_urls(data_asset_id, file_path)
64
- return download_and_read_file(file_urls.download_url)
71
+ return download_and_read_file(file_urls.download_url, offset, limit)
65
72
 
66
73
  @mcp.tool(description=client.data_assets.get_permissions.__doc__)
67
74
  def get_data_asset_permissions(data_asset_id: str) -> Permissions:
@@ -0,0 +1,172 @@
1
+ """Unit tests for file_utils module."""
2
+
3
+ import re
4
+ import threading
5
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6
+
7
+ import pytest
8
+ import requests
9
+
10
+ from codeocean_mcp_server.file_utils import MAX_FILE_CONTENT_LENGTH, FileContent, download_and_read_file
11
+
12
+ LOG = b"".join(f"line {i:04d}\n".encode() for i in range(6000)) # 6,000 lines of 10 bytes
13
+ ERROR = b"Traceback (most recent call last):\nValueError: boom\n"
14
+
15
+
16
+ class _Handler(BaseHTTPRequestHandler):
17
+ """Serve the requested body, honoring Range headers unless the path is /no-range.
18
+
19
+ A /no-content-range path answers 206 without the Content-Range header.
20
+ """
21
+
22
+ files: dict[str, bytes] = {}
23
+ content_types: dict[str, str] = {}
24
+
25
+ def do_GET(self): # noqa: N802
26
+ self.content_type = self.content_types.get(self.path, "text/plain; charset=utf-8")
27
+ body = self.files[self.path.removeprefix("/no-range").removeprefix("/no-content-range")]
28
+ match = re.fullmatch(r"bytes=(\d*)-(\d*)", self.headers.get("Range", ""))
29
+ if self.path.startswith("/no-range") or not match:
30
+ return self._send(200, body, {})
31
+ first, last = match.groups()
32
+ if first:
33
+ start, end = int(first), min(int(last or len(body) - 1), len(body) - 1)
34
+ else:
35
+ start, end = max(len(body) - int(last), 0), len(body) - 1
36
+ if start >= len(body):
37
+ return self._send(416, b"", {"Content-Range": f"bytes */{len(body)}"})
38
+ headers = {"Content-Range": f"bytes {start}-{end}/{len(body)}"}
39
+ self._send(206, body[start : end + 1], {} if self.path.startswith("/no-content-range") else headers)
40
+
41
+ def _send(self, status, body, headers):
42
+ self.send_response(status)
43
+ self.send_header("Content-Type", self.content_type)
44
+ self.send_header("Content-Length", str(len(body)))
45
+ for name, value in headers.items():
46
+ self.send_header(name, value)
47
+ self.end_headers()
48
+ self.wfile.write(body)
49
+
50
+ def log_message(self, *args):
51
+ pass
52
+
53
+
54
+ @pytest.fixture(scope="module")
55
+ def base_url():
56
+ """Run a local file server for the tests."""
57
+ _Handler.files = {
58
+ "/log": LOG + ERROR,
59
+ "/small": b"one\ntwo\nthree\n",
60
+ "/long-last-line": b"short\n" + b"y" * 1000 + b"\n",
61
+ "/long-first-line": b"x" * 150 + b"\nend\n",
62
+ "/binary": b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR",
63
+ "/no-charset": "naïve → ✓\n".encode(),
64
+ }
65
+ _Handler.content_types = {"/no-charset": "text/plain"}
66
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
67
+ threading.Thread(target=server.serve_forever, daemon=True).start()
68
+ yield f"http://127.0.0.1:{server.server_port}"
69
+ server.shutdown()
70
+
71
+
72
+ def test_reads_from_the_start_by_default(base_url):
73
+ """A default read returns the first window, cut at a whole line, with where to continue."""
74
+ result = download_and_read_file(f"{base_url}/log")
75
+ assert result.offset == 0
76
+ assert result.total_bytes == len(LOG + ERROR)
77
+ assert result.content.startswith("line 0000\n")
78
+ assert result.content.endswith("\n")
79
+ assert result.next_offset == len(result.content.encode())
80
+ assert len(result.content.encode()) <= MAX_FILE_CONTENT_LENGTH
81
+
82
+
83
+ def test_negative_offset_reads_the_tail(base_url):
84
+ """A negative offset returns the end of the file, starting on a whole line."""
85
+ result = download_and_read_file(f"{base_url}/log", offset=-100)
86
+ assert result.content.endswith(ERROR.decode())
87
+ assert result.content.startswith("line ")
88
+ assert result.next_offset is None
89
+ assert result.offset + len(result.content.encode()) == result.total_bytes
90
+
91
+
92
+ def test_paging_with_next_offset_reads_the_whole_file(base_url):
93
+ """Following next_offset reads every byte once, in order."""
94
+ content, offset = "", 0
95
+ while offset is not None:
96
+ result = download_and_read_file(f"{base_url}/log", offset=offset, limit=4096)
97
+ assert result.offset == offset
98
+ content += result.content
99
+ offset = result.next_offset
100
+ assert content == (LOG + ERROR).decode()
101
+
102
+
103
+ def test_offset_past_the_end_returns_empty_content(base_url):
104
+ """An offset at or past the end of the file is not an error."""
105
+ assert download_and_read_file(f"{base_url}/small", offset=14) == FileContent(content="", offset=14)
106
+
107
+
108
+ def test_tail_inside_the_last_line_is_returned_as_is(base_url):
109
+ """A tail shorter than the file's last line returns the end of that line, not nothing."""
110
+ assert download_and_read_file(f"{base_url}/long-last-line", offset=-20) == FileContent(
111
+ content="y" * 19 + "\n", offset=987, next_offset=None, total_bytes=1007
112
+ )
113
+
114
+
115
+ def test_paging_keeps_a_line_longer_than_the_limit(base_url):
116
+ """Following next_offset through a line longer than one page returns the whole line."""
117
+ content, offset = "", 0
118
+ while offset is not None:
119
+ result = download_and_read_file(f"{base_url}/long-first-line", offset=offset, limit=100)
120
+ assert result.offset == offset
121
+ content += result.content
122
+ offset = result.next_offset
123
+ assert content == "x" * 150 + "\nend\n"
124
+
125
+
126
+ def test_server_ignoring_range_falls_back_to_the_start(base_url):
127
+ """A 200 response is read from the start of the file."""
128
+ result = download_and_read_file(f"{base_url}/no-range/log", offset=-100, limit=25)
129
+ assert result == FileContent(
130
+ content="line 0000\nline 0001\n", offset=0, next_offset=20, total_bytes=len(LOG + ERROR)
131
+ )
132
+
133
+
134
+ def test_missing_content_range_reads_without_a_total(base_url):
135
+ """A 206 without Content-Range is read from the requested offset, with an unknown size."""
136
+ assert download_and_read_file(f"{base_url}/no-content-range/small", offset=4, limit=6) == FileContent(
137
+ content="two\n", offset=4, next_offset=8, total_bytes=None
138
+ )
139
+
140
+
141
+ def test_tail_without_content_range_ends_at_the_end_of_the_file(base_url):
142
+ """A 206 tail without Content-Range has no next_offset, since a suffix range always reaches the end."""
143
+ result = download_and_read_file(f"{base_url}/no-content-range/log", offset=-100, limit=20)
144
+ assert result.next_offset is None
145
+ assert result.content.endswith("ValueError: boom\n")
146
+
147
+
148
+ def test_limit_below_one_still_advances(base_url):
149
+ """A zero or negative limit reads one byte instead of returning a next_offset that never moves."""
150
+ for limit in (0, -5):
151
+ assert download_and_read_file(f"{base_url}/small", limit=limit) == FileContent(
152
+ content="o", offset=0, next_offset=1, total_bytes=14
153
+ )
154
+
155
+
156
+ def test_binary_file_is_reported_not_returned(base_url):
157
+ """A file with NUL bytes returns a short notice with its size and no next_offset."""
158
+ result = download_and_read_file(f"{base_url}/binary")
159
+ assert result.content.startswith("Binary file (16 bytes)")
160
+ assert result.next_offset is None
161
+ assert result.total_bytes == 16
162
+
163
+
164
+ def test_text_without_charset_is_read_as_utf8(base_url):
165
+ """A text/plain response with no charset is decoded as UTF-8, not ISO-8859-1."""
166
+ assert download_and_read_file(f"{base_url}/no-charset").content == "naïve → ✓\n"
167
+
168
+
169
+ def test_download_error_raises():
170
+ """A failed download fails the call instead of returning the error as file content."""
171
+ with pytest.raises(requests.RequestException):
172
+ download_and_read_file("http://127.0.0.1:1/missing")
@@ -1,4 +1,4 @@
1
- """End-to-end test for LOG_FORMAT, over the transport that brings a logger of its own along."""
1
+ """End-to-end tests for LOG_LEVEL and LOG_FORMAT, over the transport that brings a logger of its own along."""
2
2
 
3
3
  import os
4
4
  import re
@@ -30,9 +30,15 @@ def _wait_until_listening(port: int, timeout: float = 30.0):
30
30
  raise TimeoutError(f"MCP server did not start listening on port {port}")
31
31
 
32
32
 
33
- def _serve_and_request(port: int) -> str:
34
- """Serve over streamable HTTP, make one request, and return everything the server logged."""
35
- env = {**os.environ, "CODEOCEAN_DOMAIN": "test-domain", "LOG_FORMAT": LOG_FORMAT}
33
+ def _serve_and_request(**variables: str) -> str:
34
+ """Serve over streamable HTTP with exactly these LOG_* variables set, request once, and return the log.
35
+
36
+ Whatever LOG_LEVEL and LOG_FORMAT the test run itself has are dropped, so that only the test
37
+ decides what the server logs.
38
+ """
39
+ env = {name: value for name, value in os.environ.items() if name not in ("LOG_LEVEL", "LOG_FORMAT")}
40
+ env |= {"CODEOCEAN_DOMAIN": "test-domain", **variables}
41
+ port = _free_port()
36
42
  process = subprocess.Popen(
37
43
  [sys.executable, SERVER_SCRIPT_PATH, "--transport", "streamable-http", "--port", str(port)],
38
44
  env=env,
@@ -55,7 +61,7 @@ def _serve_and_request(port: int) -> str:
55
61
 
56
62
  def test_log_format_applies_to_uvicorns_own_records():
57
63
  """Uvicorn brings its own logging configuration, in whose format these records would be."""
58
- log = _serve_and_request(_free_port())
64
+ log = _serve_and_request(LOG_FORMAT=LOG_FORMAT)
59
65
 
60
66
  timestamp = r"^[\d-]{10} [\d:,]+"
61
67
  assert re.search(rf"{timestamp} server INFO \[uvicorn\.error\] Uvicorn running", log, re.MULTILINE)
@@ -66,3 +72,28 @@ def test_log_format_applies_to_uvicorns_own_records():
66
72
  log,
67
73
  re.MULTILINE,
68
74
  )
75
+
76
+
77
+ def test_log_level_quiets_a_request_the_caller_does_not_want_logged():
78
+ """Both loggers have to be reached: uvicorn takes its level from FastMCP, the SDK from the root."""
79
+ log = _serve_and_request(LOG_LEVEL="WARNING", LOG_FORMAT=LOG_FORMAT)
80
+
81
+ assert "[uvicorn.access]" not in log
82
+ assert "[uvicorn.error]" not in log
83
+ assert "server INFO" not in log
84
+ # The rejected request is still warned about: the level drops the chatter, not the record
85
+ # that says something went wrong.
86
+ assert "server WARNING [" in log
87
+
88
+
89
+ def test_log_level_applies_without_a_log_format():
90
+ """Without LOG_FORMAT the records are FastMCP's own, and the level has to reach those too."""
91
+ noisy = _serve_and_request()
92
+ quiet = _serve_and_request(LOG_LEVEL="WARNING")
93
+
94
+ # FastMCP's rich-formatted records wrap, so match a word of each.
95
+ assert "Uvicorn running" in noisy
96
+ assert "streamable_http_manager" in noisy
97
+ assert "Uvicorn running" not in quiet
98
+ assert "streamable_http_manager" not in quiet
99
+ assert "Invalid Content-Type" in quiet # The rejected request's WARNING is still logged.
@@ -852,7 +852,7 @@ wheels = [
852
852
 
853
853
  [[package]]
854
854
  name = "codeocean-mcp-server"
855
- version = "0.13.0"
855
+ version = "0.14.0"
856
856
  source = { editable = "." }
857
857
  dependencies = [
858
858
  { name = "anyio" },
@@ -1,21 +0,0 @@
1
- """File utilities for downloading and reading files."""
2
-
3
- import requests
4
-
5
- # Constants
6
- MAX_FILE_CONTENT_LENGTH = 50_000 # Maximum length of content to read
7
- DOWNLOAD_TIMEOUT = 30
8
-
9
-
10
- def download_and_read_file(url: str) -> str:
11
- """Download file from URL and return first MAX_FILE_CONTENT_LENGTH characters."""
12
- try:
13
- with requests.get(url, timeout=DOWNLOAD_TIMEOUT, stream=True) as response:
14
- response.raise_for_status()
15
- # Read the first 'bytes_to_read' bytes of the response
16
- data = response.raw.read(MAX_FILE_CONTENT_LENGTH)
17
- # Decode the data into a string using the response's encoding
18
- return data.decode(response.encoding or "utf-8", errors="ignore")
19
-
20
- except requests.exceptions.RequestException as e:
21
- return f"Download error: {e}"
@@ -1,67 +0,0 @@
1
- import logging
2
- import os
3
- import sys
4
-
5
-
6
- def configure_logging(transport: str = "stdio") -> None:
7
- """Configure logging based on LOG_FORMAT environment variable.
8
-
9
- If LOG_FORMAT is set, configures the root logger with a StreamHandler
10
- using the specified format string, and, for a transport uvicorn serves,
11
- applies the same format to uvicorn's own loggers. This must be called
12
- before FastMCP initialization to ensure our configuration takes
13
- precedence.
14
-
15
- If LOG_FORMAT is not set or is empty, does nothing and lets FastMCP
16
- configure logging with its default settings.
17
-
18
- Args:
19
- transport: The transport the server is about to serve on.
20
-
21
- Environment variables:
22
- LOG_FORMAT: Python logging format string (optional)
23
-
24
- Examples:
25
- - "%(asctime)s agent %(levelname)s [%(name)s] %(message)s"
26
- - "%(levelname)s: %(message)s"
27
- - "[%(name)s] %(message)s"
28
-
29
- Note:
30
- Invalid format strings will cause errors when log records are formatted,
31
- not during initialization. This typically results in ValueError, KeyError,
32
- or AttributeError being raised when logging occurs.
33
-
34
- """
35
- log_format = os.getenv("LOG_FORMAT", "").strip()
36
-
37
- # If LOG_FORMAT is not set or empty, do nothing
38
- if not log_format:
39
- return
40
-
41
- # Create handler for stderr (same as FastMCP default)
42
- handler = logging.StreamHandler(sys.stderr)
43
-
44
- # Create formatter with the specified format string
45
- # This will raise an error if the format string is invalid (fail fast)
46
- formatter = logging.Formatter(log_format)
47
- handler.setFormatter(formatter)
48
-
49
- # Configure root logger
50
- # This must be done before FastMCP calls logging.basicConfig()
51
- logging.root.addHandler(handler)
52
- logging.root.setLevel(logging.INFO)
53
-
54
- if transport == "stdio":
55
- return
56
-
57
- # Serving over HTTP, uvicorn logs through its own loggers, which it gives handlers that do not
58
- # propagate to the root logger. It configures them from this dictionary, which FastMCP leaves
59
- # at its default value, so its contents have to be replaced to be reached at all. The import
60
- # is local because uvicorn, like in FastMCP itself, is only needed for the transports it serves.
61
- from uvicorn.config import LOGGING_CONFIG
62
-
63
- LOGGING_CONFIG["formatters"]["default"]["fmt"] = log_format
64
- # Access records carry the request in fields of their own rather than in the message.
65
- LOGGING_CONFIG["formatters"]["access"]["fmt"] = log_format.replace(
66
- "%(message)s", '%(client_addr)s - "%(request_line)s" %(status_code)s'
67
- )