Feature(mcp): add read_file for byte-accurate remote text reads

read_file fetches a single remote file through the existing V2 download
channel into a per-call temp directory, decodes it, and deletes the temp
files on every exit path. It returns the file size, detected encoding, EOL
style, total line count, the requested slice (negative offset counts from
the end), a truncation flag and the whole file's SHA-256.

Encoding auto-detection follows BOM -> UTF-8 validity -> GBK fallback, and
utf-8/gbk/gb18030/latin1 can be forced. Files above 2MB and directories are
rejected from the first chunk, so nothing is written to disk for them.
The tool is gated by McpFileTransfer only: it never writes to the remote
host, so it stays available in readonly mode.

The V2 receive path now serves both download_file and read_file.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-12 16:11:27 +01:00
1 parent 0378e96470
commit 697044d84b
4 files changed
+663 -10

No files matched your search

+102 -1
View File
@@ -15,7 +15,7 @@
],
"version": 2,
"protocolVersion": "2025-06-18",
"toolCount": 63,
"toolCount": 64,
"tools": [
{
"name": "list_online_hosts",
@@ -2926,6 +2926,107 @@
"type": "object"
}
},
{
"name": "read_file",
"description": "按字节读取指定在线主机上的一个文本文件(分页 + 编码识别 + 整文件 SHA-256),只支持单个普通文件。path 为远程绝对路径:Windows 用 D:\\cfg\\app.ini 这类盘符路径,Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。offset 支持负数(-200 = 最后 200 行,看日志尾部);limit 为最多返回的行数(默认 2000);encoding=auto 时按 BOM → UTF-8 合法性 → GBK 回退识别,也可显式传 utf-8 / gbk / latin1;max_bytes 限制本次返回的文本字节数(默认 262144=256KB,超出按 truncated=true 截断)。目录、或大于 2MB 的文件返回 -32602(请改用 download_file)。返回 size/encoding/eol/lines_total/offset/lines_returned/truncated/text/sha256(sha256 是整个文件,不是本次片段)。读配置文件/日志时用它,不要用 exec_command 的 type/Get-Content(GBK 会乱码、行尾会被归一化)。",
"gate": "file_transfer",
"platforms": [
"win",
"lnx",
"mac"
],
"impl": "mfc",
"inputSchema": {
"properties": {
"encoding": {
"description": "auto(默认,按 BOM → UTF-8 合法性 → GBK 回退)/ utf-8 / gbk / gb18030 / latin1",
"type": "string"
},
"id": {
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
"type": "string"
},
"limit": {
"description": "最多返回的行数(1..200000,默认 2000)",
"type": "integer"
},
"max_bytes": {
"description": "本次返回文本的字节上限(1024..2097152,默认 262144=256KB),超出按 truncated=true 截断",
"type": "integer"
},
"offset": {
"description": "起始行(0 基)。负数表示从末尾倒数:-200 = 最后 200 行;默认 0",
"type": "integer"
},
"path": {
"description": "远程文件的绝对路径。Windows 用 D:\\cfg\\app.ini 这类盘符路径;Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。必须是单个普通文件(目录或大于 2MB 的文件返回 -32602)",
"type": "string"
}
},
"required": [
"id",
"path"
],
"type": "object"
},
"outputSchema": {
"properties": {
"encoding": {
"description": "实际使用的编码:utf-8 / utf-16le / utf-16be / gbk / gb18030 / latin1",
"type": "string"
},
"eol": {
"description": "行尾风格:crlf / lf / cr / mixed / none",
"type": "string"
},
"lines_returned": {
"description": "本次返回的行数",
"type": "integer"
},
"lines_total": {
"description": "文件总行数(末尾换行不计空行)",
"type": "integer"
},
"offset": {
"description": "本次实际起始行(负数已换算成绝对行号)",
"type": "integer"
},
"path": {
"description": "远程路径(原样回传)",
"type": "string"
},
"sha256": {
"description": "整个文件的 SHA-256(不是本次片段),可与 download_file 的结果比对",
"type": "string"
},
"size": {
"description": "文件总字节数",
"type": "integer"
},
"text": {
"description": "文件内容(UTF-8,行以 \\n 分隔,已去掉 BOM)",
"type": "string"
},
"truncated": {
"description": "true=还有内容没返回(超出 limit / max_bytes),可调整 offset 继续读",
"type": "boolean"
}
},
"required": [
"path",
"size",
"encoding",
"eol",
"lines_total",
"offset",
"lines_returned",
"truncated",
"text",
"sha256"
],
"type": "object"
}
},
{
"name": "upload_file",
"description": "把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。",
+552 -7
View File
@@ -13,6 +13,7 @@
#include "McpChat.h" // 远程交谈工具族
#include <sstream>
#include <fstream>
#ifndef _WIN64
#ifdef _DEBUG
@@ -312,7 +313,8 @@ const char* kServerInstructions =
u8"看主机:get_host_detail 先看 clientType 与 monitors,再决定用哪些工具;列表结果是快照,"
u8"主机可能在你操作期间掉线。\n"
u8"文件:list_files 列盘(省略 path)或列目录 → search_file 按名字查找(递归深度 32、最多 1 万条,"
u8"从盘符根扫描很慢且易截断,尽量指定具体目录)→ download_file 取回、upload_file 送到目标。"
u8"从盘符根扫描很慢且易截断,尽量指定具体目录)→ 看文本内容用 read_file(按字节解码,自动识别 UTF-8/GBK,"
u8"offset=-N 看尾部,不要用 type/Get-Content 读配置和日志)→ download_file 取回、upload_file 送到目标。"
u8"整理目标机上的东西用 delete_path / move_path / create_folder(需 McpFileWrite 开关),"
u8"它们的 ok 同样只代表客户端回了完成包,真实结果看 verified(true=复核确认生效、"
u8"false=复核确认未生效、null=复核没做成);删除不可恢复,recursive 必须显式传 true。"
@@ -2057,6 +2059,10 @@ std::string BuildRemoteBlockInput(const Json::Value& id, const Json::Value& args
Json::Value BuildDownloadFileInputSchema();
Json::Value BuildDownloadFileOutputSchema();
std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// P0-3:按字节读远端文本文件(复用 download_file 的 V2 接收端,读后即删临时文件)
Json::Value BuildReadFileInputSchema();
Json::Value BuildReadFileOutputSchema();
std::string BuildReadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
Json::Value BuildUploadFileInputSchema();
Json::Value BuildUploadFileOutputSchema();
std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
@@ -2600,6 +2606,17 @@ std::string BuildToolsListResult(const Json::Value& id) {
tools.append(tool);
}
// 16b) read_file(P0-3:按字节读远端文本文件;复用 download_file 的 V2 接收端)
// 独立开关 McpFileTransfer=1,不需要 McpReadonly=0:只读远端,不写。
if (CMcpServer::Instance().IsFileTransferEnabled()) {
Json::Value tool(Json::objectValue);
tool["name"] = "read_file";
tool["description"] = u8"按字节读取指定在线主机上的一个文本文件(分页 + 编码识别 + 整文件 SHA-256),只支持单个普通文件。path 为远程绝对路径:Windows 用 D:\\cfg\\app.ini 这类盘符路径,Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。offset 支持负数(-200 = 最后 200 行,看日志尾部);limit 为最多返回的行数(默认 2000);encoding=auto 时按 BOM → UTF-8 合法性 → GBK 回退识别,也可显式传 utf-8 / gbk / latin1;max_bytes 限制本次返回的文本字节数(默认 262144=256KB,超出按 truncated=true 截断)。目录、或大于 2MB 的文件返回 -32602(请改用 download_file)。返回 size/encoding/eol/lines_total/offset/lines_returned/truncated/text/sha256(sha256 是整个文件,不是本次片段)。读配置文件/日志时用它,不要用 exec_command 的 type/Get-Content(GBK 会乱码、行尾会被归一化)。";
tool["inputSchema"] = BuildReadFileInputSchema();
tool["outputSchema"] = BuildReadFileOutputSchema();
tools.append(tool);
}
// 17) upload_file(P2:MCP 文件上传,安全门:McpFileTransfer=1 且 McpReadonly=0)
// 写远程盘,故额外要求关闭只读(与 terminal_* / remote_* 一致)。
if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) {
@@ -7377,6 +7394,502 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM
return BuildError(id, -32001, msg);
}
// ===== P0-3:read_file(复用 download_file 的 V2 接收端,读后即删临时文件) =====
// 拒绝下载的体积门槛:2MB 以上的文件先落盘再读没有意义,直接让调用方改用 download_file。
static const uint64_t kReadFileSizeGate = 2 * 1024 * 1024;
static const int kReadFileDefaultMaxBytes = 262144; // 单次返回的文本字节上限
static const int kReadFileDefaultLimit = 2000; // 单次返回的最大行数
static const int kReadFileTimeoutMs = 120000; // 2MB 文件在这个时间内收不完就算失败
// read_file 的两种「不该下载」结局(文件传输会话的 error 值,这里映射成 -32602)。
static const int kFileXferTooLarge = 1008; // 首包 fileSize > maxFileBytes
static const int kFileXferPathIsDir = 1009; // 路径是目录 / 命中多个文件
// 服务端临时根目录:%APPDATA%\<BRAND_DATA_FOLDER>\mcp\tmp(用户可写,不依赖安装目录权限)。
static bool GetMcpTmpRootA(std::string& out) {
char appdata[MAX_PATH] = { 0 };
if (FAILED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, appdata))) return false;
std::string root = std::string(appdata) + "\\" BRAND_DATA_FOLDER "\\mcp\\tmp";
if (!EnsureDirA(root)) return false;
out = root;
return true;
}
// 递归删一颗小目录树(read_file 的临时目录里正常只有一个文件)。
static void DeleteTreeA(const std::string& dir) {
WIN32_FIND_DATAA fd;
HANDLE h = FindFirstFileA((dir + "\\*").c_str(), &fd);
if (h != INVALID_HANDLE_VALUE) {
do {
if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) continue;
std::string p = dir + "\\" + fd.cFileName;
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) RemoveDirectoryA(p.c_str());
else DeleteTreeA(p);
} else {
DeleteFileA(p.c_str());
}
} while (FindNextFileA(h, &fd));
FindClose(h);
}
RemoveDirectoryA(dir.c_str());
}
// RAII:成功、超时、取消、异常四条路径都靠析构清理临时文件(评审要求)。
struct McpScopedTmpDir {
std::string dir;
explicit McpScopedTmpDir(std::string d) : dir(std::move(d)) {}
~McpScopedTmpDir() { if (!dir.empty()) DeleteTreeA(dir); }
McpScopedTmpDir(const McpScopedTmpDir&) = delete;
McpScopedTmpDir& operator=(const McpScopedTmpDir&) = delete;
};
static bool IsValidUtf8(const std::string& s) {
if (s.empty()) return true;
return MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), (int)s.size(), nullptr, 0) > 0;
}
// 按指定代码页把定长字节转成 UTF-8(不依赖 NUL 结尾,容忍文件里的 0x00)。
static std::string BytesToUtf8(const char* data, int len, UINT cp) {
if (len <= 0) return std::string();
int wlen = MultiByteToWideChar(cp, 0, data, len, nullptr, 0);
if (wlen <= 0) return std::string();
std::wstring w((size_t)wlen, L'\0');
MultiByteToWideChar(cp, 0, data, len, &w[0], wlen);
int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), wlen, nullptr, 0, nullptr, nullptr);
if (n <= 0) return std::string();
std::string out((size_t)n, '\0');
WideCharToMultiByte(CP_UTF8, 0, w.data(), wlen, &out[0], n, nullptr, nullptr);
return out;
}
// UTF-16(BOM 已剥离)→ UTF-8。手工拼 wchar:实测 MultiByteToWideChar(1200) 在本机直接返回 0。
static std::string Utf16ToUtf8(const char* data, int len, bool bigEndian) {
if (len < 2) return std::string();
const int n = len / 2;
std::wstring w((size_t)n, L'\0');
for (int i = 0; i < n; ++i) {
const unsigned char lo = (unsigned char)data[2 * i];
const unsigned char hi = (unsigned char)data[2 * i + 1];
w[(size_t)i] = bigEndian ? (wchar_t)((lo << 8) | hi) : (wchar_t)((hi << 8) | lo);
}
int m = WideCharToMultiByte(CP_UTF8, 0, w.data(), n, nullptr, 0, nullptr, nullptr);
if (m <= 0) return std::string();
std::string out((size_t)m, '\0');
WideCharToMultiByte(CP_UTF8, 0, w.data(), n, &out[0], m, nullptr, nullptr);
return out;
}
static std::string Latin1ToUtf8(const std::string& s) { std::string out;
out.reserve(s.size());
for (size_t i = 0; i < s.size(); ++i) {
unsigned char c = (unsigned char)s[i];
if (c < 0x80) out += (char)c;
else { out += (char)(0xC0 | (c >> 6)); out += (char)(0x80 | (c & 0x3F)); }
}
return out;
}
// 解码:BOM → UTF-8 合法性 → GBK 回退(auto);也接受显式 utf-8 / gbk / latin1。
static bool DecodeFileText(const std::string& raw, const std::string& requested,
std::string& utf8Out, std::string& encodingOut, std::string& err) {
const std::string enc = ToLowerAscii(requested.empty() ? "auto" : requested);
const unsigned char* b = (const unsigned char*)raw.data();
auto stripUtf8Bom = [&]() {
if (raw.size() >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) return raw.substr(3);
return raw;
};
if (enc == "auto") {
if (raw.size() >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) {
utf8Out = raw.substr(3);
encodingOut = "utf-8";
} else if (raw.size() >= 2 && b[0] == 0xFF && b[1] == 0xFE) {
utf8Out = Utf16ToUtf8(raw.data() + 2, (int)raw.size() - 2, false); // UTF-16LE
encodingOut = "utf-16le";
} else if (raw.size() >= 2 && b[0] == 0xFE && b[1] == 0xFF) {
utf8Out = Utf16ToUtf8(raw.data() + 2, (int)raw.size() - 2, true); // UTF-16BE
encodingOut = "utf-16be";
} else if (IsValidUtf8(raw)) {
utf8Out = raw;
encodingOut = "utf-8";
} else {
utf8Out = BytesToUtf8(raw.data(), (int)raw.size(), 936); // CP936 = GBK
encodingOut = "gbk";
}
return true;
}
if (enc == "utf-8" || enc == "utf8") {
utf8Out = stripUtf8Bom();
encodingOut = "utf-8";
return true;
}
if (enc == "gbk" || enc == "gb18030") {
utf8Out = BytesToUtf8(raw.data(), (int)raw.size(), enc == "gb18030" ? 54936 : 936);
encodingOut = enc;
return true;
}
if (enc == "latin1" || enc == "iso-8859-1") {
utf8Out = Latin1ToUtf8(raw);
encodingOut = "latin1";
return true;
}
err = "Unsupported encoding: " + requested + " (use auto / utf-8 / gbk / latin1)";
return false;
}
// 行尾风格:crlf / lf / cr / mixed / none。
static std::string DetectEol(const std::string& t) {
size_t crlf = 0, lf = 0, cr = 0;
for (size_t i = 0; i < t.size(); ++i) {
if (t[i] == '\r') {
if (i + 1 < t.size() && t[i + 1] == '\n') { ++crlf; ++i; }
else ++cr;
} else if (t[i] == '\n') {
++lf;
}
}
if (crlf + lf + cr == 0) return "none";
if (crlf && !lf && !cr) return "crlf";
if (lf && !crlf && !cr) return "lf";
if (cr && !crlf && !lf) return "cr";
return "mixed";
}
// 统一成 '\n'(行号计算与返回文本都用它,避免把 CRLF 当两个字符算)。
static std::string NormalizeEol(const std::string& t) {
std::string out;
out.reserve(t.size());
for (size_t i = 0; i < t.size(); ++i) {
if (t[i] == '\r') {
if (i + 1 < t.size() && t[i + 1] == '\n') ++i;
out += '\n';
} else {
out += t[i];
}
}
return out;
}
// 按 '\n' 切行;末尾换行不额外产生一个空行(与 Get-Content / readlines 一致)。
static std::vector<std::string> SplitTextLines(const std::string& t) {
std::vector<std::string> lines;
if (t.empty()) return lines;
size_t start = 0;
while (start < t.size()) {
size_t nl = t.find('\n', start);
if (nl == std::string::npos) { lines.push_back(t.substr(start)); break; }
lines.push_back(t.substr(start, nl - start));
start = nl + 1;
}
return lines;
}
Json::Value BuildReadFileInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value pathProp(Json::objectValue);
pathProp["type"] = "string";
pathProp["description"] = u8"远程文件的绝对路径。Windows 用 D:\\cfg\\app.ini 这类盘符路径;Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。必须是单个普通文件(目录或大于 2MB 的文件返回 -32602)";
props["path"] = pathProp;
Json::Value off(Json::objectValue);
off["type"] = "integer";
off["description"] = u8"起始行(0 基)。负数表示从末尾倒数:-200 = 最后 200 行;默认 0";
props["offset"] = off;
Json::Value lim(Json::objectValue);
lim["type"] = "integer";
lim["description"] = u8"最多返回的行数(1..200000,默认 2000)";
props["limit"] = lim;
Json::Value enc(Json::objectValue);
enc["type"] = "string";
enc["description"] = u8"auto(默认,按 BOM → UTF-8 合法性 → GBK 回退)/ utf-8 / gbk / gb18030 / latin1";
props["encoding"] = enc;
Json::Value mb(Json::objectValue);
mb["type"] = "integer";
mb["description"] = u8"本次返回文本的字节上限(1024..2097152,默认 262144=256KB),超出按 truncated=true 截断";
props["max_bytes"] = mb;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("path");
schema["required"] = required;
return schema;
}
Json::Value BuildReadFileOutputSchema() {
Json::Value props(Json::objectValue);
auto strProp = [&](const char* k, const char* d) {
Json::Value p(Json::objectValue); p["type"] = "string"; p["description"] = d; props[k] = p;
};
auto intProp = [&](const char* k, const char* d) {
Json::Value p(Json::objectValue); p["type"] = "integer"; p["description"] = d; props[k] = p;
};
strProp("path", u8"远程路径(原样回传)");
intProp("size", u8"文件总字节数");
strProp("encoding", u8"实际使用的编码:utf-8 / utf-16le / utf-16be / gbk / gb18030 / latin1");
strProp("eol", u8"行尾风格:crlf / lf / cr / mixed / none");
intProp("lines_total", u8"文件总行数(末尾换行不计空行)");
intProp("offset", u8"本次实际起始行(负数已换算成绝对行号)");
intProp("lines_returned", u8"本次返回的行数");
Json::Value tr(Json::objectValue);
tr["type"] = "boolean";
tr["description"] = u8"true=还有内容没返回(超出 limit / max_bytes),可调整 offset 继续读";
props["truncated"] = tr;
strProp("text", u8"文件内容(UTF-8,行以 \\n 分隔,已去掉 BOM)");
strProp("sha256", u8"整个文件的 SHA-256(不是本次片段),可与 download_file 的结果比对");
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("path");
required.append("size");
required.append("encoding");
required.append("eol");
required.append("lines_total");
required.append("offset");
required.append("lines_returned");
required.append("truncated");
required.append("text");
required.append("sha256");
schema["required"] = required;
return schema;
}
// tools/call:read_file(复用 download_file 的 V2 接收通道把文件拉到临时目录,读完即删)
std::string BuildReadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
// 读远端只读,不要求关闭 McpReadonly;但同样受 McpFileTransfer 总开关约束。
if (!mcp.IsFileTransferEnabled())
return BuildError(id, -32006, "File transfer is disabled: requires McpFileTransfer=1");
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
const bool posixTarget = (clientType == "LNX" || clientType == "MAC");
if (!ctx->SupportsFileV2())
return BuildError(id, -32006, "Host does not support V2 file transfer");
std::string pathUtf8 = GetStringArg(args, "path");
if (pathUtf8.empty())
return BuildError(id, -32602, "Missing required parameter: path");
int offset = 0;
if (args.isMember("offset") && !GetIntArg(args, "offset", offset))
return BuildError(id, -32602, "offset must be an integer");
if (offset < -100000000 || offset > 100000000)
return BuildError(id, -32602, "offset out of range");
int limit = kReadFileDefaultLimit;
if (args.isMember("limit")) {
int v = 0;
if (!GetIntArg(args, "limit", v) || v < 1 || v > 200000)
return BuildError(id, -32602, "limit must be in range 1..200000");
limit = v;
}
int maxBytes = kReadFileDefaultMaxBytes;
if (args.isMember("max_bytes")) {
int v = 0;
if (!GetIntArg(args, "max_bytes", v) || v < 1024 || v > 2 * 1024 * 1024)
return BuildError(id, -32602, "max_bytes must be in range 1024..2097152");
maxBytes = v;
}
const std::string encodingArg = GetStringArg(args, "encoding");
{
// 先验证编码名:写错时不要白跑一次下载。
std::string probeUtf8, probeEnc;
if (!DecodeFileText(std::string(), encodingArg, probeUtf8, probeEnc, err))
return BuildError(id, -32602, err);
}
std::string remotePathAnsi = ToAnsi(pathUtf8, 936);
if (remotePathAnsi.empty())
return BuildError(id, -32602, "Invalid path encoding");
if (posixTarget) {
if (remotePathAnsi[0] != '/')
return BuildError(id, -32602, "path must be an absolute POSIX path for Linux/macOS hosts, e.g. /etc/app.conf");
if (remotePathAnsi.find('\\') != std::string::npos)
return BuildError(id, -32602, "path must not contain backslashes on Linux/macOS hosts; use '/'");
if (HasDotDotSegment(remotePathAnsi))
return BuildError(id, -32602, "path must not contain '..' path segments");
}
// 临时目录:%APPDATA%\<BRAND_DATA_FOLDER>\mcp\tmp\<device_id>\<token>\(每次调用独立,防并发互踩)
std::string root;
if (!GetMcpTmpRootA(root))
return BuildError(id, -32000, "Failed to create the MCP temp directory");
std::string tmpDir = root + "\\" + std::to_string(devId) + "\\" + GenerateRandomToken();
if (!EnsureDirA(tmpDir))
return BuildError(id, -32000, "Failed to create the MCP temp directory");
McpScopedTmpDir cleanup(tmpDir);
std::string localDirAnsi = tmpDir + "\\";
if (!mcp.BeginFileTransferPending(devId, "read_file", localDirAnsi, remotePathAnsi, true, kReadFileSizeGate))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_LIST_DRIVE;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearFileTransfer(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<FileTransferEntry> files;
int skipped = 0, error = 0;
DWORD errorDetail = 0;
const bool ok = mcp.WaitFileTransferDone(devId, kReadFileTimeoutMs, files, skipped, error, &errorDetail);
mcp.ClearFileTransfer(devId); // 擦会话 + CancelIO 子链接(临时文件由 RAII 清理)
if (!ok) {
if (parent) {
std::string audit = "host " + std::to_string(devId) + " read_file FAILED (error "
+ std::to_string(error) + "): " + pathUtf8;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP文件传输")));
}
// 两类「不该下载」的结局在首包就被拒收(没有落盘),给参数字典级错误码。
if (error == kFileXferTooLarge)
return BuildError(id, -32602, "File is larger than 2MB: use download_file to fetch it (" + pathUtf8 + ")");
if (error == kFileXferPathIsDir)
return BuildError(id, -32602, "Not a single regular file (directory or multiple matches): " + pathUtf8
+ " — use list_files / search_file to pick a specific file");
if (error == 1005 || error == 1006 || error == 1007) {
std::string detail = " (win32=" + std::to_string((int)errorDetail) + ")";
if (error == 1005)
return BuildError(id, -32009, "Remote path does not exist: " + pathUtf8 + detail);
if (error == 1006)
return BuildError(id, -32010, "Access denied to remote path: " + pathUtf8 + detail);
return BuildError(id, -32000, "Client could not queue the download of " + pathUtf8 + detail);
}
const char* msg = (error == 1002) ? "Timeout waiting for the file transfer"
: (error == 1004) ? "File transfer stalled: no data received for 60s "
"(the remote path is probably missing or inaccessible; "
"verify it with list_files first)"
: (error == 1001) ? "Path traversal detected in received path"
: (error == 1003) ? "Connection lost: the transfer sub-connection closed"
: (error == FEV2_HASH_MISMATCH) ? "File SHA-256 verification failed"
: "File transfer failed";
return BuildError(id, -32001, msg);
}
if (files.size() != 1)
return BuildError(id, -32602, "Expected exactly one file, got " + std::to_string(files.size())
+ " (path must be a single regular file): " + pathUtf8);
const FileTransferEntry& entry = files[0];
std::ifstream in(entry.path.c_str(), std::ios::binary);
if (!in)
return BuildError(id, -32000, "Failed to read the downloaded temp file");
std::string raw((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
in.close();
std::string utf8, encoding;
if (!DecodeFileText(raw, encodingArg, utf8, encoding, err))
return BuildError(id, -32602, err);
const std::string eol = DetectEol(utf8);
const std::string normalized = NormalizeEol(utf8);
const std::vector<std::string> lines = SplitTextLines(normalized);
const long long total = (long long)lines.size();
long long start = (offset >= 0) ? (long long)offset : total + (long long)offset;
if (start < 0) start = 0;
if (start > total) start = total;
std::string text;
long long count = 0;
bool capHit = false;
for (long long i = start; i < total && count < limit; ++i) {
const std::string& ln = lines[(size_t)i];
const size_t add = ln.size() + (text.empty() ? 0 : 1);
if (text.size() + add > (size_t)maxBytes) {
if (text.empty()) {
// 单行就超过上限:按字节硬切,回退到 UTF-8 字符边界,保证有内容返回
size_t cut = (size_t)maxBytes;
while (cut > 0 && cut < ln.size() && ((unsigned char)ln[cut] & 0xC0) == 0x80) --cut;
text = ln.substr(0, cut);
count = 1;
}
capHit = true;
break;
}
if (!text.empty()) text += '\n';
text += ln;
++count;
}
const bool moreLines = (start + count < total);
const bool truncated = capHit || moreLines;
const int linesReturned = (int)SplitTextLines(text).size();
if (parent) {
// 审计:只记路径/大小/范围,不落文件内容。
std::string audit = "host " + std::to_string(devId) + " read_file: " + pathUtf8
+ " (" + std::to_string(raw.size()) + " bytes, lines "
+ std::to_string(start) + "+" + std::to_string(count)
+ "/" + std::to_string(total) + ", " + encoding + ")";
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP文件传输")));
}
Json::Value structuredContent(Json::objectValue);
structuredContent["path"] = pathUtf8;
structuredContent["size"] = (Json::UInt64)raw.size();
structuredContent["encoding"] = encoding;
structuredContent["eol"] = eol;
structuredContent["lines_total"] = (Json::UInt64)total;
structuredContent["offset"] = (Json::Int64)start;
structuredContent["lines_returned"] = linesReturned;
structuredContent["truncated"] = truncated;
structuredContent["text"] = text;
structuredContent["sha256"] = entry.sha256;
Json::Value result(Json::objectValue);
result["structuredContent"] = structuredContent;
// 文本块 = 一行元信息 + 正文:只读 content 的客户端也能看到截断/编码,不至于默默漏读。
{
std::string head = "[read_file] " + pathUtf8 + " | " + std::to_string(raw.size()) + " bytes | "
+ encoding + " | " + eol + " | lines " + std::to_string(start) + "-"
+ std::to_string(start + count) + " of " + std::to_string(total)
+ " | truncated=" + (truncated ? "true" : "false")
+ " | sha256=" + entry.sha256;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = head + "\n" + text;
content.append(item);
result["content"] = content;
}
result["isError"] = false;
// 正文已在 content 里,别再让 BuildResult 追加一份 JSON 文本块(256KB 文本会被复制两遍)。
SetStructuredTextPayload(result, Json::Value(Json::objectValue));
return BuildResult(id, result);
}
// ===== P2:upload_file 辅助 =====
// ASCII 小写(GBK 双字节首字节 0x81..0xFE 不含 A-Z,安全);Windows 路径名不区分大小写。
@@ -10406,6 +10919,7 @@ const ToolPlatform kToolPlatforms[] = {
// Android 客户端同样实现了 COMMAND_QUERY_LOG → TOKEN_REPORT_LOG 子连接上报
{ "get_client_log", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "download_file", kPlatWin|kPlatLnx|kPlatMac },
{ "read_file", kPlatWin|kPlatLnx|kPlatMac },
{ "upload_file", kPlatWin|kPlatLnx|kPlatMac },
// ---- win+lnx(+apk) ---- 远程控制全族 + 需 SCREEN_PREVIEW 的截屏 + macOS 未开放项
// Android 用无障碍 takeScreenshot(API 30+,需开无障碍服务),只支持 mode=screen
@@ -10797,6 +11311,7 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
if (toolName == "remote_lock_screen") return BuildRemoteLockScreen(id, args, parent);
if (toolName == "remote_block_input") return BuildRemoteBlockInput(id, args, parent);
if (toolName == "download_file") return BuildDownloadFile(id, args, parent);
if (toolName == "read_file") return BuildReadFile(id, args, parent);
if (toolName == "upload_file") return BuildUploadFile(id, args, parent);
if (toolName == "copy_files_c2c") return BuildCopyFilesC2C(id, args, parent);
if (toolName == "kill_process") return BuildKillProcess(id, args, parent);
@@ -12395,7 +12910,7 @@ void CMcpServer::MarkLateFirstPacket(uint64_t device_id, std::initializer_list<B
// 工具 → 应答首包 token。只有「子连接第一个包会弹 MFC 窗口」的工具需要登记。
void CMcpServer::MarkLateFirstPacketForTool(uint64_t device_id, const std::string& tool) {
if (tool == "list_files" || tool == "download_file" || tool == "upload_file" || tool == "search_file" ||
if (tool == "list_files" || tool == "download_file" || tool == "read_file" || tool == "upload_file" || tool == "search_file" ||
IsFileWriteToolName(tool))
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_DRIVE_LIST });
else if (tool == "list_registry")
@@ -12840,6 +13355,11 @@ std::string GenerateRandomToken() {
// 60s 足够覆盖极慢链路,又远小于 download_file 默认的 600s 总超时。
static const int kFileXferStallMs = 60000;
// read_file 复用 download_file 的 V2 接收通道:这四处包处理按「下载类工具」放行。
static bool IsFileXferDownloadTool(const std::string& tool) {
return tool == "download_file" || tool == "read_file";
}
bool CMcpServer::IsFileTransferPending(uint64_t device_id) {
std::lock_guard<std::mutex> lk(m_FileXferMutex);
return m_FileXferSessions.find(device_id) != m_FileXferSessions.end();
@@ -12854,7 +13374,7 @@ bool CMcpServer::IsC2CTransferPending(uint64_t src_id, uint64_t dst_id) {
bool CMcpServer::BeginFileTransferPending(uint64_t device_id, const std::string& tool,
const std::string& localDir, const std::string& remotePath,
bool overwrite) {
bool overwrite, uint64_t maxFileBytes) {
// 与一次性挂起请求互斥(F2):先查对方注册表再查自己的,避免跨锁嵌套死锁。
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
@@ -12867,6 +13387,7 @@ bool CMcpServer::BeginFileTransferPending(uint64_t device_id, const std::string&
s.localDir = localDir;
s.remotePath = remotePath;
s.overwrite = overwrite;
s.maxFileBytes = maxFileBytes;
s.startAt = time(nullptr);
s.lastDataAt = std::chrono::steady_clock::now();
m_FileXferSessions[device_id] = std::move(s);
@@ -13020,7 +13541,7 @@ bool CMcpServer::OnDownloadDriveList(uint64_t device_id, context* fmSubCtx) {
{
std::lock_guard<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(device_id);
if (it == m_FileXferSessions.end() || it->second.tool != "download_file")
if (it == m_FileXferSessions.end() || !IsFileXferDownloadTool(it->second.tool))
return false; // 会话已清理 → 调用方 CancelIO 收尾
FileTransferSession& s = it->second;
if (s.fmSubCtx != nullptr) return true; // 已下发过,防重复
@@ -13057,7 +13578,7 @@ void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const
auto it = m_FileXferSessions.find(device_id);
if (it == m_FileXferSessions.end()) return;
FileTransferSession& s = it->second;
if (s.tool != "download_file") return;
if (!IsFileXferDownloadTool(s.tool)) return;
if (s.done) return; // 已出错/完成,丢弃迟到包
s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命
s.bytesReceived += pkt->dataLength; // P11:进度通知的兜底量(文件数未知时用)
@@ -13074,6 +13595,30 @@ void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const
uint32_t fileIndex = pkt->fileIndex;
std::string fileName((char*)(pkt + 1), pkt->nameLength); // ANSI = localDir + relPath
// read_file 只收单个普通文件:目录项与超大文件在首包就拒收(不落盘、不建目录)。
if (s.tool == "read_file") {
if (pkt->flags & FFV2_DIRECTORY) {
s.error = kFileXferPathIsDir;
s.done = true;
m_FileXferCv.notify_one();
return;
}
if (pkt->offset == 0) {
if (s.maxFileBytes > 0 && pkt->fileSize > s.maxFileBytes) {
s.error = kFileXferTooLarge;
s.done = true;
m_FileXferCv.notify_one();
return;
}
if (!s.fileEntries.empty() && s.fileEntries.find(fileIndex) == s.fileEntries.end()) {
s.error = kFileXferPathIsDir; // 一个路径命中多个文件,read_file 不接受
s.done = true;
m_FileXferCv.notify_one();
return;
}
}
}
// 目录项:只建目录(RecvFileChunkV2 会 mkdir),不参与 files 输出(见 §13 F4)。
// 与文件项一样先做路径穿越校验(F5):目录项的 filename 同样可能越界(如远程目录名含 ..)。
if (pkt->flags & FFV2_DIRECTORY) {
@@ -13138,7 +13683,7 @@ void CMcpServer::OnDownloadError(uint64_t device_id, context* fmSubCtx, const BY
auto it = m_FileXferSessions.find(device_id);
if (it == m_FileXferSessions.end()) return;
FileTransferSession& s = it->second;
if (s.tool != "download_file") return;
if (!IsFileXferDownloadTool(s.tool)) return;
if (s.fmSubCtx != fmSubCtx) return; // 非本会话的子连接 → 忽略
if (s.done) return; // 已出错/完成,丢弃迟到包
s.error = (win32err == ERROR_FILE_NOT_FOUND || win32err == ERROR_PATH_NOT_FOUND) ? 1005
@@ -13157,7 +13702,7 @@ void CMcpServer::OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len
auto it = m_FileXferSessions.find(device_id);
if (it == m_FileXferSessions.end()) return;
FileTransferSession& s = it->second;
if (s.tool != "download_file") return;
if (!IsFileXferDownloadTool(s.tool)) return;
if (s.done) return;
s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命
+6 -2
View File
@@ -392,9 +392,10 @@ public:
bool IsC2CTransferPending(uint64_t src_id, uint64_t dst_id);
// 登记文件传输会话(false = 该 host 已有文件会话或一次性挂起请求)。
// maxFileBytes 仅 read_file 使用:首包文件尺寸超过它就拒收(0=不限)。
bool BeginFileTransferPending(uint64_t device_id, const std::string& tool,
const std::string& localDir, const std::string& remotePath,
bool overwrite);
bool overwrite, uint64_t maxFileBytes = 0);
// 登记上传会话(false = 该 host 已有文件会话或一次性挂起请求)。upload 走主连接、
// 工具线程同步驱动 FileBatchTransferWorkerV2。会话同时用于单设备单传输互斥与
@@ -918,7 +919,10 @@ private:
uint32_t filesDone = 0; // 已完成的文件数(含跳过的)
bool done = false; // 全部完成或出错
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线;
// 1004=停滞(看门狗);1005=远端路径不存在;1006=拒绝访问;1007=其他下载失败
// 1004=停滞(看门狗);1005=远端路径不存在;1006=拒绝访问;1007=其他下载失败;
// 1008=read_file 拒绝:文件大于 maxFileBytes;1009=read_file 拒绝:路径是目录或命中多个文件
// read_file 专用:只收单个普通文件,首包文件尺寸超过该值直接拒收(0=不限,download_file 用)
uint64_t maxFileBytes = 0;
DWORD errorDetail = 0; // error=1005/1006/1007 时的 win32 码(原样带进文案,便于分支/排查)
std::map<uint32_t, FileTransferEntry> fileEntries; // fileIndex → {path,size,sha256}
std::set<uint32_t> skipIndexes; // overwrite=false 跳过的 fileIndex
+3
View File
@@ -64,6 +64,8 @@ GATE = {
# ---- file_transfer ----
"download_file": ("file_transfer", True, False),
# read_file 只读远端(不写),因此不受 readonly 约束
"read_file": ("file_transfer", False, False),
"upload_file": ("file_transfer", True, False),
"copy_files_c2c": ("file_transfer", True, False),
@@ -173,6 +175,7 @@ PLATFORMS = {
# 需要 CLIENT_CAP_V2;三个桌面平台的 DefaultCaps() 都含 V2
"download_file": _TRIO,
"read_file": _TRIO,
"upload_file": _TRIO,
# 远程控制:Windows / Linux 全功能;Android 只支持整屏目标,输入翻译成触摸与全局动作