filesystem.cpp

src/mcp/servers/filesystem.cpp

@file filesystem.cpp @brief Filesystem MCP server — read/write/edit/glob/grep/list_directory.

Owners: @tvanfossen

FilesystemServer

entropic::FilesystemServer::FilesystemServer(const std::filesystem::path &root_dir, const FilesystemConfig &config, const std::string &data_dir, int model_context_bytes=0)

Construct with root directory, config, and data dir.

src/mcp/servers/filesystem.cpp:2053

Source · 26 lines
FilesystemServer::FilesystemServer(
    const fs::path& root_dir,
    const FilesystemConfig& config,
    const std::string& data_dir,
    int model_context_bytes)
    : MCPServerBase("filesystem"),
      root_dir_(fs::weakly_canonical(root_dir)),
      config_(config),
      max_read_bytes_(compute_max_read_bytes(
          config, model_context_bytes)) {

    create_fs_tools(data_dir);
    register_fs_tools();

    // Issue #15 (v2.1.4): load .gitignore + .explorerignore so glob,
    // grep, and read_file can filter out build artifacts and vendor
    // blobs that pre-2.1.4 leaked into results.
    ignore_.load(root_dir_);

    logger->info("FilesystemServer initialized: root={}, "
                 "max_read_bytes={}, ignore_rules={}",
                 root_dir_.string(),
                 max_read_bytes_,
                 ignore_.rule_count());
    log_outside_root_policy();  // v2.13.0: the posture is observable
}
Activity · 5 steps
lines 2064–2064create_fs_tools(data_dir);lines 2065–2065register_fs_tools();lines 2070–2070ignore_.load(root_dir_);lines 2072–2076logger->info("FilesystemServer initialized: root={}, " "max_read_bytes={}, ignore_rules={}", root_dir_.string(), max_read_bytes_, ignore_.rule_count());lines 2077–2077log_outside_root_policy();

Requirements

REQ-MCP-001 REQ-MCP-021 REQ-MCP-022

anchor_key

std::string entropic::ReadFileTool::anchor_key(const std::string &args_json) const override

Anchor key for context deduplication.

src/mcp/servers/filesystem.cpp:1353

Show on the map →

Called by none

Calls none

Source · 5 lines
    std::string anchor_key(
        const std::string& args_json) const override {
        auto args = json::parse(args_json);
        return "file:" + args.at("path").get<std::string>();
    }
Activity · 2 steps
lines 1355–1355auto args = json::parse(args_json);lines 1356–1356return "file:" + args.at("path").get<std::string>();

Requirements

REQ-MCP-001 REQ-MCP-021

any_glob_match

bool entropic::anonymous_namespace{filesystem.cpp}::any_glob_match(const std::string &filename, const std::vector< std::string > &patterns)

Test whether a filename matches any of the brace-expanded patterns.

src/mcp/servers/filesystem.cpp:977

Show on the map →

Called by classify_glob_entry

Calls glob_match

Source · 7 lines
bool any_glob_match(const std::string& filename,
                    const std::vector<std::string>& patterns) {
    for (const auto& p : patterns) {
        if (glob_match(filename, p)) { return true; }
    }
    return false;
}
Activity · 4 steps
lines 979–979◇ for (const auto& p : patterns)lines 980–980◇ if (glob_match(filename, p))lines 980–980return true;lines 982–982return false;

Requirements

REQ-MCP-022

apply_edit

std::string entropic::anonymous_namespace{filesystem.cpp}::apply_edit(const json &args, const std::filesystem::path &resolved, const std::string &display)

Apply an edit operation and return result JSON or error.

src/mcp/servers/filesystem.cpp:1274

Source · 21 lines
std::string apply_edit(const json& args,
                       const std::filesystem::path& resolved,
                       const std::string& display) {
    const bool replace = args.contains("old_string");
    if (replace == args.contains("insert_line")) {
        return make_error("invalid_args", "edit_file takes exactly one of "
            "old_string (STR_REPLACE) or insert_line (INSERT)");
    }
    auto content = read_file_contents(resolved);
    std::string edited;
    json ok;
    auto out = replace ? do_str_replace(args, content, edited, ok)
                       : do_insert(args, content, edited, ok);
    if (out.empty()) {
        write_file_contents(resolved, edited);
        logger->info("Edited file: {} ({})", display, ok["mode"].get<std::string>());
        ok["path"] = display;
        out = ok.dump();
    }
    return out;
}
Activity · 13 steps
lines 1277–1277const bool replace = args.contains("old_string");lines 1278–1278◇ if (replace == args.contains("insert_line"))lines 1279–1280return make_error("invalid_args", "edit_file takes exactly one of " "old_string (STR_REPLACE) or insert_line (INSERT)");lines 1282–1282auto content = read_file_contents(resolved);lines 1283–1283std::string edited;lines 1284–1284json ok;lines 1285–1286auto out = replace ? do_str_replace(args, content, edited, ok) : do_insert(args, content, edited, ok);lines 1287–1287◇ if (out.empty())lines 1288–1288write_file_contents(resolved, edited);lines 1289–1289logger->info("Edited file: {} ({})", display, ok["mode"].get<std::string>());lines 1290–1290ok["path"] = display;lines 1291–1291out = ok.dump();lines 1293–1293return out;

Requirements

REQ-MCP-021

apply_insert

std::string entropic::anonymous_namespace{filesystem.cpp}::apply_insert(const std::string &content, long after, const std::string &new_str)

Insert text AFTER line after (0 = start of file).

src/mcp/servers/filesystem.cpp:949

Show on the map →

Called by do_insert

Calls none

Source · 18 lines
std::string apply_insert(const std::string& content,
                         long after,
                         const std::string& new_str) {
    size_t pos = 0;
    for (long line = 0; line < after; ++line) {
        auto nl = content.find('\n', pos);
        pos = (nl == std::string::npos) ? content.size() : nl + 1;
    }
    std::string text = new_str;
    bool at_unterminated_end = pos == content.size() && !content.empty()
        && content.back() != '\n';
    if (at_unterminated_end) {
        text = "\n" + text;
    } else if (text.empty() || text.back() != '\n') {
        text += '\n';
    }
    return content.substr(0, pos) + text + content.substr(pos);
}
Activity · 12 steps
lines 952–952size_t pos = 0;lines 953–953◇ for (long line = 0; line < after; ++line)lines 954–954auto nl = content.find('\n', pos);lines 955–955pos = (nl == std::string::npos) ? content.size() : nl + 1;lines 957–957std::string text = new_str;lines 958–959bool at_unterminated_end = pos == content.size() && !content.empty() && content.back() != '\n';lines 960–960◇ if (at_unterminated_end)lines 961–961text = "\n" + text;lines 962–962elselines 962–962◇ if (text.empty() || text.back() != '\n')lines 963–963text += '\n';lines 965–965return content.substr(0, pos) + text + content.substr(pos);

Requirements

REQ-MCP-021

apply_str_replace

std::optional< std::string > entropic::anonymous_namespace{filesystem.cpp}::apply_str_replace(const std::string &content, const std::string &old_str, const std::string &new_str, bool replace_all, std::string &error_type)

Replace old_str with new_str in content.

src/mcp/servers/filesystem.cpp:900

Show on the map →

Called by do_str_replace

Calls count_occurrences

Source · 21 lines
apply_str_replace(const std::string& content, const std::string& old_str, const std::string& new_str, bool replace_all, std::string& error_type) {

    int occurrences = count_occurrences(content, old_str);
    if (occurrences == 0) {
        error_type = "no_match";
        return std::nullopt;
    }
    if (!replace_all && occurrences > 1) {
        error_type = "multiple_matches";
        return std::nullopt;
    }

    std::string result = content;
    auto pos = result.find(old_str);
    while (pos != std::string::npos) {
        result.replace(pos, old_str.size(), new_str);
        if (!replace_all) { break; }
        pos = result.find(old_str, pos + new_str.size());
    }
    return result;
}
Activity · 15 steps
lines 902–902int occurrences = count_occurrences(content, old_str);lines 903–903◇ if (occurrences == 0)lines 904–904error_type = "no_match";lines 905–905return std::nullopt;lines 907–907◇ if (!replace_all && occurrences > 1)lines 908–908error_type = "multiple_matches";lines 909–909return std::nullopt;lines 912–912std::string result = content;lines 913–913auto pos = result.find(old_str);lines 914–914◇ while (pos != std::string::npos)lines 915–915result.replace(pos, old_str.size(), new_str);lines 916–916◇ if (!replace_all)lines 916–916break;lines 917–917pos = result.find(old_str, pos + new_str.size());lines 919–919return result;

Requirements

REQ-MCP-021

ask_outside_root_approver

void entropic::FilesystemServer::ask_outside_root_approver(const std::filesystem::path &resolved, PathAccess access, const std::string &tool) const

Put one outside-root access to the approver (v2.13.0).

src/mcp/servers/filesystem.cpp:2346

Show on the map →

Called by authorize_outside_root

Calls access_verb, capi_test_compactor_fn, outside_root_refusal

