-
Notifications
You must be signed in to change notification settings - Fork 11
feat/file_input_output #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
53d801c
feat/file_input_output
silvestre-perret-bentley 5875dc4
Copilot Review Feedback
silvestre-perret-bentley e36ba4c
improvements after internal feedback
silvestre-perret-bentley 526499d
fix after pr feedback (formula detection + max_output_sheet)
silvestre-perret-bentley 69fbd62
add input_output_collision detection
silvestre-perret-bentley 6e69182
fix tests and linting
silvestre-perret-bentley File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| """ | ||
| --------------------------------------------------------------------------------------------- | ||
| Copyright (c) Bentley Systems, Incorporated. All rights reserved. | ||
| See LICENSE.md in the project root for license terms and full copyright notice. | ||
| --------------------------------------------------------------------------------------------- | ||
|
|
||
| Server-side file I/O for the ``execute_code`` tool. | ||
|
|
||
| All operations run **outside** the sandbox. The sandbox never touches the | ||
| filesystem -- it receives pre-parsed data via ``__input__`` and returns a | ||
| structured value that this module writes to disk. | ||
|
|
||
| Sub-modules | ||
| ----------- | ||
| ``readers`` -- BaseReader, CSVReader, XLSXReader | ||
| ``writers`` -- BaseWriter, CSVWriter, XLSXWriter | ||
| ``models`` -- Pydantic models for return-value validation | ||
| ``validation`` -- validate_return_value, validate_args_allowed_dirs, deep_freeze | ||
| ``helpers`` -- get_allowed_dirs, get_input_data, dispatch functions | ||
| """ | ||
|
|
||
| from openstaad_mcp.file_io.helpers import ( | ||
| get_allowed_dirs, | ||
| get_input_data, | ||
| read_input_file, | ||
| write_output_file, | ||
| ) | ||
| from openstaad_mcp.file_io.readers import CSVReader, XLSXReader | ||
| from openstaad_mcp.file_io.validation import ( | ||
| deep_freeze, | ||
| validate_args_allowed_dirs, | ||
| validate_return_value, | ||
| ) | ||
| from openstaad_mcp.file_io.writers import CSVWriter | ||
|
|
||
| __all__ = [ | ||
| "CSVReader", | ||
| "CSVWriter", | ||
| "XLSXReader", | ||
| "deep_freeze", | ||
| "get_allowed_dirs", | ||
| "get_input_data", | ||
| "read_input_file", | ||
| "validate_args_allowed_dirs", | ||
| "validate_return_value", | ||
| "write_output_file", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| """ | ||
| --------------------------------------------------------------------------------------------- | ||
| Copyright (c) Bentley Systems, Incorporated. All rights reserved. | ||
| See LICENSE.md in the project root for license terms and full copyright notice. | ||
| --------------------------------------------------------------------------------------------- | ||
| """ | ||
| # ── File I/O limits ────────────────────────────────────────────────────── | ||
|
|
||
| # Maximum file size on disk (bytes) for read operations. | ||
| MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024 # 50 MB | ||
|
|
||
| # Row / column / sheet caps for input files. | ||
| MAX_INPUT_ROWS = 100_000 | ||
| MAX_INPUT_COLUMNS = 500 | ||
| MAX_INPUT_SHEETS = 50 | ||
|
|
||
| # Row / column / sheet caps for output (return value → file). | ||
| MAX_OUTPUT_ROWS = 100_000 | ||
| MAX_OUTPUT_COLUMNS = 500 | ||
| MAX_OUTPUT_SHEETS = 20 | ||
|
josha-bentley marked this conversation as resolved.
Outdated
|
||
|
|
||
| # Excel's own limit on sheet-tab names. | ||
| MAX_SHEET_NAME_LENGTH = 31 | ||
|
|
||
| # Allowed file extensions for file I/O paths. | ||
| ALLOWED_FILE_EXTENSIONS: frozenset[str] = frozenset({".csv", ".xlsx"}) | ||
|
|
||
| # Temp-file naming for atomic writes. | ||
| TEMP_FILE_PREFIX = ".~omcp_" | ||
|
|
||
| # Orphan temp files older than this (seconds) are cleaned up. | ||
| STALE_TEMP_AGE_SECONDS = 3600 | ||
|
|
||
| # Number of sample rows included in summaries returned to the agent. | ||
| SAMPLE_ROW_COUNT = 5 | ||
|
|
||
| # Maximum character length for a single cell value (Excel limit: 32,767 characters). | ||
| MAX_CELL_SIZE = 32_767 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| """ | ||
| --------------------------------------------------------------------------------------------- | ||
| Copyright (c) Bentley Systems, Incorporated. All rights reserved. | ||
| See LICENSE.md in the project root for license terms and full copyright notice. | ||
| --------------------------------------------------------------------------------------------- | ||
|
|
||
| Server-level helpers and public dispatch functions for file I/O.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from fastmcp.server.context import Context | ||
| from mcp.shared.exceptions import McpError | ||
|
|
||
| from openstaad_mcp.file_io.path_validator import FileIOError, parse_roots_to_dirs, validate_io_path | ||
| from openstaad_mcp.file_io.readers import BaseReader, CSVReader, XLSXReader | ||
| from openstaad_mcp.file_io.validation import deep_freeze, validate_return_value | ||
| from openstaad_mcp.file_io.writers import BaseWriter, CSVWriter, XLSXWriter | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| # ═══════════════════════════════════════════════════════════════════════════ | ||
| # Reader/writer factory helpers | ||
| # ═══════════════════════════════════════════════════════════════════════════ | ||
|
|
||
| _READERS: dict[str, type[BaseReader]] = {".csv": CSVReader, ".xlsx": XLSXReader} | ||
| _WRITERS: dict[str, type[BaseWriter]] = {".csv": CSVWriter, ".xlsx": XLSXWriter} | ||
|
|
||
|
|
||
| def _get_reader(path: Path) -> BaseReader: | ||
| ext = path.suffix.lower() | ||
| cls = _READERS.get(ext) | ||
| if cls is None: | ||
| raise FileIOError("UNSUPPORTED_FORMAT", f"Cannot read '{ext}' files") | ||
| return cls(path) | ||
|
|
||
|
|
||
| def _get_writer(path: Path) -> BaseWriter: | ||
| ext = path.suffix.lower() | ||
| cls = _WRITERS.get(ext) | ||
| if cls is None: | ||
| raise FileIOError("UNSUPPORTED_FORMAT", f"Cannot write '{ext}' files") | ||
| return cls(path) | ||
|
|
||
|
|
||
| # ═══════════════════════════════════════════════════════════════════════════ | ||
| # Public dispatch functions | ||
| # ═══════════════════════════════════════════════════════════════════════════ | ||
|
|
||
|
|
||
| def read_input_file( | ||
| path: Path, | ||
| *, | ||
| sheet: str | None = None, | ||
| start_row: int = 0, | ||
| max_rows: int | None = None, | ||
| has_header: bool | None = None, | ||
| ) -> tuple[Any, dict[str, Any]]: | ||
| """Read a CSV or XLSX file and return ``(data, summary)``.""" | ||
| reader = _get_reader(path) | ||
| data = reader.read(start_row=start_row, max_rows=max_rows, sheet=sheet, has_header=has_header) | ||
| summary = reader.build_summary(data) | ||
| return data, summary | ||
|
|
||
|
|
||
| def write_output_file(path: str, data: Any, allowed_dirs: list[Path], *, overwrite: bool = False) -> dict[str, Any]: | ||
| """Validate path, validate return value, write atomically, return summary.""" | ||
| resolved = validate_io_path(path, allowed_dirs, mode="write") | ||
| validate_return_value(resolved, data) | ||
| writer = _get_writer(resolved) | ||
| return writer.write(data, overwrite=overwrite) | ||
|
silvestre-perret-bentley marked this conversation as resolved.
|
||
|
|
||
|
|
||
| # ═══════════════════════════════════════════════════════════════════════════ | ||
| # Server-level helpers (called from server.py) | ||
| # ═══════════════════════════════════════════════════════════════════════════ | ||
|
|
||
|
|
||
| async def get_allowed_dirs( | ||
| ctx: Context, args_allowed_dirs: list[Path], input_path: str | None, output_path: str | None | ||
| ) -> list[Path]: | ||
| """Resolve MCP roots into a list of allowed directories.""" | ||
| logger.debug("Args allowed dirs: %s", args_allowed_dirs) | ||
| allowed_dirs: list[Path] = [Path(el) for el in args_allowed_dirs] | ||
| if input_path is not None or output_path is not None: | ||
| try: | ||
| roots = await ctx.list_roots() | ||
| logger.debug(f"Received MCP roots: {roots}") | ||
| except McpError as exc: | ||
| logger.error(f"Error listing MCP roots: {exc}") | ||
| roots = [] | ||
| allowed_dirs += parse_roots_to_dirs(roots) | ||
| logger.debug(f"Allowed directories for file I/O: {allowed_dirs}") | ||
| return allowed_dirs | ||
|
|
||
|
|
||
| async def get_input_data(input_path: str | None, allowed_dirs: list[Path]) -> tuple[Any, dict[str, Any] | None]: | ||
| """Validate path, read file, freeze data. Returns ``(data, summary)``.""" | ||
| if input_path is None: | ||
| return None, None | ||
| resolved_input = validate_io_path(input_path, allowed_dirs, mode="read") | ||
| data, input_summary = read_input_file(resolved_input) | ||
| return deep_freeze(data), input_summary | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.