read_multiple_files
Read multiple files simultaneously to retrieve their contents efficiently. Specify file paths and optional encoding to get a dictionary mapping each path to its content or error message.
Instructions
Read multiple files at once.
Args:
paths: List of file paths to read
encoding: File encoding (default: utf-8)
ctx: MCP context
Returns:
Dictionary mapping file paths to contents or error messages
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| paths | Yes | ||
| encoding | No | utf-8 |
Implementation Reference
- mcp_filesystem/server.py:113-142 (handler)MCP tool registration and handler for 'read_multiple_files'. This is the entry point decorated with @mcp.tool(), which receives parameters, calls the core operations method, formats exceptions for JSON compatibility, and returns the results.@mcp.tool() async def read_multiple_files( paths: List[str], ctx: Context, encoding: str = "utf-8" ) -> Dict[str, str]: """Read multiple files at once. Args: paths: List of file paths to read encoding: File encoding (default: utf-8) ctx: MCP context Returns: Dictionary mapping file paths to contents or error messages """ try: components = get_components() results = await components["operations"].read_multiple_files(paths, encoding) # Convert exceptions to strings for JSON serialization formatted_results = {} for path, result in results.items(): if isinstance(result, Exception): formatted_results[path] = f"Error: {str(result)}" else: formatted_results[path] = result return formatted_results except Exception as e: return {"error": str(e)}
- mcp_filesystem/operations.py:206-237 (handler)Core implementation of read_multiple_files in FileOperations class. Validates paths, reads file contents asynchronously, catches exceptions per file, and returns a dictionary of path to content or exception.async def read_multiple_files( self, paths: List[Union[str, Path]], encoding: str = "utf-8" ) -> Dict[str, Union[str, Exception]]: """Read multiple files at once. Args: paths: List of file paths encoding: Text encoding (default: utf-8) Returns: Dictionary mapping file paths to contents or exceptions """ # Explicitly type-annotate the results to help mypy results: Dict[str, Union[str, Exception]] = {} for path in paths: try: abs_path, allowed = await self.validator.validate_path(path) if not allowed: # Create an error and store it error_msg = f"Path outside allowed directories: {path}" results[str(path)] = ValueError(error_msg) continue content = await anyio.to_thread.run_sync( partial(abs_path.read_text, encoding=encoding) ) results[str(path)] = content except Exception as e: results[str(path)] = e return results