Source · 23 lines
void FilesystemServer::ask_outside_root_approver(
    const fs::path& resolved, PathAccess access,
    const std::string& tool) const {
    OutsideRootApprover fn = nullptr;
    void* ud = nullptr;
    {
        std::lock_guard<std::mutex> lock(approver_mutex_);
        fn = approver_;
        ud = approver_data_;
    }
    OutsideRootRequest req{resolved.string(), root_dir_.string(),
                           name() + "." + tool, access};
    auto verdict = fn != nullptr ? fn(req, ud)
                                 : OutsideRootVerdict::no_approver;
    if (verdict == OutsideRootVerdict::approved) {
        logger->info("Outside-root {} APPROVED by host: {} ({})",
                     access_verb(access), req.path, req.tool);
    } else {
        auto msg = outside_root_refusal(verdict, req);
        logger->error("Path escape blocked: {}", msg);
        throw std::runtime_error(msg);
    }
}
Activity · 13 steps
lines 2349–2349OutsideRootApprover fn = nullptr;lines 2350–2350void* ud = nullptr;lines 2352–2352std::lock_guard<std::mutex> lock(approver_mutex_);lines 2353–2353fn = approver_;lines 2354–2354ud = approver_data_;lines 2356–2357OutsideRootRequest req{resolved.string(), root_dir_.string(), name() + "." + tool, access};lines 2358–2359auto verdict = fn != nullptr ? fn(req, ud) : OutsideRootVerdict::no_approver;lines 2360–2360◇ if (verdict == OutsideRootVerdict::approved)lines 2361–2362logger->info("Outside-root {} APPROVED by host: {} ({})", access_verb(access), req.path, req.tool);lines 2363–2363elselines 2364–2364auto msg = outside_root_refusal(verdict, req);lines 2365–2365logger->error("Path escape blocked: {}", msg);lines 2366–2366throw std::runtime_error(msg);

Requirements

REQ-MCP-021

authorize_outside_root

void entropic::FilesystemServer::authorize_outside_root(const std::filesystem::path &resolved, PathAccess access, const std::string &tool) const

Decide a path that resolved outside the root (v2.13.0).

src/mcp/servers/filesystem.cpp:2312

Source · 16 lines
void FilesystemServer::authorize_outside_root(
    const fs::path& resolved, PathAccess access,
    const std::string& tool) const {
    auto denied = first_containing(config_.outside_root_deny, resolved);
    auto allowed = first_containing(config_.outside_root_allow, resolved);
    const auto mode = config_.allow_outside_root;
    if (denied.has_value()) {
        refuse_denied(resolved, *denied, access, root_dir_);
    } else if (allowed.has_value() || mode == OutsideRootAccess::allow) {
        log_outside_root_served(resolved, access, allowed);
    } else if (mode == OutsideRootAccess::refuse) {
        refuse_escape(resolved, root_dir_);
    } else {
        ask_outside_root_approver(resolved, access, tool);
    }
}
Activity · 13 steps
lines 2315–2315auto denied = first_containing(config_.outside_root_deny, resolved);lines 2316–2316auto allowed = first_containing(config_.outside_root_allow, resolved);lines 2317–2317const auto mode = config_.allow_outside_root;lines 2318–2318◇ if (denied.has_value())lines 2319–2319refuse_denied(resolved, *denied, access, root_dir_);lines 2320–2320elselines 2320–2320◇ if (allowed.has_value() || mode == OutsideRootAccess::allow)lines 2321–2321log_outside_root_served(resolved, access, allowed);lines 2322–2322elselines 2322–2322◇ if (mode == OutsideRootAccess::refuse)lines 2323–2323refuse_escape(resolved, root_dir_);lines 2324–2324elselines 2325–2325ask_outside_root_approver(resolved, access, tool);

Requirements

REQ-MCP-021

check_read_before_write

std::string entropic::anonymous_namespace{filesystem.cpp}::check_read_before_write(const FileAccessTracker &tracker, const std::string &path)

Enforce read-before-write policy on existing files.

src/mcp/servers/filesystem.cpp:856

Source · 12 lines
std::string check_read_before_write(
    const FileAccessTracker& tracker,
    const std::string& path) {
    const auto session = current_run_session();
    if (fs::exists(path) && !tracker.was_read(session, path)) {
        logger->warn("Read-before-write violation: session='{}' {}",
                     session, path);
        return make_error("read_before_write",
            "File must be read before writing: " + path);
    }
    return "";
}
Activity · 5 steps
lines 859–859const auto session = current_run_session();lines 860–860◇ if (fs::exists(path) && !tracker.was_read(session, path))lines 861–862logger->warn("Read-before-write violation: session='{}' {}", session, path);lines 863–864return make_error("read_before_write", "File must be read before writing: " + path);lines 866–866return "";

Requirements

REQ-MCP-021

check_read_gates

std::string entropic::check_read_gates(FilesystemServer &server, const fs::path &resolved, const std::string &display)

Execute read_file: resolve, size-check, read, hash, track.

src/mcp/servers/filesystem.cpp:1390

Source · 21 lines
std::string check_read_gates(FilesystemServer& server,
                             const fs::path& resolved,
                             const std::string& display) {
    std::string err;
    auto rel = fs::relative(resolved, server.root_dir()).generic_string();
    if (!fs::exists(resolved)) {
        err = make_error("not_found",
            "File not found: " + display
            + ". Use list_directory(\".\") to see available files"
              " in the working directory, or verify the path is"
              " relative to the configured root.");
    } else if (fs::is_directory(resolved)) {
        err = make_error("is_directory",
            "Path is a directory, not a file: " + display);
    } else if (!rel.empty() && server.ignore().is_ignored(rel, false)) {
        err = make_error("ignored",
            "Path '" + rel + "' is excluded by .gitignore or "
            ".explorerignore.");
    }
    return err;
}
Activity · 11 steps
lines 1393–1393std::string err;lines 1394–1394auto rel = fs::relative(resolved, server.root_dir()).generic_string();lines 1395–1395◇ if (!fs::exists(resolved))lines 1396–1400err = make_error("not_found", "File not found: " + display + ". Use list_directory(\".\") to see available files" " in the working directory, or verify the path is" " relative to the configured root.");lines 1401–1401elselines 1401–1401◇ if (fs::is_directory(resolved))lines 1402–1403err = make_error("is_directory", "Path is a directory, not a file: " + display);lines 1404–1404elselines 1404–1404◇ if (!rel.empty() && server.ignore().is_ignored(rel, false))lines 1405–1407err = make_error("ignored", "Path '" + rel + "' is excluded by .gitignore or " ".explorerignore.");lines 1409–1409return err;

Requirements

REQ-MCP-021 REQ-MCP-022

classify_glob_entry

EntryAction entropic::anonymous_namespace{filesystem.cpp}::classify_glob_entry(const fs::directory_entry &entry, const fs::path &root, const std::vector< std::string > &patterns, const IgnoreMatcher *ignore)

Classify a directory_iterator entry against ignore rules and the brace-expanded glob patterns.

src/mcp/servers/filesystem.cpp:1032

Source · 24 lines
EntryAction classify_glob_entry(
    const fs::directory_entry& entry,
    const fs::path& root,
    const std::vector<std::string>& patterns,
    const IgnoreMatcher* ignore) {
    bool is_dir = entry.is_directory();
    EntryAction result = EntryAction::kSkip;
    bool hardcoded_skip = is_dir
        && should_skip_dir(entry.path().filename().string());
    auto rel = fs::relative(entry.path(), root).generic_string();
    bool ignore_hit = !hardcoded_skip
        && ignore != nullptr
        && !rel.empty()
        && ignore->is_ignored(rel, is_dir);
    if (hardcoded_skip || (ignore_hit && is_dir)) {
        result = EntryAction::kSkipPrune;
    } else if (ignore_hit) {
        result = EntryAction::kSkip;
    } else if (entry.is_regular_file()
               && any_glob_match(rel, patterns)) {
        result = EntryAction::kTake;
    }
    return result;
}
Activity · 14 steps
lines 1037–1037bool is_dir = entry.is_directory();lines 1038–1038EntryAction result = EntryAction::kSkip;lines 1039–1040bool hardcoded_skip = is_dir && should_skip_dir(entry.path().filename().string());lines 1041–1041auto rel = fs::relative(entry.path(), root).generic_string();lines 1042–1045bool ignore_hit = !hardcoded_skip && ignore != nullptr && !rel.empty() && ignore->is_ignored(rel, is_dir);lines 1046–1046◇ if (hardcoded_skip || (ignore_hit && is_dir))lines 1047–1047result = EntryAction::kSkipPrune;lines 1048–1048elselines 1048–1048◇ if (ignore_hit)lines 1049–1049result = EntryAction::kSkip;lines 1050–1050elselines 1050–1051◇ if (entry.is_regular_file() && any_glob_match(rel, patterns))lines 1052–1052result = EntryAction::kTake;lines 1054–1054return result;

Requirements

REQ-MCP-022

collect_entries

std::vector< json > entropic::anonymous_namespace{filesystem.cpp}::collect_entries(const fs::path &dir, bool recursive, int max_depth, WalkBudget &budget)

Collect directory entries, optionally recursive, sorted by name.

src/mcp/servers/filesystem.cpp:1178

Show on the map →

Called by list_page

Calls entry_to_json, walk_budget_spent

Source · 18 lines
std::vector<json> collect_entries(const fs::path& dir,
                                  bool recursive,
                                  int max_depth,
                                  WalkBudget& budget) {
    std::vector<json> entries;
    auto it = fs::recursive_directory_iterator(
        dir, fs::directory_options::skip_permission_denied);
    for (auto& entry : it) {
        if (!recursive || it.depth() >= max_depth) {
            it.disable_recursion_pending();
        }
        entries.push_back(entry_to_json(entry, dir));
        if (walk_budget_spent(budget)) { break; }
    }
    std::sort(entries.begin(), entries.end(),
              [](const json& a, const json& b) { return a["name"] < b["name"]; });
    return entries;
}
Activity · 10 steps
lines 1182–1182std::vector<json> entries;lines 1183–1184auto it = fs::recursive_directory_iterator( dir, fs::directory_options::skip_permission_denied);lines 1185–1185◇ for (auto& entry : it)lines 1186–1186◇ if (!recursive || it.depth() >= max_depth)lines 1187–1187it.disable_recursion_pending();lines 1189–1189entries.push_back(entry_to_json(entry, dir));lines 1190–1190◇ if (walk_budget_spent(budget))lines 1190–1190break;lines 1192–1193std::sort(entries.begin(), entries.end(), [](const json& a, const json& b) { return a["name"] < b["name"]; });lines 1194–1194return entries;

Requirements

REQ-MCP-021

collect_glob_matches

void entropic::anonymous_namespace{filesystem.cpp}::collect_glob_matches(const fs::path &root, const std::string &pattern, const IgnoreMatcher *ignore, WalkBudget &budget, PagedResult &page)

Collect files matching a glob into one page, honoring IgnoreMatcher and brace-expanded patterns.

src/mcp/servers/filesystem.cpp:1074

Show on the map →

Called by execute

Calls classify_glob_entry, display_path, expand_braces, walk_budget_spent

Source · 22 lines
void collect_glob_matches(
    const fs::path& root,
    const std::string& pattern,
    const IgnoreMatcher* ignore,
    WalkBudget& budget,
    PagedResult& page) {

    auto patterns = expand_braces(pattern);
    auto it = fs::recursive_directory_iterator(
        root, fs::directory_options::skip_permission_denied);

    for (auto& entry : it) {
        auto action = classify_glob_entry(entry, root, patterns, ignore);
        if (action == EntryAction::kSkipPrune) {
            it.disable_recursion_pending();
        } else if (action == EntryAction::kTake
                   && !page.offer(display_path(root, entry.path()))) {
            break;
        }
        if (walk_budget_spent(budget)) { break; }
    }
}
Activity · 11 steps
lines 1081–1081auto patterns = expand_braces(pattern);lines 1082–1083auto it = fs::recursive_directory_iterator( root, fs::directory_options::skip_permission_denied);lines 1085–1085◇ for (auto& entry : it)lines 1086–1086auto action = classify_glob_entry(entry, root, patterns, ignore);lines 1087–1087◇ if (action == EntryAction::kSkipPrune)lines 1088–1088it.disable_recursion_pending();lines 1089–1089elselines 1089–1090◇ if (action == EntryAction::kTake && !page.offer(display_path(root, entry.path())))lines 1091–1091break;lines 1093–1093◇ if (walk_budget_spent(budget))lines 1093–1093break;

Requirements

REQ-MCP-021 REQ-MCP-022

compile_grep_or_error

std::regex entropic::compile_grep_or_error(const std::string &pattern, std::string &err)

Compile a regex or return a structured tool error.

src/mcp/servers/filesystem.cpp:1762

Show on the map →

Called by grep_preflight

Calls make_error

Source · 9 lines
std::regex compile_grep_or_error(const std::string& pattern,
                                 std::string& err) {
    try {
        return std::regex(pattern);
    } catch (const std::regex_error& e) {
        err = make_error("invalid_regex", e.what());
        return std::regex("(?!)");
    }
}
Activity · 1 steps
lines 1764–1769try { return std::regex(pattern); } catch (const std::regex_error& e) { err = make_error("invalid_regex", e.what()); return std::regex("(?!)"); }

Requirements

REQ-MCP-021

compute_max_read_bytes

static int entropic::compute_max_read_bytes(const FilesystemConfig &config, int model_context_bytes)

Compute max read bytes from config and model context.

src/mcp/servers/filesystem.cpp:2022

Source · 14 lines
static int compute_max_read_bytes(const FilesystemConfig& config,
                                  int model_context_bytes) {
    if (config.max_read_bytes.has_value()) {
        return config.max_read_bytes.value();
    }
    if (model_context_bytes <= 0) {
        // Safe default: 32KB prevents a single file from blowing typical
        // context budgets (16-128K). Large files trigger size_exceeded and
        // the model must use offset/limit or docs.* tools instead.
        return 32 * 1024;
    }
    return static_cast<int>(
        model_context_bytes * config.max_read_context_pct);
}
Activity · 5 steps
lines 2024–2024◇ if (config.max_read_bytes.has_value())lines 2025–2025return config.max_read_bytes.value();lines 2027–2027◇ if (model_context_bytes <= 0)lines 2031–2031return 32 * 1024;lines 2033–2034return static_cast<int>( model_context_bytes * config.max_read_context_pct);

Requirements

REQ-MCP-021

create_fs_tools

void entropic::FilesystemServer::create_fs_tools(const std::string &data_dir)

Construct the six filesystem tool instances (ctor step 1).

src/mcp/servers/filesystem.cpp:2091

Show on the map →

Called by FilesystemServer

Calls EditFileTool, GlobTool, GrepTool, ListDirectoryTool, ReadFileTool, WriteFileTool

Source · 8 lines
void FilesystemServer::create_fs_tools(const std::string& data_dir) {
    read_file_ = std::make_unique<ReadFileTool>(*this, data_dir);
    write_file_ = std::make_unique<WriteFileTool>(*this, data_dir);
    edit_file_ = std::make_unique<EditFileTool>(*this, data_dir);
    glob_ = std::make_unique<GlobTool>(*this, data_dir);
    grep_ = std::make_unique<GrepTool>(*this, data_dir);
    list_dir_ = std::make_unique<ListDirectoryTool>(*this, data_dir);
}
Activity · 6 steps
lines 2092–2092read_file_ = std::make_unique<ReadFileTool>(*this, data_dir);lines 2093–2093write_file_ = std::make_unique<WriteFileTool>(*this, data_dir);lines 2094–2094edit_file_ = std::make_unique<EditFileTool>(*this, data_dir);lines 2095–2095glob_ = std::make_unique<GlobTool>(*this, data_dir);lines 2096–2096grep_ = std::make_unique<GrepTool>(*this, data_dir);lines 2097–2097list_dir_ = std::make_unique<ListDirectoryTool>(*this, data_dir);

Requirements

REQ-MCP-021

do_insert

std::string entropic::anonymous_namespace{filesystem.cpp}::do_insert(const json &args, const std::string &content, std::string &out, json &ok)

Apply line insertion mode of edit_file.

src/mcp/servers/filesystem.cpp:1244

Source · 16 lines
std::string do_insert(const json& args,
                      const std::string& content,
                      std::string& out, json& ok) {
    const long after = args.at("insert_line").get<long>();
    const long total = count_lines(content);
    if (after < 0 || after > total) {
        return make_error("out_of_range", "insert_line must be 0.."
            + std::to_string(total) + " for this file (got "
            + std::to_string(after) + ")");
    }
    out = apply_insert(content, after, args.at("new_string").get<std::string>());
    ok["mode"] = "insert";
    ok["inserted_after"] = after;
    ok["message"] = "Text inserted";
    return "";
}
Activity · 9 steps
lines 1247–1247const long after = args.at("insert_line").get<long>();lines 1248–1248const long total = count_lines(content);lines 1249–1249◇ if (after < 0 || after > total)lines 1250–1252return make_error("out_of_range", "insert_line must be 0.." + std::to_string(total) + " for this file (got " + std::to_string(after) + ")");lines 1254–1254out = apply_insert(content, after, args.at("new_string").get<std::string>());lines 1255–1255ok["mode"] = "insert";lines 1256–1256ok["inserted_after"] = after;lines 1257–1257ok["message"] = "Text inserted";lines 1258–1258return "";

Requirements

REQ-MCP-021

do_str_replace

std::string entropic::anonymous_namespace{filesystem.cpp}::do_str_replace(const json &args, const std::string &content, std::string &out, json &ok)

Apply string replacement mode of edit_file.

src/mcp/servers/filesystem.cpp:1210

Source · 22 lines
std::string do_str_replace(const json& args,
                           const std::string& content,
                           std::string& out, json& ok) {
    auto old_str = args.at("old_string").get<std::string>();
    auto new_str = args.at("new_string").get<std::string>();
    bool replace_all = args.value("replace_all", false);

    std::string error_type;
    auto result = apply_str_replace(
        content, old_str, new_str, replace_all, error_type);
    if (!result.has_value()) {
        auto msg = (error_type == "multiple_matches")
            ? "old_string found multiple times — add context or use replace_all"
            : "old_string not found in file";
        return make_error(error_type, msg);
    }
    out = result.value();
    ok["mode"] = "str_replace";
    ok["replacements"] = replace_all ? count_occurrences(content, old_str) : 1;
    ok["message"] = "Edit applied";
    return "";
}
Activity · 13 steps
lines 1213–1213auto old_str = args.at("old_string").get<std::string>();lines 1214–1214auto new_str = args.at("new_string").get<std::string>();lines 1215–1215bool replace_all = args.value("replace_all", false);lines 1217–1217std::string error_type;lines 1218–1219auto result = apply_str_replace( content, old_str, new_str, replace_all, error_type);lines 1220–1220◇ if (!result.has_value())lines 1221–1223auto msg = (error_type == "multiple_matches") ? "old_string found multiple times — add context or use replace_all" : "old_string not found in file";lines 1224–1224return make_error(error_type, msg);lines 1226–1226out = result.value();lines 1227–1227ok["mode"] = "str_replace";lines 1228–1228ok["replacements"] = replace_all ? count_occurrences(content, old_str) : 1;lines 1229–1229ok["message"] = "Edit applied";lines 1230–1230return "";

Requirements

REQ-MCP-021

execute

ServerResponse entropic::ReadFileTool::execute(const std::string &args_json) override

Read a file and return numbered lines as JSON.

src/mcp/servers/filesystem.cpp:1339

Show on the map →

Called by none

Calls check_read_gates, display_path, name, read_and_track, resolve_path, root_dir

Source · 120 lines
    ServerResponse execute(const std::string& args_json) override;

    /**
     * @brief Anchor key for context deduplication.
     *
     * A non-empty key is what makes MCPServerBase auto-inject the
     * context_anchor directive for this tool.
     *
     * @param args_json JSON with "path" key.
     * @return "file:{path}" anchor key.
     * @req REQ-MCP-001
     * @req REQ-MCP-021
     * @version 1.8.5
     */
    std::string anchor_key(
        const std::string& args_json) const override {
        auto args = json::parse(args_json);
        return "file:" + args.at("path").get<std::string>();
    }

private:
    FilesystemServer& server_;
};

/**
 * @brief Execute read_file: resolve, size-check, read, hash, track.
 * @param args_json JSON arguments.
 * @return ServerResponse with content or error.
 * @utility
 * @version 1.8.5
 */
/**
 * @brief Run pre-read gates (existence, directory, ignore).
 *
 * Path-relative ignore matching uses the server's IgnoreMatcher (#15,
 * v2.1.4). v2.14.0: the whole-file size gate is gone — a large file is
 * read a window at a time (gh#201); `max_read_bytes` is now the window's
 * byte budget.
 *
 * @param server Owning server (source of the root and ignore rules).
 * @param resolved Already root-confined path.
 * @param display Path as shown to the model.
 * @return An empty string when the read may proceed; otherwise a
 *         structured error — `not_found` (whose message names
 *         list_directory, gh#124), `is_directory` for a directory
 *         argument (gh#116), or `ignored` for a path excluded by
 *         .gitignore/.explorerignore.
 * @req REQ-MCP-021
 * @req REQ-MCP-022
 * @version 2.14.0
 */
std::string check_read_gates(FilesystemServer& server,
                             const fs::path& resolved,
                             const std::string& display) {
    std::string err;
    auto rel = fs::relative(resolved, server.root_dir()).generic_string();
    if (!fs::exists(resolved)) {
        err = make_error("not_found",
            "File not found: " + display
            + ". Use list_directory(\".\") to see available files"
              " in the working directory, or verify the path is"
              " relative to the configured root.");
    } else if (fs::is_directory(resolved)) {
        err = make_error("is_directory",
            "Path is a directory, not a file: " + display);
    } else if (!rel.empty() && server.ignore().is_ignored(rel, false)) {
        err = make_error("ignored",
            "Path '" + rel + "' is excluded by .gitignore or "
            ".explorerignore.");
    }
    return err;
}

/**
 * @brief The window a read_file call asks for, validated.
 * @param args Tool arguments.
 * @param budget Byte budget (max_read_bytes).
 * @param[out] w Parsed window.
 * @return "" or a declared `invalid_args` error.
 * @utility
 * @version 2.14.0
 */
std::string read_window(const json& args, long budget, ReadWindow& w) {
    w.offset = args.value<long>("offset", 1);
    w.limit = args.value<long>("limit", 0);
    w.budget = budget;
    return (1 > w.offset || 0 > w.limit)
        ? make_error("invalid_args", "offset must be >= 1 and limit >= 1")
        : std::string{};
}

/**
 * @brief Read the requested window and record the read for the session.
 * @param server Owning server (budget, tracker).
 * @param resolved File to read (already gated).
 * @param display Path as shown to the model.
 * @param args Tool arguments (offset, limit).
 * @param[out] err Declared error, when the window is invalid or a line
 *             exceeds the budget.
 * @return The declared success object (meaningful only when err is "").
 * @req REQ-MCP-021
 * @version 2.14.0
 */
json read_and_track(FilesystemServer& server, const fs::path& resolved,
                    const std::string& display, const json& args,
                    std::string& err) {
    ReadWindow w;
    err = read_window(args, server.max_read_bytes(), w);
    json result;
    if (err.empty()) { result = read_numbered_lines(resolved, display, w, err); }
    if (err.empty()) {
        server.tracker().record_read(current_run_session(), resolved.string(),
                                     hash_content(result["lines"].dump()));
        logger->info("Read file: {} lines {}..{} of {} (truncated={})",
                     resolved.string(), w.offset,
                     w.offset + static_cast<long>(result["lines"].size()) - 1,
                     result["total"].get<long>(), result["truncated"].get<bool>());
    }
    return result;
}

28 more lines, not shown

Activity · 2 steps
lines 1355–1355auto args = json::parse(args_json);lines 1356–1356return "file:" + args.at("path").get<std::string>();
ServerResponse entropic::WriteFileTool::execute(const std::string &args_json) override

Write content to a file after read-before-write check.

src/mcp/servers/filesystem.cpp:1518

Source · 47 lines
    ServerResponse execute(const std::string& args_json) override;

private:
    FilesystemServer& server_;
};

/**
 * @brief Execute write_file: resolve, enforce policy, write.
 *
 * The path is resolved against the root first (so a traversal attempt
 * never reaches the write), then the read-before-write gate runs.
 * v2.13.0: resolved as a WRITE, so an approver sees "wants to write".
 *
 * @param args_json JSON with "path" and "content" keys.
 * @return A ServerResponse with no directives whose result is either a
 *         success JSON naming the root-relative path and bytes written, or the
 *         structured `read_before_write` error — in which case nothing
 *         is written.
 * @req REQ-MCP-021
 * @version 2.14.0
 */
ServerResponse WriteFileTool::execute(
    const std::string& args_json) {

    auto args = json::parse(args_json);
    auto requested = args.at("path").get<std::string>();
    auto content = args.at("content").get<std::string>();
    auto resolved = server_.resolve_path(requested, PathAccess::write,
                                         name());
    auto path_str = resolved.string();

    auto violation = check_read_before_write(
        server_.tracker(), path_str);
    if (!violation.empty()) {
        return {violation, {}};
    }

    write_file_contents(resolved, content);
    logger->info("Wrote file: {} ({} bytes)",
                 path_str, content.size());

    json result;
    result["path"] = display_path(server_.root_dir(), resolved);
    result["bytes_written"] = content.size();
    result["message"] = "File written successfully";
    return {result.dump(), {}};
}
Activity · 15 steps
lines 1542–1542auto args = json::parse(args_json);lines 1543–1543auto requested = args.at("path").get<std::string>();lines 1544–1544auto content = args.at("content").get<std::string>();lines 1545–1546auto resolved = server_.resolve_path(requested, PathAccess::write, name());lines 1547–1547auto path_str = resolved.string();lines 1549–1550auto violation = check_read_before_write( server_.tracker(), path_str);lines 1551–1551◇ if (!violation.empty())lines 1552–1552return {violation, {}};lines 1555–1555write_file_contents(resolved, content);lines 1556–1557logger->info("Wrote file: {} ({} bytes)", path_str, content.size());lines 1559–1559json result;lines 1560–1560result["path"] = display_path(server_.root_dir(), resolved);lines 1561–1561result["bytes_written"] = content.size();lines 1562–1562result["message"] = "File written successfully";lines 1563–1563return {result.dump(), {}};
ServerResponse entropic::EditFileTool::execute(const std::string &args_json) override

Edit a file via string replacement or line insertion.

src/mcp/servers/filesystem.cpp:1596

Source · 30 lines
    ServerResponse execute(const std::string& args_json) override;

private:
    FilesystemServer& server_;
};

/**
 * @brief Execute edit_file: read, apply edit, write back.
 *
 * v2.13.0: resolved as a WRITE — an edit modifies the file.
 *
 * @param args_json JSON arguments.
 * @return ServerResponse whose result is the declared success object or
 *         a declared structured error.
 * @utility
 * @version 2.14.0
 */
ServerResponse EditFileTool::execute(const std::string& args_json) {
    auto args = json::parse(args_json);
    auto requested = args.at("path").get<std::string>();
    auto resolved = server_.resolve_path(requested, PathAccess::write,
                                         name());
    auto violation = check_read_before_write(
        server_.tracker(), resolved.string());
    if (!violation.empty()) {
        return {violation, {}};
    }
    return {apply_edit(args, resolved,
                       display_path(server_.root_dir(), resolved)), {}};
}
Activity · 7 steps
lines 1614–1614auto args = json::parse(args_json);lines 1615–1615auto requested = args.at("path").get<std::string>();lines 1616–1617auto resolved = server_.resolve_path(requested, PathAccess::write, name());lines 1618–1619auto violation = check_read_before_write( server_.tracker(), resolved.string());lines 1620–1620◇ if (!violation.empty())lines 1621–1621return {violation, {}};lines 1623–1624return {apply_edit(args, resolved, display_path(server_.root_dir(), resolved)), {}};
ServerResponse entropic::GlobTool::execute(const std::string &args_json) override

Find files matching a glob pattern.

src/mcp/servers/filesystem.cpp:1667

Show on the map →

Called by none

Calls collect_glob_matches, config, finish, ignore, read_page, root_dir

Source · 37 lines
    ServerResponse execute(const std::string& args_json) override;

private:
    FilesystemServer& server_; ///< Owning server (for root_dir)
};

/**
 * @brief Execute glob: one page of root-relative paths matching a pattern.
 *
 * Issues #13/#15 (v2.1.4): brace expansion, ignore filtering.
 * v2.14.0 (gh#203): declared `{paths, truncated, reason?, next_offset?}`
 * instead of an array whose last element might be a sentinel object.
 *
 * @param args_json JSON with "pattern" and optional "limit"/"offset".
 * @return ServerResponse with the declared result or `invalid_args`.
 * @req REQ-MCP-022
 * @version 2.14.0
 */
ServerResponse GlobTool::execute(const std::string& args_json) {
    auto args = json::parse(args_json);
    auto pattern = args.at("pattern").get<std::string>();
    Page requested;
    auto err = read_page(args, 500, 5000, requested);
    if (!err.empty()) { return {err, {}}; }

    WalkBudget budget{server_.config().max_walk_entries, 0, false};
    PagedResult page(requested);
    collect_glob_matches(server_.root_dir(), pattern, &server_.ignore(),
                         budget, page);
    json result;
    page.finish(result, "paths", budget.truncated);
    logger->info("Glob '{}': {} paths, {} entries walked, truncated={}{}",
                 pattern, result["paths"].size(), budget.visited,
                 result["truncated"].get<bool>(),
                 budget.truncated ? " (walk cap — narrow the pattern)" : "");
    return {result.dump(), {}};
}
Activity · 13 steps
lines 1686–1686auto args = json::parse(args_json);lines 1687–1687auto pattern = args.at("pattern").get<std::string>();lines 1688–1688Page requested;lines 1689–1689auto err = read_page(args, 500, 5000, requested);lines 1690–1690◇ if (!err.empty())lines 1690–1690return {err, {}};lines 1692–1692WalkBudget budget{server_.config().max_walk_entries, 0, false};lines 1693–1693PagedResult page(requested);lines 1694–1695collect_glob_matches(server_.root_dir(), pattern, &server_.ignore(), budget, page);lines 1696–1696json result;lines 1697–1697page.finish(result, "paths", budget.truncated);lines 1698–1701logger->info("Glob '{}': {} paths, {} entries walked, truncated={}{}", pattern, result["paths"].size(), budget.visited, result["truncated"].get<bool>(), budget.truncated ? " (walk cap — narrow the pattern)" : "");lines 1702–1702return {result.dump(), {}};
ServerResponse entropic::GrepTool::execute(const std::string &args_json) override

Search files for regex pattern matches.

src/mcp/servers/filesystem.cpp:1744

Show on the map →

Called by none

Calls config, finish, grep_preflight, grep_target, name, resolve_path, root_dir

Source · 120 lines
    ServerResponse execute(const std::string& args_json) override;

private:
    FilesystemServer& server_; ///< Owning server (for root_dir)
};

/**
 * @brief Compile a regex or return a structured tool error.
 *
 * @param pattern Regex source.
 * @param[out] err Set to a non-empty JSON error string on failure.
 * @return The compiled regex on success; on failure a never-matching
 *         regex with `err` set to a structured `invalid_regex` error —
 *         a bad pattern from the model is a tool error, never a throw
 *         through the dispatch path.
 * @req REQ-MCP-021
 * @version 2.1.4
 */
std::regex compile_grep_or_error(const std::string& pattern,
                                 std::string& err) {
    try {
        return std::regex(pattern);
    } catch (const std::regex_error& e) {
        err = make_error("invalid_regex", e.what());
        return std::regex("(?!)");
    }
}

/**
 * @brief Execute grep: brace-expand the file glob, compile the
 *        content regex (error-safe), iterate the tree applying the
 *        same classify_glob_entry filter glob uses.
 *
 * Issues #13/#15 (v2.1.4).
 *
 * @utility
 * @version 2.1.4
 */
/**
 * @brief Walk `start` applying the glob/ignore filter and grep files.
 * @param root Project root (patterns and shown paths are relative to it).
 * @param start Directory to walk (the root, or the `path` argument).
 * @param file_patterns Brace-expanded glob patterns.
 * @param re Compiled content regex.
 * @param ignore Ignore matcher.
 * @param[in,out] budget Entry budget (gh#161) — grep needs it MORE than
 *                glob does, since it also opens every matching file.
 * @param[in,out] page Page being collected.
 * @req REQ-MCP-022
 * @version 2.14.0
 */
static void grep_search(
    const fs::path& root, const fs::path& start,
    const std::vector<std::string>& file_patterns,
    const std::regex& re, const IgnoreMatcher& ignore,
    WalkBudget& budget, PagedResult& page) {
    auto it = fs::recursive_directory_iterator(
        start, fs::directory_options::skip_permission_denied);
    for (auto& entry : it) {
        auto action = classify_glob_entry(entry, root, file_patterns,
                                          &ignore);
        if (action == EntryAction::kSkipPrune) {
            it.disable_recursion_pending();
        } else if (action == EntryAction::kTake
                   && !grep_file(entry.path(),
                                 display_path(root, entry.path()), re, page)) {
            break;
        }
        if (walk_budget_spent(budget)) { break; }
    }
}

/**
 * @brief Search `start` — one file, or a tree under the glob filter.
 * @param server Owning server (root, ignore rules).
 * @param start Resolved `path` argument.
 * @param args Tool arguments (glob).
 * @param re Compiled regex.
 * @param[in,out] budget Walk budget.
 * @param[in,out] page Page being collected.
 * @utility
 * @version 2.14.0
 */
static void grep_target(FilesystemServer& server, const fs::path& start,
                        const json& args, const std::regex& re,
                        WalkBudget& budget, PagedResult& page) {
    const auto& root = server.root_dir();
    if (fs::is_regular_file(start)) {
        grep_file(start, display_path(root, start), re, page);
    } else {
        grep_search(root, start,
                    expand_braces(args.value("glob", std::string("*"))),
                    re, server.ignore(), budget, page);
    }
}

/**
 * @brief Validate a grep call: paging, regex, and that `path` exists.
 * @param args Tool arguments.
 * @param start Resolved `path` argument.
 * @param root Project root (for the message).
 * @param[out] requested Parsed page.
 * @param[out] re Compiled regex.
 * @return "" or the first declared error (`invalid_args`,
 *         `invalid_regex`, `not_found`).
 * @utility
 * @version 2.14.0
 */
static std::string grep_preflight(const json& args, const fs::path& start,
                                  const fs::path& root, Page& requested,
                                  std::regex& re) {
    std::string err = read_page(args, 100, 1000, requested);
    re = compile_grep_or_error(args.at("pattern").get<std::string>(), err);
    if (err.empty() && !fs::exists(start)) {
        err = make_error("not_found", "No such file or directory: "
                         + display_path(root, start));
    }
    return err;
}

37 more lines, not shown

Activity · 1 steps
lines 1764–1769try { return std::regex(pattern); } catch (const std::regex_error& e) { err = make_error("invalid_regex", e.what()); return std::regex("(?!)"); }
ServerResponse entropic::ListDirectoryTool::execute(const std::string &args_json) override

List directory entries with optional recursion.

src/mcp/servers/filesystem.cpp:1943

Show on the map →

Called by none

Calls config, display_path, list_page, make_error, name, read_page, resolve_path, root_dir

Source · 65 lines
    ServerResponse execute(const std::string& args_json) override;

private:
    FilesystemServer& server_;
};

/**
 * @brief Collect one page of a directory listing into `result`.
 * @param dir Directory to list.
 * @param args Tool arguments (recursive, max_depth).
 * @param requested Requested page.
 * @param max_walk Walk cap (filesystem.max_walk_entries).
 * @param[in,out] result Result object (gets entries + ending).
 * @req REQ-MCP-021
 * @version 2.14.0
 */
static void list_page(const fs::path& dir, const json& args, Page requested,
                      int max_walk, json& result) {
    WalkBudget budget{max_walk, 0, false};
    PagedResult page(requested);
    for (auto& e : collect_entries(dir, args.value("recursive", false),
                                   args.value("max_depth", 3), budget)) {
        if (!page.offer(std::move(e))) { break; }
    }
    page.finish(result, "entries", budget.truncated);
}

/**
 * @brief Execute list_directory: one page of a directory's entries.
 *
 * The optional parameters carry documented defaults (gh#116): `path`
 * defaults to the project root, `recursive` to false, `max_depth` to 3.
 * v2.13.0: resolved as a READ for the outside-root policy. v2.14.0
 * (gh#203): the declared `{path, entries, truncated, ...}` object instead
 * of a bare array; recursive names are relative to the listed directory
 * (they were bare file names, ambiguous across subdirectories).
 *
 * @param args_json JSON with optional "path", "recursive", "max_depth",
 *                  "limit" (default 500) and "offset" — all may be omitted.
 * @return A ServerResponse whose result is the declared success object,
 *         or `not_directory` / `invalid_args`.
 * @req REQ-MCP-021
 * @version 2.14.0
 */
ServerResponse ListDirectoryTool::execute(
    const std::string& args_json) {

    auto args = json::parse(args_json);
    auto resolved = server_.resolve_path(args.value("path", std::string(".")),
                                         PathAccess::read, name());
    auto display = display_path(server_.root_dir(), resolved);
    Page requested;
    auto err = read_page(args, 500, 5000, requested);
    if (err.empty() && !fs::is_directory(resolved)) {
        err = make_error("not_directory", "Not a directory: " + display);
    }
    if (!err.empty()) { return {err, {}}; }

    json result;
    result["path"] = display;
    list_page(resolved, args, requested, server_.config().max_walk_entries, result);
    logger->info("Listed {}: {} entries, truncated={}", display,
                 result["entries"].size(), result["truncated"].get<bool>());
    return {result.dump(), {}};
}
Activity · 6 steps
lines 1961–1961WalkBudget budget{max_walk, 0, false};lines 1962–1962PagedResult page(requested);lines 1963–1963◇ for (auto& e : collect_entries(dir, args.value("recursive", false), args.value("max_depth", 3), budget))lines 1965–1965◇ if (!page.offer(std::move(e)))lines 1965–1965break;lines 1967–1967page.finish(result, "entries", budget.truncated);

Requirements

REQ-MCP-021 REQ-MCP-022

first_containing

std::optional< fs::path > entropic::anonymous_namespace{filesystem.cpp}::first_containing(const std::vector< fs::path > &entries, const fs::path &resolved)

The first list entry whose subtree holds resolved .

src/mcp/servers/filesystem.cpp:181

Source · 12 lines
std::optional<fs::path> first_containing(
    const std::vector<fs::path>& entries, const fs::path& resolved) {
    std::optional<fs::path> hit;
    for (const auto& e : entries) {
        auto base = canonical_entry(e);
        if (path_within(resolved, base)) {
            hit = base;
            break;
        }
    }
    return hit;
}
Activity · 7 steps
lines 183–183std::optional<fs::path> hit;lines 184–184◇ for (const auto& e : entries)lines 185–185auto base = canonical_entry(e);lines 186–186◇ if (path_within(resolved, base))lines 187–187hit = base;lines 188–188break;lines 191–191return hit;

Requirements

REQ-MCP-021

grep_file

bool entropic::anonymous_namespace{filesystem.cpp}::grep_file(const fs::path &path, const std::string &display, const std::regex &re, PagedResult &page)

Search a single file for regex matches, feeding one page.

src/mcp/servers/filesystem.cpp:1125

Show on the map →

Called by grep_search, grep_target

Calls looks_binary

Source · 18 lines
bool grep_file(const fs::path& path, const std::string& display,
               const std::regex& re, PagedResult& page) {
    std::ifstream in(path);
    std::string line;
    long line_num = 0;
    bool keep_going = !looks_binary(path);
    while (keep_going && std::getline(in, line)) {
        ++line_num;
        if (std::regex_search(line, re)) {
            json m;
            m["path"] = display;
            m["line"] = line_num;
            m["content"] = line;
            keep_going = page.offer(std::move(m));
        }
    }
    return !page.full();
}
Activity · 13 steps
lines 1127–1127std::ifstream in(path);lines 1128–1128std::string line;lines 1129–1129long line_num = 0;lines 1130–1130bool keep_going = !looks_binary(path);lines 1131–1131◇ while (keep_going && std::getline(in, line))lines 1132–1132++line_num;lines 1133–1133◇ if (std::regex_search(line, re))lines 1134–1134json m;lines 1135–1135m["path"] = display;lines 1136–1136m["line"] = line_num;lines 1137–1137m["content"] = line;lines 1138–1138keep_going = page.offer(std::move(m));lines 1141–1141return !page.full();

Requirements

REQ-MCP-022

ignore

const IgnoreMatcher & entropic::FilesystemServer::ignore() const

Get the ignore matcher (#15, v2.1.4).

src/mcp/servers/filesystem.cpp:2227

Show on the map →

Called by TEST_CASE, check_read_gates, execute, grep_target

Calls none

Source · 3 lines
const IgnoreMatcher& FilesystemServer::ignore() const {
    return ignore_;
}
Activity · 1 steps
lines 2228–2228return ignore_;

Requirements

REQ-MCP-022

list_page

static void entropic::list_page(const fs::path &dir, const json &args, Page requested, int max_walk, json &result)

Collect one page of a directory listing into result .

src/mcp/servers/filesystem.cpp:1959

Show on the map →

Called by execute

Calls collect_entries, finish, offer

Source · 10 lines
static void list_page(const fs::path& dir, const json& args, Page requested,
                      int max_walk, json& result) {
    WalkBudget budget{max_walk, 0, false};
    PagedResult page(requested);
    for (auto& e : collect_entries(dir, args.value("recursive", false),
                                   args.value("max_depth", 3), budget)) {
        if (!page.offer(std::move(e))) { break; }
    }
    page.finish(result, "entries", budget.truncated);
}
Activity · 6 steps
lines 1961–1961WalkBudget budget{max_walk, 0, false};lines 1962–1962PagedResult page(requested);lines 1963–1963◇ for (auto& e : collect_entries(dir, args.value("recursive", false), args.value("max_depth", 3), budget))lines 1965–1965◇ if (!page.offer(std::move(e)))lines 1965–1965break;lines 1967–1967page.finish(result, "entries", budget.truncated);

Requirements

REQ-MCP-021

log_outside_root_policy

void entropic::FilesystemServer::log_outside_root_policy() const

Log the outside-root policy, warning on ineffective entries.

src/mcp/servers/filesystem.cpp:2399

Show on the map →

Called by FilesystemServer, set_working_dir

Calls join_paths, outside_root_mode_name, warn_deny_entries_inside_root

Source · 15 lines
void FilesystemServer::log_outside_root_policy() const {
    const auto& deny = config_.outside_root_deny;
    if (config_.allow_outside_root == OutsideRootAccess::allow) {
        logger->warn("Outside-root policy: allow_outside_root=true — every "
                     "path outside {} is served (deny={})",
                     root_dir_.string(), join_paths(deny));
    } else {
        logger->info("Outside-root policy: allow_outside_root={} allow={} "
                     "deny={} (root: {})",
                     outside_root_mode_name(config_.allow_outside_root),
                     join_paths(config_.outside_root_allow),
                     join_paths(deny), root_dir_.string());
    }
    warn_deny_entries_inside_root(deny, root_dir_);
}
Activity · 6 steps
lines 2400–2400const auto& deny = config_.outside_root_deny;lines 2401–2401◇ if (config_.allow_outside_root == OutsideRootAccess::allow)lines 2402–2404logger->warn("Outside-root policy: allow_outside_root=true — every " "path outside {} is served (deny={})", root_dir_.string(), join_paths(deny));lines 2405–2405elselines 2406–2410logger->info("Outside-root policy: allow_outside_root={} allow={} " "deny={} (root: {})", outside_root_mode_name(config_.allow_outside_root), join_paths(config_.outside_root_allow), join_paths(deny), root_dir_.string());lines 2412–2412warn_deny_entries_inside_root(deny, root_dir_);

Requirements

REQ-MCP-021

make_error

std::string entropic::anonymous_namespace{filesystem.cpp}::make_error(const std::string &code, const std::string &message)

Build a JSON error response.

src/mcp/servers/filesystem.cpp:446

Source · 7 lines
std::string make_error(const std::string& code,
                       const std::string& message) {
    json j;
    j["error"] = code;
    j["message"] = message;
    return j.dump();
}
Activity · 4 steps
lines 448–448json j;lines 449–449j["error"] = code;lines 450–450j["message"] = message;lines 451–451return j.dump();

Requirements

REQ-MCP-021

max_read_bytes

int entropic::FilesystemServer::max_read_bytes() const

Get max read bytes (size gate).

src/mcp/servers/filesystem.cpp:2248

Source · 3 lines
int FilesystemServer::max_read_bytes() const {
    return max_read_bytes_;
}
Activity · 1 steps
lines 2249–2249return max_read_bytes_;

Requirements

REQ-MCP-021

outside_root_refusal

std::string entropic::anonymous_namespace{filesystem.cpp}::outside_root_refusal(OutsideRootVerdict verdict, const OutsideRootRequest &req)

The refusal text for an approver verdict other than approved .

src/mcp/servers/filesystem.cpp:233

Source · 16 lines
std::string outside_root_refusal(OutsideRootVerdict verdict,
                                 const OutsideRootRequest& req) {
    std::string head = "Path escapes project root: " + req.path
        + " (root: " + req.root + ")";
    if (verdict == OutsideRootVerdict::rejected) {
        return "outside_root_rejected: " + head + " — the host's path "
               "approver refused this " + access_verb(req.access) + ".";
    }
    return "outside_root_approval_required: " + head + " — "
        + access_verb(req.access) + " access outside the project root "
        "needs approval (mcp.filesystem.allow_outside_root: optional) and "
        "no path approver is registered, so it is refused. Pre-approve "
        "the directory with mcp.filesystem.outside_root_allow, set "
        "allow_outside_root: true, or register an approver with "
        "entropic_set_path_approval_callback.";
}
Activity · 4 steps
lines 235–236std::string head = "Path escapes project root: " + req.path + " (root: " + req.root + ")";lines 237–237◇ if (verdict == OutsideRootVerdict::rejected)lines 238–239return "outside_root_rejected: " + head + " — the host's path " "approver refused this " + access_verb(req.access) + ".";lines 241–247return "outside_root_approval_required: " + head + " — " + access_verb(req.access) + " access outside the project root " "needs approval (mcp.filesystem.allow_outside_root: optional) and " "no path approver is registered, so it is refused. Pre-approve " "the directory with mcp.filesystem.outside_root_allow, set " "allow_outside_root: true, or register an approver with " "entropic_set_path_approval_callback.";

Requirements

REQ-MCP-021

path_within

bool entropic::anonymous_namespace{filesystem.cpp}::path_within(const fs::path &path, const fs::path &base)

Whether path lies in the subtree rooted at base .

src/mcp/servers/filesystem.cpp:147

Show on the map →

Called by display_path, first_containing, resolve_path, warn_deny_entries_inside_root

Calls none

Source · 6 lines
bool path_within(const fs::path& path, const fs::path& base) {
    fs::path rel = path.lexically_relative(base);
    return !rel.empty()
        && *rel.begin() != fs::path("..")
        && rel != fs::path("..");
}
Activity · 2 steps
lines 148–148fs::path rel = path.lexically_relative(base);lines 149–151return !rel.empty() && *rel.begin() != fs::path("..") && rel != fs::path("..");

Requirements

REQ-MCP-021

read_and_track

json entropic::read_and_track(FilesystemServer &server, const fs::path &resolved, const std::string &display, const json &args, std::string &err)

Read the requested window and record the read for the session.

src/mcp/servers/filesystem.cpp:1442

Source · 17 lines
json read_and_track(FilesystemServer& server, const fs::path& resolved,
                    const std::string& display, const json& args,
                    std::string& err) {
    ReadWindow w;
    err = read_window(args, server.max_read_bytes(), w);
    json result;
    if (err.empty()) { result = read_numbered_lines(resolved, display, w, err); }
    if (err.empty()) {
        server.tracker().record_read(current_run_session(), resolved.string(),
                                     hash_content(result["lines"].dump()));
        logger->info("Read file: {} lines {}..{} of {} (truncated={})",
                     resolved.string(), w.offset,
                     w.offset + static_cast<long>(result["lines"].size()) - 1,
                     result["total"].get<long>(), result["truncated"].get<bool>());
    }
    return result;
}
Activity · 9 steps
lines 1445–1445ReadWindow w;lines 1446–1446err = read_window(args, server.max_read_bytes(), w);lines 1447–1447json result;lines 1448–1448◇ if (err.empty())lines 1448–1448result = read_numbered_lines(resolved, display, w, err);lines 1449–1449◇ if (err.empty())lines 1450–1451server.tracker().record_read(current_run_session(), resolved.string(), hash_content(result["lines"].dump()));lines 1452–1455logger->info("Read file: {} lines {}..{} of {} (truncated={})", resolved.string(), w.offset, w.offset + static_cast<long>(result["lines"].size()) - 1, result["total"].get<long>(), result["truncated"].get<bool>());lines 1457–1457return result;

Requirements

REQ-MCP-021

read_file_contents

std::string entropic::anonymous_namespace{filesystem.cpp}::read_file_contents(const fs::path &path)

Read entire file contents into a string.

src/mcp/servers/filesystem.cpp:391

Show on the map →

Called by none

Calls none

Source · 10 lines
std::string read_file_contents(const fs::path& path) {
    std::ifstream in(path, std::ios::binary);
    if (!in.is_open()) {
        throw std::runtime_error(
            "Cannot open file: " + path.string());
    }
    std::ostringstream ss;
    ss << in.rdbuf();
    return ss.str();
}
Activity · 6 steps
lines 392–392std::ifstream in(path, std::ios::binary);lines 393–393◇ if (!in.is_open())lines 394–395throw std::runtime_error( "Cannot open file: " + path.string());lines 397–397std::ostringstream ss;lines 398–398ss << in.rdbuf();lines 399–399return ss.str();

Requirements

REQ-MCP-021

read_numbered_lines

json entropic::anonymous_namespace{filesystem.cpp}::read_numbered_lines(const fs::path &path, const std::string &display, const ReadWindow &w, std::string &err)

Read a window of numbered lines, streaming (gh#201).

src/mcp/servers/filesystem.cpp:657

Source · 21 lines
json read_numbered_lines(const fs::path& path, const std::string& display,
                         const ReadWindow& w, std::string& err) {
    std::ifstream in(path, std::ios::binary);
    WindowReader reader{w};
    std::string line;
    long n = 0;
    while (reader.err.empty() && std::getline(in, line)) {
        reader.take(++n, line);
    }
    err = reader.err;
    json result;
    result["path"] = display;
    result["total"] = n;
    result["offset"] = w.offset;
    result["truncated"] = reader.more;
    if (reader.more) {
        result["next_offset"] = w.offset + static_cast<long>(reader.lines.size());
    }
    result["lines"] = std::move(reader.lines);
    return result;
}
Activity · 16 steps
lines 659–659std::ifstream in(path, std::ios::binary);lines 660–660WindowReader reader{w};lines 661–661std::string line;lines 662–662long n = 0;lines 663–663◇ while (reader.err.empty() && std::getline(in, line))lines 664–664reader.take(++n, line);lines 666–666err = reader.err;lines 667–667json result;lines 668–668result["path"] = display;lines 669–669result["total"] = n;lines 670–670result["offset"] = w.offset;lines 671–671result["truncated"] = reader.more;lines 672–672◇ if (reader.more)lines 673–673result["next_offset"] = w.offset + static_cast<long>(reader.lines.size());lines 675–675result["lines"] = std::move(reader.lines);lines 676–676return result;

Requirements

REQ-MCP-021

read_page

std::string entropic::anonymous_namespace{filesystem.cpp}::read_page(const json &args, long default_limit, long max_limit, Page &page)

Read offset / limit from tool arguments (gh#202).

src/mcp/servers/filesystem.cpp:479

Show on the map →

Called by execute, grep_preflight

Calls make_error

Source · 15 lines
std::string read_page(const json& args, long default_limit, long max_limit,
                      Page& page) {
    page.offset = args.value<long>("offset", 0);
    page.limit = args.value("limit", default_limit);
    std::string err;
    // Written with '>' only: knots v1.4.3 reads a bare '<' here as a
    // template bracket and loses the function boundary.
    if (0 > page.offset || 1 > page.limit || page.limit > max_limit) {
        err = make_error("invalid_args",
            "offset must be >= 0 and limit 1.." + std::to_string(max_limit)
            + " (got offset " + std::to_string(page.offset) + ", limit "
            + std::to_string(page.limit) + ")");
    }
    return err;
}
Activity · 6 steps
lines 481–481page.offset = args.value<long>("offset", 0);lines 482–482page.limit = args.value("limit", default_limit);lines 483–483std::string err;lines 486–486◇ if (0 > page.offset || 1 > page.limit || page.limit > max_limit)lines 487–490err = make_error("invalid_args", "offset must be >= 0 and limit 1.." + std::to_string(max_limit) + " (got offset " + std::to_string(page.offset) + ", limit " + std::to_string(page.limit) + ")");lines 492–492return err;

Requirements

REQ-MCP-022

record_read

void entropic::FileAccessTracker::record_read(const std::string &session, const std::string &path, size_t hash)

Record that session read a file.

src/mcp/servers/filesystem.cpp:56

Show on the map →

Called by TEST_CASE, read_and_track

Calls with

Source · 6 lines
void FileAccessTracker::record_read(const std::string& session,
                                    const std::string& path,
                                    size_t hash) {
    reads_.with(session, [&](auto& reads) { reads[path] = hash; });
    logger->info("Tracked read: session='{}' {}", session, path);
}
Activity · 2 steps
lines 59–59reads_.with(session, [&](auto& reads) { reads[path] = hash; });lines 60–60logger->info("Tracked read: session='{}' {}", session, path);

Requirements

REQ-LOOP-009 REQ-MCP-021

refuse_denied

void entropic::anonymous_namespace{filesystem.cpp}::refuse_denied(const fs::path &resolved, const fs::path &entry, PathAccess access, const fs::path &root)

Refuse a path under an outside_root_deny entry (logs, throws).

src/mcp/servers/filesystem.cpp:260

Source · 11 lines
[[noreturn]] void refuse_denied(const fs::path& resolved,
                                const fs::path& entry, PathAccess access,
                                const fs::path& root) {
    logger->error("Path escape blocked by outside_root_deny: {} {} "
                  "(entry: {}, root: {})", access_verb(access),
                  resolved.string(), entry.string(), root.string());
    throw std::runtime_error(
        "outside_root_denied: " + resolved.string() + " is under "
        "mcp.filesystem.outside_root_deny entry " + entry.string()
        + " — refused regardless of allow_outside_root.");
}
Activity · 2 steps
lines 263–265logger->error("Path escape blocked by outside_root_deny: {} {} " "(entry: {}, root: {})", access_verb(access), resolved.string(), entry.string(), root.string());lines 266–269throw std::runtime_error( "outside_root_denied: " + resolved.string() + " is under " "mcp.filesystem.outside_root_deny entry " + entry.string() + " — refused regardless of allow_outside_root.");

Requirements

REQ-MCP-021

refuse_escape

void entropic::anonymous_namespace{filesystem.cpp}::refuse_escape(const fs::path &resolved, const fs::path &root)

Refuse an escape under allow_outside_root: false (logs, throws).

src/mcp/servers/filesystem.cpp:284

Source · 7 lines
[[noreturn]] void refuse_escape(const fs::path& resolved,
                                const fs::path& root) {
    logger->error("Path escape blocked: {} (root: {})",
                  resolved.string(), root.string());
    throw std::runtime_error(
        "Path escapes project root: " + resolved.string());
}
Activity · 2 steps
lines 286–287logger->error("Path escape blocked: {} (root: {})", resolved.string(), root.string());lines 288–289throw std::runtime_error( "Path escapes project root: " + resolved.string());

Requirements

REQ-MCP-021

register_fs_tools

void entropic::FilesystemServer::register_fs_tools()

Register the six filesystem tools (ctor step 2).

src/mcp/servers/filesystem.cpp:2109

Source · 8 lines
void FilesystemServer::register_fs_tools() {
    register_tool(read_file_.get());
    register_tool(write_file_.get());
    register_tool(edit_file_.get());
    register_tool(glob_.get());
    register_tool(grep_.get());
    register_tool(list_dir_.get());
}
Activity · 6 steps
lines 2110–2110register_tool(read_file_.get());lines 2111–2111register_tool(write_file_.get());lines 2112–2112register_tool(edit_file_.get());lines 2113–2113register_tool(glob_.get());lines 2114–2114register_tool(grep_.get());lines 2115–2115register_tool(list_dir_.get());

Requirements

REQ-MCP-001

release_session

bool entropic::FileAccessTracker::release_session(const std::string &session)

Forget every read session recorded (gh#158).

src/mcp/servers/filesystem.cpp:98

Source · 3 lines
bool FileAccessTracker::release_session(const std::string& session) {
    return reads_.release(session);
}
Activity · 1 steps
lines 99–99return reads_.release(session);
bool entropic::FilesystemServer::release_session(const std::string &key) override

Release key 's recorded reads (gh#158).

src/mcp/servers/filesystem.cpp:2205

Source · 3 lines
bool FilesystemServer::release_session(const std::string& key) {
    return tracker_.release_session(key);
}
Activity · 1 steps
lines 2206–2206return tracker_.release_session(key);

Requirements

REQ-LOOP-009 REQ-MCP-021

required_access_level

MCPAccessLevel entropic::ReadFileTool::required_access_level() const override

Read-only tool — requires READ access.

src/mcp/servers/filesystem.cpp:1328

Show on the map →

Called by none

Calls none

Source · 3 lines
    MCPAccessLevel required_access_level() const override {
        return MCPAccessLevel::READ;
    }
Activity · 1 steps
lines 1329–1329return MCPAccessLevel::READ;
MCPAccessLevel entropic::GlobTool::required_access_level() const override

Read-only tool — requires READ access.

src/mcp/servers/filesystem.cpp:1656

Show on the map →

Called by none

Calls none

Source · 3 lines
    MCPAccessLevel required_access_level() const override {
        return MCPAccessLevel::READ;
    }
Activity · 1 steps
lines 1657–1657return MCPAccessLevel::READ;
MCPAccessLevel entropic::GrepTool::required_access_level() const override

Read-only tool — requires READ access.

src/mcp/servers/filesystem.cpp:1733

Show on the map →

Called by none

Calls none

Source · 3 lines
    MCPAccessLevel required_access_level() const override {
        return MCPAccessLevel::READ;
    }
Activity · 1 steps
lines 1734–1734return MCPAccessLevel::READ;
MCPAccessLevel entropic::ListDirectoryTool::required_access_level() const override

Read-only tool — requires READ access.

src/mcp/servers/filesystem.cpp:1932

Show on the map →

Called by none

Calls none

Source · 3 lines
    MCPAccessLevel required_access_level() const override {
        return MCPAccessLevel::READ;
    }
Activity · 1 steps
lines 1933–1933return MCPAccessLevel::READ;

Requirements

REQ-MCP-011

resolve_path

fs::path entropic::FilesystemServer::resolve_path(const std::string &requested, PathAccess access, const std::string &tool) const

Resolve a path and apply the outside-root policy (v2.13.0).

src/mcp/servers/filesystem.cpp:2279

Source · 14 lines
fs::path FilesystemServer::resolve_path(
    const std::string& requested, PathAccess access,
    const std::string& tool) const {

    fs::path req_path(requested);
    fs::path resolved = req_path.is_absolute()
        ? fs::weakly_canonical(req_path)
        : fs::weakly_canonical(root_dir_ / req_path);

    if (!path_within(resolved, root_dir_)) {
        authorize_outside_root(resolved, access, tool);
    }
    return resolved;
}
Activity · 5 steps
lines 2283–2283fs::path req_path(requested);lines 2284–2286fs::path resolved = req_path.is_absolute() ? fs::weakly_canonical(req_path) : fs::weakly_canonical(root_dir_ / req_path);lines 2288–2288◇ if (!path_within(resolved, root_dir_))lines 2289–2289authorize_outside_root(resolved, access, tool);lines 2291–2291return resolved;

Requirements

REQ-MCP-021

root_dir

const fs::path & entropic::FilesystemServer::root_dir() const

Get the root directory.

src/mcp/servers/filesystem.cpp:2181

Show on the map →

Called by TEST_CASE, check_read_gates, execute, grep_target

Calls none

Source · 3 lines
const fs::path& FilesystemServer::root_dir() const {
    return root_dir_;
}
Activity · 1 steps
lines 2182–2182return root_dir_;

Requirements

REQ-MCP-021

session_count

std::size_t entropic::FileAccessTracker::session_count() const

Sessions currently holding recorded reads.

src/mcp/servers/filesystem.cpp:108

Source · 3 lines
std::size_t FileAccessTracker::session_count() const {
    return reads_.session_count();
}
Activity · 1 steps
lines 109–109return reads_.session_count();
std::size_t entropic::FilesystemServer::session_count() const override

Sessions whose reads this server currently tracks (gh#158).

src/mcp/servers/filesystem.cpp:2215

Source · 3 lines
std::size_t FilesystemServer::session_count() const {
    return tracker_.session_count();
}
Activity · 1 steps
lines 2216–2216return tracker_.session_count();

Requirements

REQ-LOOP-009

set_outside_root_approver

void entropic::FilesystemServer::set_outside_root_approver(OutsideRootApprover fn, void *user_data)

Install the approver consulted under optional (v2.13.0).

src/mcp/servers/filesystem.cpp:2377

Show on the map →

Called by TEST_CASE, set_outside_root_approver

Calls none

Source · 9 lines
void FilesystemServer::set_outside_root_approver(
    OutsideRootApprover fn, void* user_data) {
    std::lock_guard<std::mutex> lock(approver_mutex_);
    approver_ = fn;
    approver_data_ = user_data;
    logger->info("Outside-root approver {} (root: {})",
                 fn != nullptr ? "installed" : "cleared",
                 root_dir_.string());
}
Activity · 4 steps
lines 2379–2379std::lock_guard<std::mutex> lock(approver_mutex_);lines 2380–2380approver_ = fn;lines 2381–2381approver_data_ = user_data;lines 2382–2384logger->info("Outside-root approver {} (root: {})", fn != nullptr ? "installed" : "cleared", root_dir_.string());

Requirements

REQ-MCP-021

set_working_dir

bool entropic::FilesystemServer::set_working_dir(const std::string &path) override

Set working directory (changes root_dir).

src/mcp/servers/filesystem.cpp:2157

Show on the map →

Called by TEST_CASE, TEST_CASE, set_working_dir_all

Calls load, log_outside_root_policy, rule_count

Source · 16 lines
bool FilesystemServer::set_working_dir(const std::string& path) {
    auto canonical = fs::weakly_canonical(path);
    if (!fs::is_directory(canonical)) {
        logger->error("set_working_dir: not a directory: {}",
                      path);
        return false;
    }
    root_dir_ = canonical;
    // Issue #15 (v2.1.4): reload ignore rules for the new root.
    ignore_.load(root_dir_);
    logger->info("Working directory changed to: {} (ignore_rules={})",
                 root_dir_.string(), ignore_.rule_count());
    // v2.13.0: "outside the root" just moved; say what that now means.
    log_outside_root_policy();
    return true;
}
Activity · 9 steps
lines 2158–2158auto canonical = fs::weakly_canonical(path);lines 2159–2159◇ if (!fs::is_directory(canonical))lines 2160–2161logger->error("set_working_dir: not a directory: {}", path);lines 2162–2162return false;lines 2164–2164root_dir_ = canonical;lines 2166–2166ignore_.load(root_dir_);lines 2167–2168logger->info("Working directory changed to: {} (ignore_rules={})", root_dir_.string(), ignore_.rule_count());lines 2170–2170log_outside_root_policy();lines 2171–2171return true;

Requirements

REQ-MCP-021 REQ-MCP-022

should_skip_dir

bool entropic::anonymous_namespace{filesystem.cpp}::should_skip_dir(const std::string &name)

Check if a directory name should be skipped.

src/mcp/servers/filesystem.cpp:129

Source · 3 lines
bool should_skip_dir(const std::string& name) {
    return IgnoreMatcher::is_skipped_dir_name(name);
}
Activity · 1 steps
lines 130–130return IgnoreMatcher::is_skipped_dir_name(name);

Requirements

REQ-MCP-022

skip_duplicate_check

bool entropic::FilesystemServer::skip_duplicate_check(const std::string &tool_name) const override

read_file must always execute (updates FileAccessTracker ).

src/mcp/servers/filesystem.cpp:2138

Show on the map →

Called by none

Calls none

Source · 4 lines
bool FilesystemServer::skip_duplicate_check(
    const std::string& tool_name) const {
    return tool_name == "read_file";
}
Activity · 1 steps
lines 2140–2140return tool_name == "read_file";

Requirements

REQ-MCP-015 REQ-MCP-021

tracker

FileAccessTracker & entropic::FilesystemServer::tracker()

Get the file access tracker.

src/mcp/servers/filesystem.cpp:2193

Show on the map →

Called by TEST_CASE, execute, read_and_track

Calls none

Source · 3 lines
FileAccessTracker& FilesystemServer::tracker() {
    return tracker_;
}
Activity · 1 steps
lines 2194–2194return tracker_;

Requirements

REQ-MCP-021

was_read

bool entropic::FileAccessTracker::was_read(const std::string &session, const std::string &path) const

Check whether session has read a file.

src/mcp/servers/filesystem.cpp:79

Source · 6 lines
bool FileAccessTracker::was_read(const std::string& session,
                                 const std::string& path) const {
    return reads_.peek(session, [&](const auto* reads) {
        return reads != nullptr && reads->count(path) > 0;
    });
}
Activity · 1 steps
lines 81–83return reads_.peek(session, [&](const auto* reads) { return reads != nullptr && reads->count(path) > 0; });

Requirements

REQ-LOOP-009 REQ-MCP-021

write_file_contents

void entropic::anonymous_namespace{filesystem.cpp}::write_file_contents(const fs::path &path, const std::string &content)

Write string contents to a file, creating parent dirs.

src/mcp/servers/filesystem.cpp:409

Source · 10 lines
void write_file_contents(const fs::path& path,
                         const std::string& content) {
    fs::create_directories(path.parent_path());
    std::ofstream out(path, std::ios::binary | std::ios::trunc);
    if (!out.is_open()) {
        throw std::runtime_error(
            "Cannot write file: " + path.string());
    }
    out << content;
}
Activity · 5 steps
lines 411–411fs::create_directories(path.parent_path());lines 412–412std::ofstream out(path, std::ios::binary | std::ios::trunc);lines 413–413◇ if (!out.is_open())lines 414–415throw std::runtime_error( "Cannot write file: " + path.string());lines 417–417out << content;

Requirements

REQ-MCP-021