diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json
new file mode 100644
index 0000000..1490bfb
--- /dev/null
+++ b/.config/dotnet-tools.json
@@ -0,0 +1,13 @@
+{
+ "version": 1,
+ "isRoot": true,
+ "tools": {
+ "docfx": {
+ "version": "2.81.0",
+ "commands": [
+ "docfx"
+ ],
+ "rollForward": false
+ }
+ }
+}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..3a88a3d
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,35 @@
+name: CI
+
+on:
+ push:
+ branches: ["**"]
+ tags-ignore: ["**"]
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ # windows: unit-тесты ширины глифов XPS берут системный шрифт arial.ttf
+ runs-on: windows-latest
+ steps:
+ - uses: actions/checkout@v5
+
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+
+ - name: Build
+ run: dotnet build PilotMCP.slnx -c Debug --nologo
+
+ # Интеграционные тесты (Category=Integration) требуют живой сервер Pilot — в CI только unit-тесты
+ - name: Unit tests
+ run: dotnet test PilotMCP.slnx -c Debug --no-build --nologo --filter "Category!=Integration" --logger "trx;LogFileName=unit.trx"
+
+ - name: Upload test results
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: test-results
+ path: "**/TestResults/*.trx"
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
new file mode 100644
index 0000000..08d77be
--- /dev/null
+++ b/.github/workflows/docs.yml
@@ -0,0 +1,62 @@
+name: Docs
+
+on:
+ push:
+ branches: [master]
+ paths:
+ - 'docs/**'
+ - 'docfx.json'
+ - '.config/dotnet-tools.json'
+ - 'Tools/**'
+ - 'DocGen/**'
+ - 'README.md'
+ - '.github/workflows/docs.yml'
+ pull_request:
+ paths:
+ - 'docs/**'
+ - 'docfx.json'
+ - '.config/dotnet-tools.json'
+ - 'Tools/**'
+ - 'DocGen/**'
+ - 'README.md'
+ - '.github/workflows/docs.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: pages-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-dotnet@v6
+ with:
+ dotnet-version: 8.0.x
+ # Справочник инструментов docs/tools/ генерируется по коду; падает, если список записи расходится с README
+ - run: dotnet run --project DocGen
+ - run: dotnet tool restore
+ - run: dotnet docfx docfx.json --warningsAsErrors
+ # manifest.json records the build machine paths and is not part of the site.
+ - run: rm _site/manifest.json
+ - uses: actions/upload-pages-artifact@v5
+ with:
+ path: _site
+
+ deploy:
+ if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request'
+ needs: build
+ runs-on: ubuntu-latest
+ permissions:
+ pages: write
+ id-token: write
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ steps:
+ - id: deployment
+ uses: actions/deploy-pages@v5
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..651ce94
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,141 @@
+name: Release
+
+# Релиз по тегу vX.Y.Z (semver, допускается суффикс -beta.1):
+# 1) unit-тесты, сборка zip-архивов win-x64 (PackReleaseArchives в PilotMCP.csproj);
+# 2) MCPB-бандл из self-contained сборки (установка в Claude Desktop);
+# 3) GitHub Release с архивами и .mcpb;
+# 4) публикация метаданных в официальный MCP Registry (OIDC, без секретов).
+on:
+ push:
+ tags: ["v*"]
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ runs-on: windows-latest
+ permissions:
+ contents: write # создание GitHub Release
+ defaults:
+ run:
+ shell: pwsh
+ steps:
+ - uses: actions/checkout@v5
+
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+
+ - uses: actions/setup-node@v5
+ with:
+ node-version: "lts/*"
+
+ - name: Version from tag
+ id: ver
+ run: |
+ $tag = "${{ github.ref_name }}"
+ if ($tag -notmatch '^v(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?)$') { throw "Тег '$tag' должен иметь вид vX.Y.Z" }
+ $v = $Matches[1]
+ "version=$v" >> $env:GITHUB_OUTPUT
+ "prerelease=$([bool]($v -match '-'))".ToLower() >> $env:GITHUB_OUTPUT
+
+ - name: Unit tests
+ run: dotnet test PilotMCP.Tests/PilotMCP.Tests.csproj -c Release --nologo --filter "Category!=Integration"
+
+ - name: Build release archives
+ run: dotnet build PilotMCP.csproj -c Release --nologo -p:Version=${{ steps.ver.outputs.version }}
+
+ - name: Build MCPB bundle
+ id: mcpb
+ run: |
+ $v = "${{ steps.ver.outputs.version }}"
+ $sc = "artifacts/PilotMCP-v$v-win-x64-selfcontained.zip"
+ if (-not (Test-Path $sc)) { throw "Нет $sc" }
+
+ New-Item -ItemType Directory -Force mcpb-build/server | Out-Null
+ Expand-Archive $sc -DestinationPath mcpb-build/server -Force
+ $m = Get-Content mcpb/manifest.json -Raw | ConvertFrom-Json
+ $m.version = $v
+ $m | ConvertTo-Json -Depth 20 | Set-Content mcpb-build/manifest.json -Encoding utf8NoBOM
+
+ npm install -g @anthropic-ai/mcpb@2.1.2
+ mcpb validate mcpb-build/manifest.json
+ if ($LASTEXITCODE -ne 0) { throw "mcpb validate failed" }
+ $out = "artifacts/PilotMCP-v$v-win-x64.mcpb"
+ mcpb pack mcpb-build $out
+ if ($LASTEXITCODE -ne 0) { throw "mcpb pack failed" }
+
+ $sha = (Get-FileHash $out -Algorithm SHA256).Hash.ToLowerInvariant()
+ "sha256=$sha" >> $env:GITHUB_OUTPUT
+ "file=$out" >> $env:GITHUB_OUTPUT
+
+ - name: Prepare server.json for MCP Registry
+ run: |
+ $v = "${{ steps.ver.outputs.version }}"
+ $s = Get-Content server.json -Raw | ConvertFrom-Json
+ $s.version = $v
+ $p = $s.packages[0]
+ $p.version = $v
+ $p.identifier = "https://github.com/${{ github.repository }}/releases/download/${{ github.ref_name }}/PilotMCP-v$v-win-x64.mcpb"
+ $p.fileSha256 = "${{ steps.mcpb.outputs.sha256 }}"
+ New-Item -ItemType Directory -Force registry | Out-Null
+ $s | ConvertTo-Json -Depth 20 | Set-Content registry/server.json -Encoding utf8NoBOM
+ Get-Content registry/server.json
+
+ - name: Create GitHub Release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ $v = "${{ steps.ver.outputs.version }}"
+ $files = @("artifacts/PilotMCP-v$v-win-x64.zip", "artifacts/PilotMCP-v$v-win-x64-selfcontained.zip", "${{ steps.mcpb.outputs.file }}")
+ $ghArgs = @("release", "create", "${{ github.ref_name }}") + $files + @("--title", "PilotMCP ${{ github.ref_name }}", "--generate-notes")
+ if ("${{ steps.ver.outputs.prerelease }}" -eq "true") { $ghArgs += "--prerelease" }
+ gh @ghArgs
+ if ($LASTEXITCODE -ne 0) { throw "gh release create failed" }
+
+ - uses: actions/upload-artifact@v4
+ with:
+ name: registry-server-json
+ path: registry/server.json
+
+ publish-registry:
+ needs: build
+ runs-on: ubuntu-latest
+ permissions:
+ id-token: write # OIDC-вход в MCP Registry
+ contents: read
+ env:
+ MCP_PUBLISHER_VERSION: v1.8.9
+ steps:
+ - uses: actions/download-artifact@v4
+ with:
+ name: registry-server-json
+
+ # Шаги ниже — из официальной документации MCP Registry (modelcontextprotocol.io/registry/github-actions)
+ - name: Install cosign
+ uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2
+
+ - name: Download and verify mcp-publisher
+ run: |
+ set -euo pipefail
+ os="$(uname -s | tr '[:upper:]' '[:lower:]')"
+ arch="$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')"
+ archive="mcp-publisher_${os}_${arch}.tar.gz"
+ base_url="https://github.com/modelcontextprotocol/registry/releases/download/${MCP_PUBLISHER_VERSION}"
+
+ curl --fail --location --silent --show-error --output "$archive" "$base_url/$archive"
+ curl --fail --location --silent --show-error --output "$archive.sigstore.json" "$base_url/$archive.sigstore.json"
+ cosign verify-blob \
+ --bundle "$archive.sigstore.json" \
+ --certificate-identity "https://github.com/modelcontextprotocol/registry/.github/workflows/release.yml@refs/tags/${MCP_PUBLISHER_VERSION}" \
+ --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \
+ "$archive"
+ tar xzf "$archive" mcp-publisher
+ rm -f "$archive" "$archive.sigstore.json"
+
+ - name: Authenticate to MCP Registry
+ run: ./mcp-publisher login github-oidc
+
+ - name: Publish server to MCP Registry
+ run: ./mcp-publisher publish
diff --git a/.gitignore b/.gitignore
index 9491a2f..63ccc25 100644
--- a/.gitignore
+++ b/.gitignore
@@ -360,4 +360,8 @@ MigrationBackup/
.ionide/
# Fody - auto-generated XML schema
-FodyWeavers.xsd
\ No newline at end of file
+FodyWeavers.xsd
+
+# Документация (docfx): сайт и сгенерированный справочник инструментов
+_site/
+docs/tools/
diff --git a/DocGen/DocGen.csproj b/DocGen/DocGen.csproj
new file mode 100644
index 0000000..f5cd233
--- /dev/null
+++ b/DocGen/DocGen.csproj
@@ -0,0 +1,15 @@
+
+
+
+ Exe
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
diff --git a/DocGen/Program.cs b/DocGen/Program.cs
new file mode 100644
index 0000000..eb3b945
--- /dev/null
+++ b/DocGen/Program.cs
@@ -0,0 +1,214 @@
+using System.ComponentModel;
+using System.Globalization;
+using System.Reflection;
+using System.Text;
+using System.Text.RegularExpressions;
+using ModelContextProtocol.Server;
+using PilotMCP;
+
+// Генерирует справочник инструментов docs/tools/*.md по сборке PilotMCP (рефлексия + разбор Tools/*.cs).
+// Ненулевой код выхода — если признак «запись» из исходников расходится со списком PILOT_READONLY в README.md.
+
+var root = FindRoot();
+var outDir = Path.Combine(root, "docs", "tools");
+
+// Класс -> (slug страницы, заголовок). Порядок = порядок групп; классы с одним slug сливаются в одну страницу.
+var groupMap = new (string Class, string Slug, string Title)[]
+{
+ ("ConnectionTools", "connection", "Подключение"),
+ ("ObjectTools", "objects", "Объекты"),
+ ("FileUploadTools", "files", "Загрузка файлов"),
+ ("QueryTools", "search", "Навигация и поиск"),
+ ("PeopleTools", "people", "Пользователи и организация"),
+ ("PeopleAdminTools", "people-admin", "Управление пользователями и оргструктурой"),
+ ("TransformTools", "pipe", "Работа с файлами результатов"),
+ ("InspectTools", "pipe", "Работа с файлами результатов"),
+ ("ExportTools", "pipe", "Работа с файлами результатов"),
+ ("DocumentTools", "documents", "Документы"),
+ ("AnnotationTools", "annotations", "Замечания (аннотации)"),
+ ("HistoryTools", "history", "История и версии"),
+ ("AccessTools", "access", "Права доступа"),
+ ("RelationTools", "relations", "Связи между объектами"),
+ ("MessengerTools", "chats", "Чаты"),
+ ("SettingsTools", "settings", "Настройки"),
+ ("ReportTools", "reports", "Отчёты"),
+ ("AdminTools", "admin", "Администрирование (пользователь, настройки)"),
+ ("MetadataAdminTools", "metadata", "Метаданные и автоматизации"),
+ ("TaskTools", "tasks", "Задачи"),
+ ("SignatureTools", "signatures", "Подписи"),
+ ("CommandTools", "commands", "Команды сервера"),
+};
+
+var writeTools = FindWriteTools(Path.Combine(root, "Tools"));
+
+var tools = new List();
+foreach (var type in typeof(PilotConnection).Assembly.GetTypes().Where(t => t.GetCustomAttribute() != null))
+{
+ var (slug, title) = groupMap.Where(g => g.Class == type.Name).Select(g => (g.Slug, g.Title)).FirstOrDefault();
+ if (slug == null) (slug, title) = (type.Name.ToLowerInvariant(), type.Name);
+ foreach (var m in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
+ {
+ var attr = m.GetCustomAttribute();
+ if (attr == null) continue;
+ var name = attr.Name ?? m.Name;
+ var ps = m.GetParameters().Select(p => new Param(
+ p.Name!, TypeName(p.ParameterType), !p.HasDefaultValue,
+ p.HasDefaultValue ? DefaultText(p.DefaultValue) : "",
+ p.GetCustomAttribute()?.Description ?? "")).ToList();
+ // Метод в Tools/*.cs ищется по имени C#-метода, а не по имени инструмента
+ var isWrite = writeTools.TryGetValue(type.Name + "." + m.Name, out var w)
+ ? w
+ : throw new InvalidOperationException($"Не найден исходный код метода {type.Name}.{m.Name} в Tools/*.cs");
+ tools.Add(new Tool(name, type.Name, slug, title,
+ m.GetCustomAttribute()?.Description ?? "", ps, isWrite));
+ }
+}
+
+var dup = tools.GroupBy(t => t.Name).FirstOrDefault(g => g.Count() > 1);
+if (dup != null) Fail($"Повторяющееся имя инструмента: {dup.Key}");
+
+// Сверка с README: список заблокированных в режиме PILOT_READONLY должен совпадать с найденными инструментами записи
+var readme = File.ReadAllText(Path.Combine(root, "README.md"));
+var blockedLine = readme.Split('\n').FirstOrDefault(l => l.StartsWith("Заблокированы:", StringComparison.Ordinal))
+ ?? throw new InvalidOperationException("В README.md не найдена строка «Заблокированы:».");
+var blocked = Regex.Matches(blockedLine, "`([^`]+)`").Select(m => m.Groups[1].Value).ToHashSet(StringComparer.Ordinal);
+var found = tools.Where(t => t.IsWrite).Select(t => t.Name).ToHashSet(StringComparer.Ordinal);
+var onlyCode = found.Except(blocked).OrderBy(x => x, StringComparer.Ordinal).ToList();
+var onlyReadme = blocked.Except(found).OrderBy(x => x, StringComparer.Ordinal).ToList();
+if (onlyCode.Count > 0 || onlyReadme.Count > 0)
+ Fail("Список записи расходится с README.md (PILOT_READONLY).\n" +
+ $" Пишут в коде, но нет в README: {string.Join(", ", onlyCode)}\n" +
+ $" Есть в README, но не пишут в коде: {string.Join(", ", onlyReadme)}");
+
+// Страницы
+Directory.CreateDirectory(outDir);
+foreach (var f in Directory.EnumerateFiles(outDir)) File.Delete(f);
+
+var groups = tools
+ .GroupBy(t => t.Slug)
+ .OrderBy(g => GroupOrder(g.Key)).ThenBy(g => g.Key, StringComparer.Ordinal)
+ .ToList();
+
+foreach (var g in groups)
+{
+ var sb = new StringBuilder();
+ sb.Append($"# {g.First().Title}\n\n");
+ foreach (var t in g.OrderBy(t => t.Name, StringComparer.Ordinal))
+ {
+ sb.Append($"## {t.Name}\n\n");
+ sb.Append(t.IsWrite
+ ? "**Запись.** Блокируется режимом `PILOT_READONLY`.\n\n"
+ : "**Чтение.**\n\n");
+ sb.Append(Esc(t.Description)).Append("\n\n");
+ if (t.Params.Count == 0)
+ {
+ sb.Append("Параметров нет.\n\n");
+ continue;
+ }
+ sb.Append("| Параметр | Тип | Обязательный | По умолчанию | Описание |\n| --- | --- | --- | --- | --- |\n");
+ foreach (var p in t.Params)
+ sb.Append($"| `{p.Name}` | `{p.Type}` | {(p.Required ? "да" : "нет")} | {(p.Required ? "" : $"`{p.Default}`")} | {Esc(p.Description)} |\n");
+ sb.Append('\n');
+ }
+ Write(g.Key + ".md", sb.ToString());
+}
+
+var idx = new StringBuilder();
+idx.Append("# Справочник инструментов\n\n");
+idx.Append($"Всего инструментов: {tools.Count}, из них записывающих: {tools.Count(t => t.IsWrite)}. ");
+idx.Append("Записывающие инструменты блокируются режимом `PILOT_READONLY` (см. [Конфигурация](../configuration.md)). ");
+idx.Append("Страницы справочника сформированы автоматически по коду сервера.\n\n");
+idx.Append("| Инструмент | Группа | Тип | Описание |\n| --- | --- | --- | --- |\n");
+foreach (var g in groups)
+ foreach (var t in g.OrderBy(t => t.Name, StringComparer.Ordinal))
+ idx.Append($"| [`{t.Name}`]({g.Key}.md#{t.Name.ToLowerInvariant()}) | {t.Title} | {(t.IsWrite ? "запись" : "чтение")} | {Esc(Short(t.Description))} |\n");
+Write("index.md", idx.ToString());
+
+var toc = new StringBuilder("- name: Все инструменты\n href: index.md\n");
+foreach (var g in groups)
+ toc.Append($"- name: \"{g.First().Title}\"\n href: {g.Key}.md\n");
+Write("toc.yml", toc.ToString());
+
+Console.WriteLine($"DocGen: {tools.Count} инструментов ({found.Count} записывающих), {groups.Count} групп -> {outDir}");
+return 0;
+
+void Write(string file, string text) =>
+ File.WriteAllText(Path.Combine(outDir, file), text, new UTF8Encoding(false));
+
+static void Fail(string message)
+{
+ Console.Error.WriteLine("DocGen: " + message);
+ Environment.Exit(1);
+}
+
+int GroupOrder(string slug)
+{
+ var i = Array.FindIndex(groupMap, g => g.Slug == slug);
+ return i < 0 ? int.MaxValue : i;
+}
+
+static string FindRoot()
+{
+ for (var d = new DirectoryInfo(AppContext.BaseDirectory); d != null; d = d.Parent)
+ if (File.Exists(Path.Combine(d.FullName, "PilotMCP.slnx"))) return d.FullName;
+ throw new InvalidOperationException("Не найден корень репозитория (PilotMCP.slnx).");
+}
+
+// "Класс.Метод" -> вызывает ли тело ToolRunner.RunWrite/RunWriteAsync.
+// Тело метода = текст от его [McpServerTool] до следующего [McpServerTool] / [McpServerToolType] / конца файла.
+static Dictionary FindWriteTools(string toolsDir)
+{
+ var result = new Dictionary(StringComparer.Ordinal);
+ foreach (var file in Directory.EnumerateFiles(toolsDir, "*.cs").OrderBy(f => f, StringComparer.Ordinal))
+ {
+ var text = File.ReadAllText(file);
+ var classes = Regex.Matches(text, @"^public\s+(?:static\s+)?class\s+(\w+)", RegexOptions.Multiline);
+ var attrs = Regex.Matches(text, @"\[McpServerTool\b(?!Type)");
+ var ends = Regex.Matches(text, @"\[McpServerToolType\]").Select(m => m.Index)
+ .Concat(attrs.Select(m => m.Index)).Append(text.Length).Order().ToList();
+ foreach (Match a in attrs)
+ {
+ var end = ends.First(e => e > a.Index);
+ var segment = text.Substring(a.Index, end - a.Index);
+ var m = Regex.Match(segment, @"^\s*public\s+[^\r\n=]*?\b(\w+)\s*(?:<[^>\r\n]*>)?\(", RegexOptions.Multiline);
+ if (!m.Success) throw new InvalidOperationException($"Не найдена сигнатура метода после [McpServerTool] в {file}");
+ var cls = classes.Cast().Last(c => c.Index < a.Index).Groups[1].Value;
+ result[cls + "." + m.Groups[1].Value] = Regex.IsMatch(segment, @"ToolRunner\.RunWrite(Async)?\(");
+ }
+ }
+ return result;
+}
+
+static string TypeName(Type t)
+{
+ if (Nullable.GetUnderlyingType(t) is { } u) return TypeName(u) + "?";
+ if (t.IsArray) return TypeName(t.GetElementType()!) + "[]";
+ if (t.IsGenericType)
+ return t.Name[..t.Name.IndexOf('`')] + "<" + string.Join(", ", t.GetGenericArguments().Select(TypeName)) + ">";
+ return t == typeof(string) ? "string" : t == typeof(int) ? "int" : t == typeof(long) ? "long"
+ : t == typeof(bool) ? "bool" : t == typeof(double) ? "double" : t == typeof(float) ? "float"
+ : t == typeof(decimal) ? "decimal" : t == typeof(object) ? "object" : t.Name;
+}
+
+static string DefaultText(object? v) => v switch
+{
+ null => "null",
+ string s => "\"" + s + "\"",
+ bool b => b ? "true" : "false",
+ IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
+ _ => v.ToString() ?? "null"
+};
+
+// Первое предложение описания, не длиннее 160 символов
+static string Short(string d)
+{
+ var m = Regex.Match(d, @"^.*?(?:\.(?=\s)|$)", RegexOptions.Singleline);
+ var s = m.Value.Trim();
+ return s.Length > 160 ? s[..159].TrimEnd() + "…" : s;
+}
+
+static string Esc(string s) =>
+ Regex.Replace(s.Replace("\r", "").Replace("\n", " "), @"([\\`*_<>|\[\]])", @"\$1");
+
+sealed record Param(string Name, string Type, bool Required, string Default, string Description);
+sealed record Tool(string Name, string Class, string Slug, string Title, string Description, List Params, bool IsWrite);
diff --git a/DocumentParsing/MarkupBuilder.cs b/DocumentParsing/MarkupBuilder.cs
new file mode 100644
index 0000000..487590f
--- /dev/null
+++ b/DocumentParsing/MarkupBuilder.cs
@@ -0,0 +1,221 @@
+using Ascon.Pilot.DataClasses.Markups;
+using Ascon.Pilot.DataClasses.Markups.Primitives;
+using System.Globalization;
+using System.Text.RegularExpressions;
+
+namespace PilotMCP;
+
+/// Описание одной фигуры замечания. Координаты и размеры — в пикселях изображения GetDocumentPageImage.
+public class ShapeSpec
+{
+ public string Shape { get; set; } = "";
+ public double X { get; set; }
+ public double Y { get; set; }
+ public double Width { get; set; } = 100;
+ public double Height { get; set; } = 60;
+ public int Page { get; set; }
+ public string Color { get; set; } = "red";
+ public double StrokeWidth { get; set; } = 2;
+ public string Points { get; set; } = "";
+ public bool Cloud { get; set; }
+ public string StartEnding { get; set; } = "";
+ public string EndEnding { get; set; } = "";
+}
+
+///
+/// Строит Markup-объекты Pilot (формат замечаний клиента 26.20+) из фигур в пикселях верхне-левой системы координат.
+/// Единицы Markup — пункты PDF (DIP * 72/96), ось Y направлена вверх от низа страницы, Markup.Page считается с 1.
+///
+public static class MarkupBuilder
+{
+ private const double PtPerDip = 72.0 / 96.0;
+ // Squiggly намеренно нет: список замечаний клиента 26.20 (MarkupListItem.ToCommandType) падает на нём
+ // с "Unknown MarkupSubtype: Squiggly"; интерфейс клиента сам создаёт только эти три вида.
+ public static readonly Dictionary TextDecorationKinds = new()
+ {
+ ["highlight"] = MarkupTextDecorationKind.Highlight,
+ ["underline"] = MarkupTextDecorationKind.Underline,
+ ["strikeout"] = MarkupTextDecorationKind.StrikeOut
+ };
+
+ private const float StickerSize = 24; // размер стикера-точки, как в AnnotationsHelper.CreateMarkupAnnotation клиента
+
+ /// Фигура → Markup. Некорректные данные — ArgumentException.
+ public static Markup Build(int id, ShapeSpec s, double dpi, double pageHeightDip)
+ {
+ Validate(s);
+ var k = 96.0 / dpi; // пиксели → DIP
+ float X(double px) => (float)(px * k * PtPerDip);
+ float Y(double px) => (float)((pageHeightDip - px * k) * PtPerDip); // сверху вниз → снизу вверх
+ float L(double px) => (float)(px * k * PtPerDip);
+ MarkupPoint P(double px, double py) => new(X(px), Y(py));
+
+ var shape = s.Shape.Trim().ToLowerInvariant();
+ var page = s.Page + 1;
+ var style = BuildStyle(s);
+
+ if (s.Cloud && shape is not ("polyline" or "polygon"))
+ throw new ArgumentException("cloud применим только к polyline и polygon.");
+ var hasEndings = s.StartEnding != "" || s.EndEnding != "";
+ if (hasEndings && shape is not ("arrow" or "line"))
+ throw new ArgumentException("startEnding/endEnding применимы только к arrow и line.");
+
+ var border = s.Cloud ? BorderEffect.Cloud : BorderEffect.None;
+
+ // Прямоугольник клиент хранит как Y = верхний край (ось вверх) и ОТРИЦАТЕЛЬНУЮ высоту:
+ // RectangleMarkupGeometryConverter.ToCompactMarkup (BottomRight.Y после переворота меньше TopLeft.Y).
+ MarkupRect Rect() => new(X(s.X), Y(s.Y), L(s.Width), -L(s.Height));
+
+ if (shape is "rectangle" or "rect" or "ellipse" or "circle" or "triangle" && (s.Width <= 0 || s.Height <= 0))
+ throw new ArgumentException($"Для {shape} width и height должны быть больше 0.");
+
+ switch (shape)
+ {
+ case "rectangle" or "rect":
+ return new RectangleMarkup(id, page, Rect(), style);
+ case "ellipse" or "circle": // (x, y) = центр; радиусы положительные
+ return new EllipseMarkup(id, page, P(s.X, s.Y), L(s.Width) / 2, L(s.Height) / 2, style);
+ case "triangle":
+ return new PolygonMarkup(id, page, new[]
+ {
+ P(s.X, s.Y + s.Height), P(s.X + s.Width / 2, s.Y), P(s.X + s.Width, s.Y + s.Height)
+ }, style);
+ case "arrow" or "line":
+ {
+ // (x, y) = остриё, хвост = (x+width, y+height). Клиент ставит OpenArrow на конец линии (End):
+ // LineGeometryConverter.ToCompactMarkup.
+ var start = ParseEnding(s.StartEnding, MarkupLineEndings.None);
+ var end = ParseEnding(s.EndEnding, shape == "arrow" ? MarkupLineEndings.OpenArrow : MarkupLineEndings.None);
+ return new LineMarkup(id, page, P(s.X + s.Width, s.Y + s.Height), P(s.X, s.Y), start, end, style);
+ }
+ case "polyline":
+ return new PolylineMarkup(id, page, ParsePoints(s.Points, 2, P), style, border);
+ case "polygon":
+ return new PolygonMarkup(id, page, ParsePoints(s.Points, 3, P), style, border);
+ case "ink":
+ return new InkMarkup(id, page, ParsePoints(s.Points, 2, P), style);
+ case "point" or "textnote":
+ // Стикер: X, Y = левый верхний угол (ось вверх), размер 24x24 — как CreateNewMarkupForPoint клиента.
+ return new TextMarkup(id, page, new MarkupRect(X(s.X), Y(s.Y), StickerSize, StickerSize), style);
+ default:
+ throw new ArgumentException(
+ $"Неизвестная фигура: {s.Shape}. Используйте: rectangle, ellipse, triangle, arrow, line, polyline, polygon, ink, point");
+ }
+ }
+
+ ///
+ /// Выделение текста: одна строка (четырёхугольник) в DIP, верхне-левая система координат.
+ /// Вершины строго TL, TR, BR, BL в системе с осью вверх (у TL Y больше) — так их пишет клиент
+ /// (GetSelectionQuads) и читает TextDecorationMarkupGeometryConverter.
+ ///
+ public static Markup TextDecoration(int id, int page, double xDip, double topDip, double widthDip, double heightDip,
+ string kind, string color, double pageHeightDip)
+ {
+ if (!TextDecorationKinds.TryGetValue(kind.Trim().ToLowerInvariant(), out var decoration))
+ throw new ArgumentException($"Неизвестный стиль: {kind}. Используйте: {string.Join(", ", TextDecorationKinds.Keys)}");
+ MarkupPoint P(double x, double y) => new((float)(x * PtPerDip), (float)((pageHeightDip - y) * PtPerDip));
+ var quad = new[]
+ {
+ P(xDip, topDip), P(xDip + widthDip, topDip), P(xDip + widthDip, topDip + heightDip), P(xDip, topDip + heightDip)
+ };
+ // Клиент создаёт выделение текста с LineStyle = Solid и толщиной 2 (AnnotationManager.CreateNewMarkupForText).
+ var style = new MarkupStyle(ParseColor(color), 2, null, MarkupLineStyle.Solid);
+ return new TextDecorationMarkup(id, page + 1, quad, decoration, style);
+ }
+
+ /// Ключевые точки фигуры в единицах Markup — по ним считается ограничивающий прямоугольник.
+ public static IEnumerable Outline(Markup m) => m switch
+ {
+ RectangleMarkup r => Corners(r.Bounds),
+ FreeTextMarkup f => Corners(f.Bounds),
+ TextMarkup t => Corners(t.Bounds),
+ EllipseMarkup e => Corners(e.GetBounds()),
+ LineMarkup l => new[] { l.Start, l.End },
+ PolylineMarkup p => p.Points,
+ PolygonMarkup p => p.Points,
+ InkMarkup i => i.Points.Where(p => !float.IsNaN(p.X) && !float.IsNaN(p.Y)),
+ TextDecorationMarkup d => d.QuadPoints,
+ _ => Array.Empty()
+ };
+
+ private static MarkupPoint[] Corners(MarkupRect r) => new MarkupPoint[] { new(r.X, r.Y), new(r.Right, r.Bottom) };
+
+ ///
+ /// Цвет → int для MarkupStyle. Непрозрачный цвет хранится как 0xRRGGBB (так делает клиент),
+ /// кроме чёрного: 0 клиент читает как полностью прозрачный, поэтому чёрный — 0xFF000000.
+ ///
+ public static int ParseColor(string color)
+ {
+ var c = color.Trim();
+ // ResolveColor молча подменяет неизвестное на красный; для Markup такое не допускаем:
+ // имя допустимо, если ResolveColor вернул не красный-по-умолчанию (или это сам "red").
+ var valid = Regex.IsMatch(c, "^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$")
+ || (!c.StartsWith('#') && (c.Equals("red", StringComparison.OrdinalIgnoreCase)
+ || AnnotationBuilder.ResolveColor(c) != "#FFFF0000"));
+ if (!valid)
+ throw new ArgumentException(
+ $"Неизвестный цвет: '{color}'. Используйте имя (red, green, blue, yellow, orange, purple, pink, black, white, gray, cyan, magenta) или #RRGGBB / #AARRGGBB.");
+ var argb = Convert.ToUInt32(AnnotationBuilder.ResolveColor(c)[1..], 16);
+ // клиент (ColorHelper.FromRgb) читает 0x00RRGGBB как непрозрачный — полностью прозрачный только 0
+ if ((argb >> 24) == 0) return 0;
+ if ((argb >> 24) != 0xFF) return unchecked((int)argb);
+ var rgb = (int)(argb & 0xFFFFFF);
+ return rgb == 0 ? unchecked((int)0xFF000000) : rgb;
+ }
+
+ /// Цвет из Markup-стиля → строка: "transparent" для 0, #AARRGGBB при ненулевой альфе, иначе #RRGGBB.
+ public static string FormatColor(int c)
+ => c == 0 ? "transparent" : (c >>> 24) != 0 ? $"#{(uint)c:X8}" : $"#{c:X6}";
+
+ // Заливки и стиль линии клиент не рисует, поэтому их нет: фон null, линия сплошная.
+ private static MarkupStyle BuildStyle(ShapeSpec s)
+ {
+ if (s.StrokeWidth <= 0)
+ throw new ArgumentException("strokeWidth должен быть больше 0.");
+ return new MarkupStyle(ParseColor(s.Color), (float)s.StrokeWidth, null, MarkupLineStyle.Solid);
+ }
+
+ /// null из JSON → значения по умолчанию, обязательное shape и конечные числа проверяются.
+ private static void Validate(ShapeSpec s)
+ {
+ if (string.IsNullOrWhiteSpace(s.Shape))
+ throw new ArgumentException("Поле shape обязательно.");
+ s.Color ??= "red";
+ s.Points ??= "";
+ s.StartEnding ??= "";
+ s.EndEnding ??= "";
+ foreach (var (name, v) in new[] { ("x", s.X), ("y", s.Y), ("width", s.Width), ("height", s.Height), ("strokeWidth", s.StrokeWidth) })
+ if (!double.IsFinite(v))
+ throw new ArgumentException($"Поле {name} должно быть конечным числом.");
+ }
+
+ // Клиент (LineEnding.GetMarkupLineEndings) отрисовывает только None и OpenArrow.
+ private static MarkupLineEndings ParseEnding(string name, MarkupLineEndings fallback)
+ {
+ if (name == "") return fallback;
+ return name.Trim().ToLowerInvariant() switch
+ {
+ "none" => MarkupLineEndings.None,
+ "openarrow" => MarkupLineEndings.OpenArrow,
+ _ => throw new ArgumentException($"Неподдерживаемое окончание линии: {name}. Используйте: none, openarrow")
+ };
+ }
+
+ /// "x1,y1;x2,y2;..." (пиксели) → точки Markup.
+ private static MarkupPoint[] ParsePoints(string points, int min, Func convert)
+ {
+ var result = points.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(p =>
+ {
+ var xy = p.Split(',', StringSplitOptions.TrimEntries);
+ if (xy.Length != 2
+ || !double.TryParse(xy[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var x)
+ || !double.TryParse(xy[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var y)
+ || !double.IsFinite(x) || !double.IsFinite(y))
+ throw new ArgumentException($"Некорректная точка '{p}': ожидается 'x,y'.");
+ return convert(x, y);
+ }).ToArray();
+ if (result.Length < min)
+ throw new ArgumentException($"Нужно минимум {min} точек в points (формат 'x1,y1;x2,y2;...'), получено {result.Length}.");
+ return result;
+ }
+}
diff --git a/DocumentParsing/PageGeometry.cs b/DocumentParsing/PageGeometry.cs
new file mode 100644
index 0000000..6debcfe
--- /dev/null
+++ b/DocumentParsing/PageGeometry.cs
@@ -0,0 +1,30 @@
+namespace PilotMCP;
+
+///
+/// Размеры страниц документа в DIP (1/96") — в тех же единицах, в которых GetDocumentPageImage
+/// рендерит страницу (XPS: FixedPage Width/Height, PDF: размер страницы PdfPig * 96/72).
+///
+public static class PageGeometry
+{
+ /// Размеры запрошенных страниц (индекс с 0). Страницы вне документа в результат не попадают.
+ public static Dictionary Load(string path, string ext, IEnumerable pages)
+ {
+ var result = new Dictionary();
+ if (ext == ".pdf")
+ {
+ using var pdf = UglyToad.PdfPig.PdfDocument.Open(path);
+ foreach (var page in pages.Distinct().Where(p => p >= 0 && p < pdf.NumberOfPages))
+ {
+ var pg = pdf.GetPage(page + 1);
+ result[page] = (pg.Width * 96.0 / 72.0, pg.Height * 96.0 / 72.0);
+ }
+ }
+ else
+ {
+ var sizes = XpsTextExtractor.GetPageSizes(path);
+ foreach (var page in pages.Distinct().Where(p => p >= 0 && p < sizes.Count))
+ result[page] = sizes[page];
+ }
+ return result;
+ }
+}
diff --git a/DocumentParsing/PdfTextExtractor.cs b/DocumentParsing/PdfTextExtractor.cs
index ee20bf4..2e1c10e 100644
--- a/DocumentParsing/PdfTextExtractor.cs
+++ b/DocumentParsing/PdfTextExtractor.cs
@@ -64,6 +64,9 @@ public static class PdfTextExtractor
///
public static List FindText(string pdfPath, string searchText)
{
+ if (string.IsNullOrEmpty(searchText))
+ throw new ArgumentException("Текст для поиска не может быть пустым.", nameof(searchText));
+
var found = new List();
using var document = PdfDocument.Open(pdfPath);
@@ -87,6 +90,11 @@ public static class PdfTextExtractor
// Собираем текст строки и индексы букв
var lineText = string.Join("", sortedLetters.Select(l => l.Value));
+ // Value буквы может быть длиннее одного символа (лигатура "fi", суррогатная пара):
+ // индекс символа строки -> индекс буквы
+ var charToLetter = new List(lineText.Length);
+ for (int li = 0; li < sortedLetters.Count; li++)
+ charToLetter.AddRange(Enumerable.Repeat(li, sortedLetters[li].Value.Length));
// Ищем все вхождения в строке
int startIdx = 0;
@@ -96,9 +104,8 @@ public static class PdfTextExtractor
if (idx < 0) break;
// Вычисляем координаты из позиций букв
- var firstLetter = sortedLetters[idx];
- var lastLetterIdx = Math.Min(idx + searchText.Length - 1, sortedLetters.Count - 1);
- var lastLetter = sortedLetters[lastLetterIdx];
+ var firstLetter = sortedLetters[charToLetter[idx]];
+ var lastLetter = sortedLetters[charToLetter[idx + searchText.Length - 1]];
var x = firstLetter.Location.X;
var matchWidth = (lastLetter.Location.X + lastLetter.Width) - firstLetter.Location.X;
diff --git a/DocumentParsing/XpsTextExtractor.cs b/DocumentParsing/XpsTextExtractor.cs
index 65112c8..34d47b6 100644
--- a/DocumentParsing/XpsTextExtractor.cs
+++ b/DocumentParsing/XpsTextExtractor.cs
@@ -1,7 +1,9 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
+using System.Text.RegularExpressions;
using System.Xml.Linq;
+using SkiaSharp;
namespace PilotMCP;
@@ -14,7 +16,7 @@ public static class XpsTextExtractor
private static readonly XNamespace XpsNs = "http://schemas.microsoft.com/xps/2005/06";
private static readonly XNamespace OpenXpsNs = "http://schemas.openxps.org/oxps/v1.0";
- public record TextBlock(string Text, double X, double Y, double Width, double FontSize, int Page, double[]? Advances = null);
+ public record TextBlock(string Text, double X, double Y, double Width, double FontSize, int Page, double[]? Advances = null, double[]? NaturalAdvances = null);
///
/// Извлекает все текстовые блоки из XPS-файла.
@@ -27,42 +29,67 @@ public static List ExtractText(string xpsPath)
using var zip = ZipFile.OpenRead(xpsPath);
var pageXmls = LoadFixedPages(zip);
+ using var fonts = new FontCache(zip);
for (int pageIdx = 0; pageIdx < pageXmls.Count; pageIdx++)
{
- var doc = pageXmls[pageIdx];
+ var (pagePath, doc) = pageXmls[pageIdx];
if (doc.Root == null) continue;
var ns = doc.Root.Name.Namespace;
- ExtractGlyphsFromElement(doc.Root, ns, pageIdx, result);
+ ExtractGlyphsFromElement(doc.Root, ns, pageIdx, result, pagePath, fonts);
}
return result;
}
///
- /// Загружает FixedPage XML из XPS-архива.
- /// Поддерживает два формата:
- /// 1) Обычный: Documents/1/Pages/1.fpage (один файл = одна страница)
- /// 2) Interleaved (piece): Documents/1/Pages/1.fpage/[0].piece, [1].last.piece
- /// (страница разбита на куски, которые нужно склеить)
+ /// Размеры страниц (ширина, высота) в DIP (1/96") из атрибутов FixedPage — по индексу страницы с 0.
///
- private static List LoadFixedPages(ZipArchive zip)
+ public static List<(double Width, double Height)> GetPageSizes(string xpsPath)
{
- // Сначала пробуем обычный формат
+ using var zip = ZipFile.OpenRead(xpsPath);
+ return LoadFixedPages(zip).Select((p, i) =>
+ {
+ var d = p.Doc;
+ var w = ParseDouble(d.Root?.Attribute("Width")?.Value);
+ var h = ParseDouble(d.Root?.Attribute("Height")?.Value);
+ if (w <= 0 || h <= 0)
+ throw new InvalidDataException($"Страница {i}: у FixedPage нет корректных Width/Height.");
+ return (w, h);
+ }).ToList();
+ }
+
+ // Числа в имени сравниваем как числа: "10.fpage" идёт после "2.fpage", а не перед ним.
+ private static string NumericKey(string name)
+ => Regex.Replace(name, @"\d+", m => m.Value.PadLeft(10, '0'));
+
+ ///
+ /// Загружает FixedPage XML из XPS-архива в порядке документа: _rels/.rels → FixedDocumentSequence →
+ /// FixedDocument → PageContent (так же нумерует страницы рендерер MuPDF в GetDocumentPageImage).
+ /// Части могут лежать целиком (Pages/1.fpage) или кусками (Pages/1.fpage/[0].piece, [1].last.piece).
+ ///
+ private static List<(string Path, XDocument Doc)> LoadFixedPages(ZipArchive zip)
+ {
+ var budget = new ReadBudget(MaxTotalBytes);
+ var order = PageOrder(zip, budget);
+ if (order != null)
+ return order.Select(p => (p, XDocument.Parse(ReadPart(zip, p, budget)
+ ?? throw new InvalidDataException($"В XPS нет страницы '{p}', указанной в FixedDocument.")))).ToList();
+
+ // shortcut: пакет без FixedDocumentSequence (нестандартный) — порядок по номерам в именах файлов
var directPages = zip.Entries
.Where(e => e.FullName.EndsWith(".fpage", StringComparison.OrdinalIgnoreCase))
- .OrderBy(e => e.FullName)
+ .OrderBy(e => NumericKey(e.FullName))
.ToList();
if (directPages.Count > 0)
{
- var docs = new List();
+ if (directPages.Count > MaxPages)
+ throw new InvalidDataException($"В XPS больше {MaxPages} страниц.");
+ var docs = new List<(string, XDocument)>();
foreach (var entry in directPages)
- {
- using var stream = entry.Open();
- docs.Add(XDocument.Load(stream));
- }
+ docs.Add((entry.FullName, XDocument.Parse(DecodeText(ReadEntries(new[] { entry }, entry.FullName, MaxPartBytes, budget)))));
return docs;
}
@@ -75,66 +102,169 @@ private static List LoadFixedPages(ZipArchive zip)
var idx = e.FullName.IndexOf(".fpage/", StringComparison.OrdinalIgnoreCase);
return e.FullName[..(idx + 6)]; // "Documents/1/Pages/1.fpage"
})
- .OrderBy(g => g.Key)
+ .OrderBy(g => NumericKey(g.Key))
.ToList();
- var result = new List();
+ if (pieceGroups.Count > MaxPages)
+ throw new InvalidDataException($"В XPS больше {MaxPages} страниц.");
+ var result = new List<(string, XDocument)>();
foreach (var group in pieceGroups)
{
- var sb = new StringBuilder();
- foreach (var piece in group.OrderBy(e => e.FullName))
- {
- using var stream = piece.Open();
- using var reader = new StreamReader(stream);
- sb.Append(reader.ReadToEnd());
- }
- var xml = sb.ToString();
+ var xml = DecodeText(ReadEntries(group.OrderBy(e => NumericKey(e.FullName)), group.Key, MaxPartBytes, budget));
if (!string.IsNullOrWhiteSpace(xml))
- result.Add(XDocument.Parse(xml));
+ result.Add((group.Key, XDocument.Parse(xml)));
}
return result;
}
+ /// Пути страниц в порядке FixedDocumentSequence; null, если в пакете нет последовательности.
+ private static List? PageOrder(ZipArchive zip, ReadBudget budget)
+ {
+ var rels = ReadPart(zip, "_rels/.rels", budget);
+ var seqTarget = rels == null ? null : XDocument.Parse(rels).Root?.Elements()
+ .FirstOrDefault(r => ((string?)r.Attribute("Type"))?.EndsWith("/fixedrepresentation", StringComparison.OrdinalIgnoreCase) == true)
+ ?.Attribute("Target")?.Value;
+ if (seqTarget == null) return null;
+ var seqPath = ResolvePart("", seqTarget);
+ var seq = ReadPart(zip, seqPath, budget);
+ if (seq == null) return null;
+
+ var pages = new List();
+ foreach (var docRef in XDocument.Parse(seq).Root!.Elements().Where(e => e.Name.LocalName == "DocumentReference"))
+ {
+ var docPath = ResolvePart(seqPath, (string)docRef.Attribute("Source")!);
+ var doc = ReadPart(zip, docPath, budget)
+ ?? throw new InvalidDataException($"В XPS нет FixedDocument '{docPath}'.");
+ pages.AddRange(XDocument.Parse(doc).Root!.Elements().Where(e => e.Name.LocalName == "PageContent")
+ .Select(pc => ResolvePart(docPath, (string)pc.Attribute("Source")!)));
+ // повторные ссылки на одну страницу легальны (MuPDF покажет обе), поэтому ограничиваем число, а не дубли
+ if (pages.Count > MaxPages)
+ throw new InvalidDataException($"В XPS больше {MaxPages} страниц.");
+ }
+ return pages;
+ }
+
+ // XPS приходит из базы Pilot (загрузить его может любой пользователь) — ограничиваем распаковку против zip-бомб.
+ private const long MaxPartBytes = 64L << 20; // одна часть (страница, FixedDocument и т.п.)
+ private const long MaxTotalBytes = 512L << 20; // все XML-части одного извлечения
+ private const long MaxFontBytes = 32L << 20; // один шрифт
+ private const long MaxFontsTotalBytes = 128L << 20;
+ private const int MaxPages = 10_000;
+
+ private sealed class ReadBudget(long bytes) { public long Remaining = bytes; }
+
+ /// Распаковывает записи подряд, не больше maxBytes на часть и не больше остатка бюджета.
+ private static byte[] ReadEntries(IEnumerable entries, string name, long maxBytes, ReadBudget budget)
+ {
+ using var ms = new MemoryStream();
+ var buffer = new byte[81920];
+ foreach (var entry in entries)
+ {
+ using var s = entry.Open();
+ int n;
+ while ((n = s.Read(buffer, 0, buffer.Length)) > 0)
+ {
+ if (ms.Length + n > maxBytes || n > budget.Remaining)
+ throw new InvalidDataException($"Часть XPS '{name}' после распаковки превышает допустимый размер.");
+ budget.Remaining -= n;
+ ms.Write(buffer, 0, n);
+ }
+ }
+ return ms.ToArray();
+ }
+
+ /// Текст части с определением кодировки по BOM (XPS допускает UTF-8 и UTF-16).
+ private static string DecodeText(byte[] bytes)
+ {
+ using var reader = new StreamReader(new MemoryStream(bytes), Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
+ return reader.ReadToEnd();
+ }
+
+ /// Ссылка Source (абсолютная или относительно части basePart) → имя записи в ZIP.
+ private static string ResolvePart(string basePart, string source)
+ => Uri.UnescapeDataString(new Uri(new Uri("http://xps/" + basePart), source).AbsolutePath).TrimStart('/');
+
+ /// Записи ZIP части пакета: одна целая или упорядоченные куски [N].piece; пусто, если части нет.
+ private static ZipArchiveEntry[] PartEntries(ZipArchive zip, string name)
+ {
+ var direct = zip.Entries.FirstOrDefault(e => e.FullName.Equals(name, StringComparison.OrdinalIgnoreCase));
+ return direct != null
+ ? new[] { direct }
+ : zip.Entries
+ .Where(e => e.FullName.StartsWith(name + "/", StringComparison.OrdinalIgnoreCase)
+ && e.FullName.EndsWith(".piece", StringComparison.OrdinalIgnoreCase))
+ .OrderBy(e => int.Parse(Regex.Match(e.Name, @"^\[(\d+)\]").Groups[1].Value))
+ .ToArray();
+ }
+
+ /// Содержимое части пакета: целиком или склеенное из кусков [N].piece; null, если части нет.
+ private static string? ReadPart(ZipArchive zip, string name, ReadBudget budget)
+ {
+ var parts = PartEntries(zip, name);
+ // куски склеиваются по байтам: граница [N].piece может разрезать многобайтовый символ
+ return parts.Length == 0 ? null : DecodeText(ReadEntries(parts, name, MaxPartBytes, budget));
+ }
+
+ /// Число страниц XPS (по FixedDocument, как нумерует рендерер).
+ public static int GetPageCount(string xpsPath)
+ {
+ using var zip = ZipFile.OpenRead(xpsPath);
+ return LoadFixedPages(zip).Count;
+ }
+
+ /// Смещение по X границы n-го символа внутри блока (по Advances, иначе поровну).
+ private static double OffsetIn(TextBlock block, int n)
+ {
+ if (block.Advances != null && block.Advances.Length >= block.Text.Length)
+ return block.Advances.Take(n).Sum();
+ return n * block.Width / Math.Max(block.Text.Length, 1);
+ }
+
+ ///
+ /// Смещение правой границы символа n-1 (конец совпадения, n символов от начала блока). Advance последнего
+ /// глифа в Indices может включать зазор до следующей колонки: берём не больше натурального из шрифта.
+ ///
+ private static double EndOffsetIn(TextBlock block, int n)
+ {
+ if (n < 1 || block.Advances == null || block.Advances.Length < block.Text.Length)
+ return OffsetIn(block, n);
+ var last = block.Advances[n - 1];
+ var natural = block.NaturalAdvances is { } na && na.Length >= n ? na[n - 1] : 0;
+ if (natural > 0 && natural < last) last = natural;
+ return OffsetIn(block, n - 1) + last;
+ }
+
///
/// Ищет текст в XPS-файле и возвращает координаты всех вхождений.
+ /// Единицы координат — 1/96 дюйма (FixedPage), Y — верх текста сверху вниз.
///
public static List FindText(string xpsPath, string searchText)
{
+ if (string.IsNullOrEmpty(searchText))
+ throw new ArgumentException("Текст для поиска не может быть пустым.", nameof(searchText));
+
var allBlocks = ExtractText(xpsPath);
var found = new List();
- // Exact match in individual blocks — compute precise offset using per-character advances
+ // Точные вхождения внутри блока (все, не только первое) — смещение по Advances
foreach (var block in allBlocks)
{
- var idx = block.Text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase);
- if (idx >= 0)
+ for (var start = 0; start <= block.Text.Length - searchText.Length;)
{
- double offsetX = 0;
- double matchWidth = 0;
- if (block.Advances != null && block.Advances.Length >= idx + searchText.Length)
- {
- for (int i = 0; i < idx; i++)
- offsetX += block.Advances[i];
- for (int i = idx; i < idx + searchText.Length; i++)
- matchWidth += block.Advances[i];
- }
- else
- {
- var charWidth = block.Width / Math.Max(block.Text.Length, 1);
- offsetX = idx * charWidth;
- matchWidth = searchText.Length * charWidth;
- }
+ var idx = block.Text.IndexOf(searchText, start, StringComparison.OrdinalIgnoreCase);
+ if (idx < 0) break;
+ var offsetX = OffsetIn(block, idx);
found.Add(block with
{
- Text = block.Text,
X = block.X + offsetX,
- Width = matchWidth
+ Width = EndOffsetIn(block, idx + searchText.Length) - offsetX
});
+ start = idx + searchText.Length;
}
}
- // If not found in individual blocks, try concatenating adjacent blocks on the same page/line
+ // Если в отдельных блоках не найдено — склеиваем соседние блоки одной строки
if (found.Count == 0)
{
found = FindInConcatenatedBlocks(allBlocks, searchText);
@@ -143,12 +273,14 @@ public static List FindText(string xpsPath, string searchText)
return found;
}
- private static void ExtractGlyphsFromElement(XElement element, XNamespace ns, int pageIdx, List result)
+ private static void ExtractGlyphsFromElement(XElement element, XNamespace ns, int pageIdx, List result, string pagePath, FontCache fonts)
{
// Process Glyphs elements
foreach (var glyph in element.Descendants(ns + "Glyphs"))
{
var text = glyph.Attribute("UnicodeString")?.Value;
+ // Префикс "{}" — escape-последовательность XPS, в текст не входит
+ if (text != null && text.StartsWith("{}", StringComparison.Ordinal)) text = text[2..];
if (string.IsNullOrEmpty(text)) continue;
var originX = ParseDouble(glyph.Attribute("OriginX")?.Value);
@@ -162,7 +294,7 @@ private static void ExtractGlyphsFromElement(XElement element, XNamespace ns, in
var cur = glyph;
while (cur != null && cur != element)
{
- var rt = cur.Attribute("RenderTransform")?.Value;
+ var rt = RenderTransformOf(cur);
if (!string.IsNullOrEmpty(rt))
chain.Add(ParseMatrix(rt));
cur = cur.Parent;
@@ -179,6 +311,9 @@ private static void ExtractGlyphsFromElement(XElement element, XNamespace ns, in
var indicesStr = glyph.Attribute("Indices")?.Value;
var advances = ParseAdvances(indicesStr, text.Length, fontSize, scaleX);
var totalWidth = advances.Sum();
+ var fontUri = glyph.Attribute("FontUri")?.Value;
+ var typeface = string.IsNullOrEmpty(fontUri) ? null : fonts.Get(ResolvePart(pagePath, fontUri));
+ var natural = typeface == null ? null : NaturalAdvances(typeface, indicesStr, text, fontSize, scaleX);
result.Add(new TextBlock(
Text: text,
@@ -187,11 +322,22 @@ private static void ExtractGlyphsFromElement(XElement element, XNamespace ns, in
Width: totalWidth,
FontSize: effectiveFontSize,
Page: pageIdx,
- Advances: advances
+ Advances: advances,
+ NaturalAdvances: natural
));
}
}
+ /// RenderTransform элемента: атрибут или свойство-элемент Element.RenderTransform/MatrixTransform@Matrix.
+ private static string? RenderTransformOf(XElement el)
+ {
+ var attr = el.Attribute("RenderTransform")?.Value;
+ if (!string.IsNullOrEmpty(attr)) return attr;
+ return el.Elements().FirstOrDefault(c => c.Name.LocalName == el.Name.LocalName + ".RenderTransform")
+ ?.Elements().FirstOrDefault(m => m.Name.LocalName == "MatrixTransform")
+ ?.Attribute("Matrix")?.Value;
+ }
+
///
/// Parses a RenderTransform string "a,b,c,d,e,f" into a matrix array [a,b,c,d,e,f].
/// Matrix transforms point (x,y) to: x' = a*x + c*y + e, y' = b*x + d*y + f
@@ -241,8 +387,9 @@ private static double ComputeScaleX(List chain)
///
/// Parses the Indices attribute to extract per-character advance widths in FixedPage coordinates.
- /// XPS Indices format: each entry separated by ';', advance is after the comma: "[cluster:]glyph,advance[,uOff,vOff]"
- /// Advance is in hundredths of FontRenderingEmSize.
+ /// XPS Indices format: entries separated by ';': "[(codeUnits:glyphs)]glyph,advance[,uOff,vOff]".
+ /// Advance is in hundredths of FontRenderingEmSize. Кластер "(n:m)" — n символов на m глифов
+ /// (m записей подряд): суммарная ширина делится поровну между его n символами.
///
private static double[] ParseAdvances(string? indices, int charCount, double fontSize, double scaleX)
{
@@ -256,85 +403,202 @@ private static double[] ParseAdvances(string? indices, int charCount, double fon
}
var entries = indices.Split(';');
- for (int i = 0; i < charCount; i++)
+ int e = 0, i = 0;
+ while (i < charCount)
+ {
+ if (e >= entries.Length) { advances[i++] = defaultAdvance; continue; }
+
+ var (codeUnits, glyphs) = ParseCluster(entries[e]);
+ double sum = 0;
+ for (int g = 0; g < glyphs && e + g < entries.Length; g++)
+ sum += EntryAdvance(entries[e + g], fontSize, scaleX) ?? defaultAdvance;
+ e += glyphs;
+
+ var n = Math.Min(codeUnits, charCount - i);
+ for (int k = 0; k < n; k++) advances[i + k] = sum / n;
+ i += n;
+ }
+
+ return advances;
+ }
+
+ ///
+ /// Натуральная ширина каждого символа из шрифта (FixedPage-единицы); 0 — неизвестна (кластеры, нет глифа).
+ /// Номер глифа берётся из Indices, а если его там нет — из cmap шрифта по символу.
+ ///
+ private static double[] NaturalAdvances(SKTypeface typeface, string? indices, string text, double fontSize, double scaleX)
+ {
+ var result = new double[text.Length];
+ var glyphIds = new ushort[text.Length];
+ var entries = string.IsNullOrEmpty(indices) ? Array.Empty() : indices.Split(';');
+ var fromCmap = typeface.GetGlyphs(text);
+ int e = 0, i = 0;
+ while (i < text.Length)
{
- if (i < entries.Length)
+ var (codeUnits, glyphs) = e < entries.Length ? ParseCluster(entries[e]) : (1, 1);
+ if (codeUnits == 1 && glyphs == 1)
+ glyphIds[i] = e < entries.Length && EntryGlyph(entries[e]) is { } g ? g : (i < fromCmap.Length ? fromCmap[i] : (ushort)0);
+ e += glyphs;
+ i += Math.Min(codeUnits, text.Length - i);
+ }
+ using var font = new SKFont(typeface, (float)fontSize) { Subpixel = true, LinearMetrics = true, Hinting = SKFontHinting.None };
+ var widths = font.GetGlyphWidths(glyphIds);
+ for (int k = 0; k < result.Length; k++)
+ if (glyphIds[k] != 0) result[k] = widths[k] * scaleX;
+ return result;
+ }
+
+ /// Номер глифа из записи "[(n:m)]glyph,advance..."; null — не задан.
+ private static ushort? EntryGlyph(string entry)
+ {
+ var close = entry.IndexOf(')');
+ if (entry.TrimStart().StartsWith('(') && close >= 0) entry = entry[(close + 1)..];
+ var comma = entry.IndexOf(',');
+ var head = (comma < 0 ? entry : entry[..comma]).Trim();
+ return ushort.TryParse(head, NumberStyles.None, CultureInfo.InvariantCulture, out var g) ? g : null;
+ }
+
+ /// Шрифты одного извлечения: грузятся по требованию, кэшируются по части, освобождаются в Dispose.
+ private sealed class FontCache(ZipArchive zip) : IDisposable
+ {
+ private readonly Dictionary _fonts = new(StringComparer.OrdinalIgnoreCase);
+ private readonly ReadBudget _fontBudget = new(MaxFontsTotalBytes);
+
+ public SKTypeface? Get(string part)
+ {
+ if (_fonts.TryGetValue(part, out var cached)) return cached;
+ SKTypeface? typeface = null;
+ try
{
- var entry = entries[i];
- // Entry format: [clusterMap:]glyphIndex,advanceWidth[,uOffset[,vOffset]]
- // Often just ",advanceWidth" (comma-prefixed, no glyph index)
- var commaIdx = entry.IndexOf(',');
- if (commaIdx >= 0)
- {
- // Get advance width (second comma-separated value, or first after leading comma)
- var afterComma = entry[(commaIdx + 1)..];
- var nextComma = afterComma.IndexOf(',');
- var advStr = nextComma >= 0 ? afterComma[..nextComma] : afterComma;
- var advRaw = ParseDouble(advStr);
- if (advRaw > 0)
- {
- // Advance is in hundredths of em size, convert to local units then scale
- advances[i] = advRaw / 100.0 * fontSize * scaleX;
- continue;
- }
- }
+ var entries = PartEntries(zip, part);
+ if (entries.Length == 0) throw new InvalidDataException("часть пакета не найдена");
+ var data = ReadEntries(entries, part, MaxFontBytes, _fontBudget);
+ if (part.EndsWith(".odttf", StringComparison.OrdinalIgnoreCase))
+ Deobfuscate(data, Path.GetFileNameWithoutExtension(part));
+ using var skData = SKData.CreateCopy(data);
+ typeface = SKTypeface.FromData(skData)
+ ?? throw new InvalidDataException("SkiaSharp не распознал шрифт");
+ }
+ catch (Exception ex)
+ {
+ Console.Error.WriteLine($"XPS: не удалось загрузить шрифт '{part}': {ex.Message}; ширина последнего глифа берётся из Indices.");
}
- advances[i] = defaultAdvance;
+ _fonts[part] = typeface;
+ return typeface;
}
- return advances;
+ public void Dispose()
+ {
+ foreach (var f in _fonts.Values) f?.Dispose();
+ _fonts.Clear();
+ }
+ }
+
+ ///
+ /// Снимает обфускацию .odttf (XPS 2.1.7): ключ — 16 байт GUID из имени файла в порядке записи hex-цифр
+ /// (без дефисов); первые 32 байта шрифта XOR ключ в обратном порядке (data[i], data[i+16] ^= key[15-i]).
+ /// Операция симметрична: повторный вызов обфусцирует обратно.
+ ///
+ internal static void Deobfuscate(byte[] data, string guidName)
+ {
+ var hex = guidName.Replace("-", "").Trim('{', '}');
+ if (hex.Length != 32 || !hex.All(Uri.IsHexDigit))
+ throw new InvalidDataException($"имя обфусцированного шрифта '{guidName}' не GUID");
+ if (data.Length < 32) throw new InvalidDataException("файл шрифта короче 32 байт");
+ var key = Convert.FromHexString(hex);
+ for (int i = 0; i < 16; i++)
+ {
+ data[i] ^= key[15 - i];
+ data[i + 16] ^= key[15 - i];
+ }
+ }
+
+ /// Префикс кластера "(codeUnits:glyphs)" записи Indices; без префикса — 1:1.
+ private static (int CodeUnits, int Glyphs) ParseCluster(string entry)
+ {
+ var m = Regex.Match(entry, @"^\s*\((\d+):(\d+)\)");
+ if (m.Success
+ && int.TryParse(m.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out var cu)
+ && int.TryParse(m.Groups[2].Value, NumberStyles.None, CultureInfo.InvariantCulture, out var gl)
+ && cu > 0 && gl > 0)
+ return (cu, gl);
+ return (1, 1);
+ }
+
+ /// Ширина глифа из записи "[(n:m)]glyph,advance[,u,v]" в координатах FixedPage; null — не задана.
+ private static double? EntryAdvance(string entry, double fontSize, double scaleX)
+ {
+ var close = entry.IndexOf(')');
+ if (entry.TrimStart().StartsWith('(') && close >= 0) entry = entry[(close + 1)..];
+ var commaIdx = entry.IndexOf(',');
+ if (commaIdx < 0) return null;
+ var afterComma = entry[(commaIdx + 1)..];
+ var nextComma = afterComma.IndexOf(',');
+ var advRaw = ParseDouble(nextComma >= 0 ? afterComma[..nextComma] : afterComma);
+ // Advance in hundredths of em size, converted to FixedPage units
+ return advRaw > 0 ? advRaw / 100.0 * fontSize * scaleX : null;
}
private static List FindInConcatenatedBlocks(List blocks, string searchText)
{
var found = new List();
- // Group by page and approximate Y position (same line = similar Y)
- var grouped = blocks
- .GroupBy(b => (b.Page, YLine: Math.Round(b.Y / 5) * 5))
- .OrderBy(g => g.Key.Page)
- .ThenBy(g => g.Key.YLine);
-
- foreach (var group in grouped)
+ foreach (var line in GroupIntoLines(blocks))
{
- var lineBlocks = group.OrderBy(b => b.X).ToList();
- var lineText = string.Join("", lineBlocks.Select(b => b.Text));
+ var lineText = string.Join("", line.Select(b => b.Text));
+ // Начало каждого блока в склеенной строке
+ var starts = new int[line.Count];
+ for (int i = 1; i < line.Count; i++) starts[i] = starts[i - 1] + line[i - 1].Text.Length;
- var idx = lineText.IndexOf(searchText, StringComparison.OrdinalIgnoreCase);
- if (idx >= 0)
+ for (var start = 0; start <= lineText.Length - searchText.Length;)
{
- // Find which block(s) contain the match
- int charPos = 0;
- for (int i = 0; i < lineBlocks.Count; i++)
- {
- var block = lineBlocks[i];
- var blockEnd = charPos + block.Text.Length;
- if (charPos <= idx && blockEnd > idx)
- {
- // Calculate approximate X offset within this block
- var charOffset = idx - charPos;
- var charWidth = block.FontSize * 0.5;
- var matchX = block.X + charOffset * charWidth;
- var matchWidth = searchText.Length * charWidth;
-
- found.Add(new TextBlock(
- Text: searchText,
- X: matchX,
- Y: block.Y - block.FontSize,
- Width: matchWidth,
- FontSize: block.FontSize,
- Page: block.Page
- ));
- break;
- }
- charPos = blockEnd;
- }
+ var idx = lineText.IndexOf(searchText, start, StringComparison.OrdinalIgnoreCase);
+ if (idx < 0) break;
+ var end = idx + searchText.Length; // исключительно
+
+ var first = BlockAt(starts, idx);
+ var last = BlockAt(starts, end - 1);
+ var x0 = line[first].X + OffsetIn(line[first], idx - starts[first]);
+ var x1 = line[last].X + EndOffsetIn(line[last], end - starts[last]);
+
+ found.Add(new TextBlock(
+ Text: lineText.Substring(idx, searchText.Length),
+ X: x0,
+ Y: line[first].Y, // Y блока уже верх текста
+ Width: x1 - x0,
+ FontSize: line[first].FontSize,
+ Page: line[first].Page));
+ start = end;
}
}
return found;
}
+ /// Индекс блока, содержащего символ pos склеенной строки (блоки непустые).
+ private static int BlockAt(int[] starts, int pos)
+ {
+ var i = Array.BinarySearch(starts, pos);
+ return i >= 0 ? i : ~i - 1;
+ }
+
+ /// Блоки → строки по базовой линии (Y + FontSize) с допуском 0.5 размера шрифта; внутри строки по X.
+ private static List> GroupIntoLines(List blocks)
+ {
+ var lines = new List>();
+ var ordered = blocks.OrderBy(b => b.Page).ThenBy(b => b.Y + b.FontSize).ThenBy(b => b.X);
+ foreach (var block in ordered)
+ {
+ var head = lines.Count > 0 ? lines[^1][0] : null;
+ var tolerance = Math.Max(block.FontSize * 0.5, 1);
+ if (head == null || head.Page != block.Page
+ || Math.Abs((head.Y + head.FontSize) - (block.Y + block.FontSize)) > tolerance)
+ lines.Add(new List());
+ lines[^1].Add(block);
+ }
+ return lines.Select(l => l.OrderBy(b => b.X).ToList()).ToList();
+ }
+
private static double ParseDouble(string? value)
{
if (string.IsNullOrEmpty(value)) return 0;
@@ -345,13 +609,14 @@ private static double ParseDouble(string? value)
///
/// Форматирует результат поиска текста для модели.
///
- public static string FormatSearchResults(List results, string searchText)
+ public static string FormatSearchResults(List results, string searchText, string? unit = null)
{
if (results.Count == 0)
return $"Текст \"{searchText}\" не найден в документе.";
var sb = new StringBuilder();
sb.AppendLine($"Найдено {results.Count} вхождений \"{searchText}\":");
+ if (unit != null) sb.AppendLine($"Единицы x, y, ширина, шрифт: {unit}; y — верх текста сверху вниз.");
sb.AppendLine();
foreach (var r in results)
{
diff --git a/Infrastructure/Helpers.cs b/Infrastructure/Helpers.cs
index 068561a..71e3a41 100644
--- a/Infrastructure/Helpers.cs
+++ b/Infrastructure/Helpers.cs
@@ -1,37 +1,13 @@
using Ascon.Pilot.Common;
using Ascon.Pilot.DataClasses;
using Ascon.Pilot.Server.Api.Contracts;
-using System.Text.Json;
namespace PilotMCP;
-internal static class Helpers
+internal static partial class Helpers
{
private static readonly string TempDocDir = Path.Combine(Path.GetTempPath(), "pilot-mcp");
- ///
- /// Скачивает файл из архива Pilot по чанкам. Возвращает количество скачанных байт.
- ///
- public static long DownloadToFile(IFileArchiveApi fileApi, Guid bodyId, string savePath)
- {
- var dir = Path.GetDirectoryName(savePath);
- if (!string.IsNullOrEmpty(dir))
- Directory.CreateDirectory(dir);
-
- const int chunkSize = 1024 * 1024;
- long offset = 0;
- using var fs = File.Create(savePath);
- while (true)
- {
- var chunk = fileApi.GetFileChunk(bodyId, offset, chunkSize);
- if (chunk == null || chunk.Length == 0) break;
- fs.Write(chunk, 0, chunk.Length);
- offset += chunk.Length;
- if (chunk.Length < chunkSize) break;
- }
- return offset;
- }
-
///
/// Скачивает файл во временную папку pilot-mcp. Возвращает путь к файлу.
///
@@ -48,6 +24,10 @@ public static string DownloadToTemp(IFileArchiveApi fileApi, Guid bodyId, string
public static Guid CreateChildObject(PilotConnection connection, Guid parentId, int typeId,
Dictionary? attributes = null, Guid? predefinedId = null)
{
+ // без проверки SDK падает внутри CreateObject с NullReferenceException
+ if (connection.ServerApi.GetObjectsAsync(new[] { parentId }).GetAwaiter().GetResult() is not { Count: > 0 })
+ throw new ArgumentException($"Родительский объект {parentId} не найден.");
+
var newId = predefinedId ?? Guid.NewGuid();
var modifier = connection.CreateModifier();
var builder = modifier.CreateObject(newId, parentId, typeId);
@@ -59,7 +39,7 @@ public static Guid CreateChildObject(PilotConnection connection, Guid parentId,
}
if (modifier.AnyChanges())
- modifier.Apply(null);
+ connection.ApplyAndWait(() => modifier.Apply(null));
return newId;
}
@@ -120,30 +100,6 @@ public static string GetDisplayName(DObject obj, DMetadata? metadata = null)
return obj.Id.ToString();
}
- private const int MaxAttrValueLength = 500;
-
- public static string FormatDValue(DValue? val, int maxLength = MaxAttrValueLength)
- {
- if (val == null) return "";
- if (val.DateValue.HasValue) return val.DateValue.Value.ToString("yyyy-MM-dd HH:mm:ss");
- if (!string.IsNullOrEmpty(val.StrValue)) return Truncate(val.StrValue!, maxLength);
- if (val.GuidValue != Guid.Empty) return val.GuidValue.ToString()!;
- if (val.ArrayValue != null && val.ArrayValue.Any())
- return Truncate(string.Join(", ", val.ArrayValue), maxLength);
- if (val.ArrayIntValue != null && val.ArrayIntValue.Any())
- return Truncate(string.Join(", ", val.ArrayIntValue), maxLength);
- if (val.IntValue != 0) return val.IntValue.ToString()!;
- if (val.DoubleValue != 0) return val.DoubleValue.ToString()!;
- if (val.DecimalValue != 0) return val.DecimalValue.ToString()!;
- return "";
- }
-
- public static string Truncate(string text, int maxLength)
- {
- if (string.IsNullOrEmpty(text) || text.Length <= maxLength) return text;
- return text[..maxLength] + $"... ({text.Length} chars total)";
- }
-
///
/// Вычисляет MD5 файла через SDK StreamExtensions.
/// Возвращает hex-строку в том же формате, что использует Pilot (Md5Ext.ToOldMd5String).
@@ -154,26 +110,4 @@ public static string ComputeFileMd5(string filePath)
var md5 = Ascon.Pilot.Common.Utils.StreamExtensions.ComputeMd5(stream, 81920);
return Md5Ext.ToOldMd5String(md5);
}
-
- public static Dictionary? ParseAttributes(string json)
- {
- try
- {
- var dict = new Dictionary();
- using var doc = JsonDocument.Parse(json);
- foreach (var prop in doc.RootElement.EnumerateObject())
- {
- dict[prop.Name] = prop.Value.ValueKind switch
- {
- JsonValueKind.String => new DValue { StrValue = prop.Value.GetString()! },
- JsonValueKind.Number when prop.Value.TryGetInt64(out var l) => new DValue { IntValue = l },
- JsonValueKind.Number => new DValue { DoubleValue = prop.Value.GetDouble() },
- JsonValueKind.True or JsonValueKind.False => new DValue { IntValue = prop.Value.GetBoolean() ? 1 : 0 },
- _ => new DValue { StrValue = prop.Value.GetRawText() }
- };
- }
- return dict;
- }
- catch { return null; }
- }
}
diff --git a/Infrastructure/HelpersObjects.cs b/Infrastructure/HelpersObjects.cs
new file mode 100644
index 0000000..109759a
--- /dev/null
+++ b/Infrastructure/HelpersObjects.cs
@@ -0,0 +1,83 @@
+using Ascon.Pilot.DataClasses;
+using Ascon.Pilot.Server.Api.Contracts;
+using System.Globalization;
+
+namespace PilotMCP;
+
+// Чистые функции для инструментов объектов — отдельным файлом, чтобы линковаться в unit-тесты.
+internal static partial class Helpers
+{
+ ///
+ /// Строит DValue из строки по типу атрибута (как это делает клиент Pilot: числа и даты — InvariantCulture).
+ /// Неразбираемое значение → ArgumentException (инструмент вернёт ошибку).
+ ///
+ public static DValue BuildTypedValue(MAttribute attr, string value)
+ {
+ value ??= "";
+ try
+ {
+ switch (attr.Type)
+ {
+ case MAttrType.Integer:
+ return new DValue { IntValue = long.Parse(value.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture) };
+ case MAttrType.Boolean:
+ return new DValue { IntValue = ParseBool(value) ? 1 : 0 };
+ case MAttrType.Double:
+ return new DValue { DoubleValue = double.Parse(value.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture) };
+ case MAttrType.Decimal:
+ return new DValue { DecimalValue = decimal.Parse(value.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture) };
+ case MAttrType.DateTime:
+ return new DValue
+ {
+ DateValue = DateTime.Parse(value.Trim(), CultureInfo.InvariantCulture,
+ DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal)
+ };
+ case MAttrType.UserState:
+ return new DValue { GuidValue = Guid.Parse(value.Trim()) };
+ case MAttrType.OrgUnit:
+ return new DValue
+ {
+ ArrayIntValue = value.Split(new[] { ',', ';' }, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
+ .Select(s => int.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture)).ToArray()
+ };
+ case MAttrType.ElementBook:
+ case MAttrType.Array:
+ return new DValue
+ {
+ ArrayValue = value.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
+ };
+ case MAttrType.ByteArray:
+ throw new ArgumentException($"атрибут '{attr.Name}' типа ByteArray не поддерживается");
+ default: // String, Numerator, Inherited
+ return new DValue { StrValue = value };
+ }
+ }
+ catch (Exception ex) when (ex is FormatException or OverflowException)
+ {
+ throw new ArgumentException(
+ $"Значение \"{value}\" не подходит для атрибута '{attr.Name}' типа {attr.Type}: {ex.Message}", ex);
+ }
+ }
+
+ private static bool ParseBool(string value) => value.Trim().ToLowerInvariant() switch
+ {
+ "1" or "true" or "yes" or "да" => true,
+ "0" or "false" or "no" or "нет" => false,
+ _ => throw new FormatException("ожидается true/false или 1/0")
+ };
+
+ /// Размер файла в архиве: читает чанки (без записи на диск). 0 — файла нет или он пуст.
+ public static long MeasureArchiveFile(IFileArchiveApi fileApi, Guid bodyId)
+ {
+ const int chunkSize = 1024 * 1024;
+ long offset = 0;
+ while (true)
+ {
+ var chunk = fileApi.GetFileChunk(bodyId, offset, chunkSize);
+ if (chunk == null || chunk.Length == 0) break;
+ offset += chunk.Length;
+ if (chunk.Length < chunkSize) break;
+ }
+ return offset;
+ }
+}
diff --git a/Infrastructure/HelpersValues.cs b/Infrastructure/HelpersValues.cs
new file mode 100644
index 0000000..6be76c7
--- /dev/null
+++ b/Infrastructure/HelpersValues.cs
@@ -0,0 +1,139 @@
+using Ascon.Pilot.DataClasses;
+using Ascon.Pilot.Server.Api.Contracts;
+using System.Globalization;
+using System.Text.Json;
+
+namespace PilotMCP;
+
+// Чистые функции без зависимости от PilotConnection — вынесены в отдельный файл, чтобы линковаться в unit-тесты.
+internal static partial class Helpers
+{
+ ///
+ /// Скачивает файл из архива Pilot по чанкам. Возвращает количество скачанных байт.
+ /// Пишет во временный savePath + ".part" и переименовывает только после полного успеха,
+ /// чтобы сбой не затирал существующий файл и не оставлял обрезок.
+ ///
+ public static long DownloadToFile(IFileArchiveApi fileApi, Guid bodyId, string savePath)
+ {
+ var dir = Path.GetDirectoryName(savePath);
+ if (!string.IsNullOrEmpty(dir))
+ Directory.CreateDirectory(dir);
+
+ const int chunkSize = 1024 * 1024;
+ var partPath = savePath + ".part";
+ long offset = 0;
+ var ok = false;
+ try
+ {
+ using (var fs = File.Create(partPath))
+ {
+ while (true)
+ {
+ var chunk = fileApi.GetFileChunk(bodyId, offset, chunkSize);
+ if (chunk == null || chunk.Length == 0) break;
+ fs.Write(chunk, 0, chunk.Length);
+ offset += chunk.Length;
+ if (chunk.Length < chunkSize) break;
+ }
+ }
+
+ if (offset == 0)
+ throw new InvalidOperationException(
+ $"Сервер вернул пустое содержимое файла (Body.Id={bodyId}). Файл не сохранён.");
+
+ File.Move(partPath, savePath, overwrite: true);
+ ok = true;
+ }
+ finally
+ {
+ if (!ok) File.Delete(partPath);
+ }
+ return offset;
+ }
+
+ private const int MaxAttrValueLength = 500;
+
+ public static string FormatDValue(DValue? val, int maxLength = MaxAttrValueLength)
+ {
+ if (val == null) return "";
+ if (val.DateValue.HasValue) return val.DateValue.Value.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
+ if (!string.IsNullOrEmpty(val.StrValue)) return Truncate(val.StrValue!, maxLength);
+ if (val.GuidValue is { } g && g != Guid.Empty) return g.ToString();
+ if (val.ArrayValue != null && val.ArrayValue.Any())
+ return Truncate(string.Join(", ", val.ArrayValue), maxLength);
+ if (val.ArrayIntValue != null && val.ArrayIntValue.Any())
+ return Truncate(string.Join(", ", val.ArrayIntValue), maxLength);
+ if (val.IntValue is { } i) return i.ToString(CultureInfo.InvariantCulture);
+ if (val.DoubleValue is { } d) return d.ToString(CultureInfo.InvariantCulture);
+ if (val.DecimalValue is { } m) return m.ToString(CultureInfo.InvariantCulture);
+ return "";
+ }
+
+ public static string Truncate(string text, int maxLength)
+ {
+ if (string.IsNullOrEmpty(text) || text.Length <= maxLength) return text;
+ return text[..maxLength] + $"... ({text.Length} chars total)";
+ }
+
+ ///
+ /// Разбирает JSON-объект атрибутов. Пустая строка → null (атрибутов нет).
+ /// JSON null пропускается; массивы чисел → ArrayIntValue, массивы строк → ArrayValue.
+ /// Некорректный JSON или неподдерживаемое значение → ArgumentException (инструмент вернёт ошибку).
+ ///
+ public static Dictionary? ParseAttributes(string json)
+ {
+ if (string.IsNullOrWhiteSpace(json)) return null;
+
+ try
+ {
+ var dict = new Dictionary();
+ using var doc = JsonDocument.Parse(json);
+ if (doc.RootElement.ValueKind != JsonValueKind.Object)
+ throw new ArgumentException("атрибуты должны быть JSON-объектом вида {\"имя\":\"значение\"}");
+
+ foreach (var prop in doc.RootElement.EnumerateObject())
+ {
+ var v = prop.Value;
+ switch (v.ValueKind)
+ {
+ case JsonValueKind.Null:
+ continue;
+ case JsonValueKind.String:
+ dict[prop.Name] = new DValue { StrValue = v.GetString()! };
+ break;
+ case JsonValueKind.Number when v.TryGetInt64(out var l):
+ dict[prop.Name] = new DValue { IntValue = l };
+ break;
+ case JsonValueKind.Number:
+ dict[prop.Name] = new DValue { DoubleValue = v.GetDouble() };
+ break;
+ case JsonValueKind.True:
+ case JsonValueKind.False:
+ dict[prop.Name] = new DValue { IntValue = v.GetBoolean() ? 1 : 0 };
+ break;
+ case JsonValueKind.Array:
+ dict[prop.Name] = ParseArray(prop.Name, v);
+ break;
+ default:
+ throw new ArgumentException($"атрибут '{prop.Name}': вложенные объекты не поддерживаются");
+ }
+ }
+ return dict;
+ }
+ catch (JsonException ex)
+ {
+ throw new ArgumentException($"Некорректный JSON атрибутов: {ex.Message}", ex);
+ }
+ }
+
+ private static DValue ParseArray(string name, JsonElement array)
+ {
+ var items = array.EnumerateArray().ToList();
+ if (items.Count > 0 && items.All(e => e.ValueKind == JsonValueKind.String))
+ return new DValue { ArrayValue = items.Select(e => e.GetString()!).ToArray() };
+ if (items.Count > 0 && items.All(e => e.ValueKind == JsonValueKind.Number && e.TryGetInt32(out _)))
+ return new DValue { ArrayIntValue = items.Select(e => e.GetInt32()).ToArray() };
+ throw new ArgumentException(
+ $"атрибут '{name}': массив должен быть непустым и состоять только из строк или только из целых чисел");
+ }
+}
diff --git a/Infrastructure/MessageHelpers.cs b/Infrastructure/MessageHelpers.cs
new file mode 100644
index 0000000..d595a54
--- /dev/null
+++ b/Infrastructure/MessageHelpers.cs
@@ -0,0 +1,79 @@
+using System.Globalization;
+using Ascon.Pilot.DataClasses;
+using static Ascon.Pilot.Common.DMessageExtensions;
+
+namespace PilotMCP;
+
+/// Чистые хелперы мессенджера и задач (без обращения к серверу).
+public static class MessageHelpers
+{
+ ///
+ /// Текст сообщения для показа: последняя правка (EditTextMessage из RelatedMessages) заменяет оригинал и
+ /// помечается «(ред.)», markdown помечается, реакции (MessageReaction) сводятся в «[реакции: ...]».
+ ///
+ public static string FormatText(INMessage msg)
+ {
+ if (msg.Data == null || msg.Data.Length == 0)
+ return $"[{msg.Type}]";
+
+ if (msg.Type is not (MessageType.TextMessage or MessageType.EditTextMessage or MessageType.MessageAnswer))
+ return $"[{msg.Type}]";
+
+ var related = msg.RelatedMessages?.ToList() ?? new List();
+ var source = msg;
+ var edited = false;
+ var edit = related.Where(r => r.Type == MessageType.EditTextMessage && r.Data is { Length: > 0 })
+ .OrderBy(r => r.ServerDate ?? r.LocalDate).LastOrDefault();
+ if (edit != null) { source = edit; edited = true; }
+
+ string text;
+ bool markdown;
+ try
+ {
+ var data = source.GetMessageData();
+ text = data?.Text ?? "";
+ markdown = data?.IsMarkdown == true;
+ }
+ catch (Exception ex)
+ {
+ return $"[ошибка чтения текста, {source.Data.Length} bytes: {ex.Message}]";
+ }
+
+ if (edited) text += " (ред.)";
+ if (markdown) text += " [markdown]";
+
+ var reactions = new List();
+ foreach (var r in related.Where(r => r.Type == MessageType.MessageReaction && r.Data is { Length: > 0 }))
+ {
+ try { reactions.AddRange(r.GetMessageData()?.Emojis ?? new List()); }
+ catch (Exception ex) { reactions.Add($"[ошибка реакции: {ex.Message}]"); }
+ }
+ if (reactions.Count > 0)
+ text += " [реакции: " + string.Join(" ", reactions.GroupBy(e => e).Select(g => g.Count() > 1 ? $"{g.Key}x{g.Count()}" : g.Key)) + "]";
+
+ return text;
+ }
+
+ /// Разбирает GUID через запятую. Любой некорректный элемент — ошибка (возвращается его текст).
+ public static bool TryParseGuids(string? csv, out List guids, out string? bad)
+ {
+ guids = new List();
+ bad = null;
+ foreach (var s in (csv ?? "").Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
+ {
+ if (!Guid.TryParse(s, out var g)) { bad = s; return false; }
+ guids.Add(g);
+ }
+ return true;
+ }
+
+ /// Дедлайн yyyy-MM-dd → конец этого дня (23:59:59 по местному времени, как в клиенте Pilot) в UTC.
+ public static bool TryParseDeadline(string text, out DateTime utc)
+ {
+ utc = default;
+ if (!DateTime.TryParseExact(text.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var d))
+ return false;
+ utc = DateTime.SpecifyKind(d.Date.AddHours(23).AddMinutes(59).AddSeconds(59), DateTimeKind.Local).ToUniversalTime();
+ return true;
+ }
+}
diff --git a/Infrastructure/QueryHelpers.cs b/Infrastructure/QueryHelpers.cs
new file mode 100644
index 0000000..493ce90
--- /dev/null
+++ b/Infrastructure/QueryHelpers.cs
@@ -0,0 +1,88 @@
+using System.Globalization;
+using System.Text;
+
+namespace PilotMCP;
+
+/// Чистые хелперы разбора аргументов поиска и файловых инструментов (без зависимости от сервера).
+public static class QueryHelpers
+{
+ private const string LuceneSpecials = "+-&|!(){}[]^\"~*?:\\/";
+
+ /// Экранирует спецсимволы Lucene в одном слове, чтобы оно искалось буквально.
+ public static string EscapeLucene(string word)
+ {
+ // AND/OR/NOT в верхнем регистре — операторы Lucene (запрос с ними сервер не исполняет);
+ // анализатор всё равно приводит слова к нижнему регистру, поэтому так ищется буквально.
+ if (word is "AND" or "OR" or "NOT") return word.ToLowerInvariant();
+ var sb = new StringBuilder(word.Length + 4);
+ foreach (var c in word)
+ {
+ if (LuceneSpecials.Contains(c)) sb.Append('\\');
+ sb.Append(c);
+ }
+ return sb.ToString();
+ }
+
+ /// Фраза в кавычках: многословное значение остаётся одним термом поля.
+ public static string QuoteLucene(string value)
+ => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
+
+ /// Разбивает текст на слова и экранирует каждое. Пустой результат — пустой массив.
+ public static string[] EscapedWords(string text)
+ => (text ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .Select(EscapeLucene).ToArray();
+
+ ///
+ /// Разбор даты (InvariantCulture, без времени = UTC). Для верхней границы без времени
+ /// берётся конец этого дня (иначе объекты, созданные в этот день, выпадают из диапазона).
+ ///
+ public static bool TryParseDate(string s, bool upperBound, out DateTime utc)
+ {
+ utc = default;
+ s = s.Trim();
+ if (!DateTime.TryParse(s, CultureInfo.InvariantCulture,
+ DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out utc))
+ return false;
+ if (upperBound && !s.Contains(':'))
+ utc = utc.AddDays(1).AddSeconds(-1);
+ return true;
+ }
+
+ ///
+ /// Разбор пары границ дат. Пустая строка = нет границы. Возвращает текст ошибки или null.
+ ///
+ public static string? ParseRange(string from, string to, string fromName, string toName,
+ out DateTime dateFrom, out DateTime dateTo)
+ {
+ dateFrom = DateTime.MinValue;
+ dateTo = DateTime.MaxValue;
+ if (!string.IsNullOrWhiteSpace(from) && !TryParseDate(from, false, out dateFrom))
+ return $"Некорректная дата {fromName}: '{from}'. Ожидается ISO 8601, например 2025-01-31.";
+ if (!string.IsNullOrWhiteSpace(to) && !TryParseDate(to, true, out dateTo))
+ return $"Некорректная дата {toName}: '{to}'. Ожидается ISO 8601, например 2025-01-31.";
+ if (dateFrom > dateTo)
+ return $"Дата {fromName} позже даты {toName}.";
+ return null;
+ }
+
+ /// Поле CSV: кавычки при разделителе, кавычке, переводе строки или возврате каретки.
+ public static string CsvEscape(string s, string separator)
+ => s.Contains(separator) || s.Contains('"') || s.Contains('\n') || s.Contains('\r')
+ ? $"\"{s.Replace("\"", "\"\"")}\""
+ : s;
+
+ ///
+ /// Проверяет пару входной/выходной файл: совпадение путей (запись обнулила бы вход до чтения)
+ /// и создаёт каталог вывода. Возвращает текст ошибки или null.
+ ///
+ public static string? PrepareOutput(string inputFile, string outputFile)
+ {
+ var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
+ var full = Path.GetFullPath(outputFile);
+ if (string.Equals(Path.GetFullPath(inputFile), full, comparison))
+ return "outputFile совпадает с inputFile: запись затёрла бы входной файл. Укажите другой путь или оставьте outputFile пустым.";
+ var dir = Path.GetDirectoryName(full);
+ if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
+ return null;
+ }
+}
diff --git a/Infrastructure/ReconnectingProxy.cs b/Infrastructure/ReconnectingProxy.cs
index 1acba7b..0b99020 100644
--- a/Infrastructure/ReconnectingProxy.cs
+++ b/Infrastructure/ReconnectingProxy.cs
@@ -1,11 +1,16 @@
+using Ascon.Pilot.Transport;
+using System.Diagnostics.CodeAnalysis;
using System.Reflection;
+using System.Runtime.ExceptionServices;
namespace PilotMCP;
///
/// DispatchProxy-обёртка для API-интерфейсов Pilot.
/// При ошибке соединения (Transport closed, disposed и т.д.) автоматически
-/// переподключается и повторяет вызов.
+/// переподключается. Вызов повторяется только если это безопасно: метод читающий
+/// (Get*/Load*/Calc*/Open*...) либо цель уже была disposed (запрос не уходил на сервер).
+/// Записи после таймаута/обрыва не повторяются — сервер мог уже применить изменение.
/// Поддерживает как sync, так и async (Task-returning) методы.
///
public class ReconnectingProxy : DispatchProxy where T : class
@@ -36,7 +41,7 @@ public static T Create(T initialTarget, Func targetFactory, Action restore, F
try
{
- var result = targetMethod.Invoke(_target, args);
+ var result = InvokeTarget(targetMethod, args);
// Для async методов (возвращающих Task) — перехватываем ошибку внутри Task
if (result is Task task)
@@ -44,10 +49,6 @@ public static T Create(T initialTarget, Func targetFactory, Action restore, F
return result;
}
- catch (TargetInvocationException tie) when (IsRecoverable(tie.InnerException))
- {
- return Retry(targetMethod, args, tie.InnerException!);
- }
catch (Exception ex) when (IsRecoverable(ex))
{
return Retry(targetMethod, args, ex);
@@ -85,7 +86,8 @@ private async Task WrapTaskVoid(Task originalTask, MethodInfo method, object?[]?
catch (Exception ex) when (IsRecoverable(ex))
{
Restore(method.Name, ex.GetType().Name);
- var retryResult = method.Invoke(_target, args);
+ if (!CanReplay(method, ex)) throw;
+ var retryResult = InvokeTarget(method, args);
if (retryResult is Task retryTask)
await retryTask;
}
@@ -100,7 +102,8 @@ private async Task WrapTaskGeneric(Task originalTask,
catch (Exception ex) when (IsRecoverable(ex))
{
Restore(method.Name, ex.GetType().Name);
- var retryResult = method.Invoke(_target, args);
+ if (!CanReplay(method, ex)) throw;
+ var retryResult = InvokeTarget(method, args);
if (retryResult is Task retryTask)
return await retryTask;
throw;
@@ -123,16 +126,43 @@ private void Restore(string methodName, string reason)
private object? Retry(MethodInfo method, object?[]? args, Exception original)
{
Restore(method.Name, original.GetType().Name);
+ if (!CanReplay(method, original)) Rethrow(original);
+ return InvokeTarget(method, args);
+ }
+
+ /// Вызов метода target с разворачиванием TargetInvocationException — наружу идёт настоящая ошибка сервера.
+ private object? InvokeTarget(MethodInfo method, object?[]? args)
+ {
try
{
return method.Invoke(_target, args);
}
- catch (TargetInvocationException tie)
+ catch (TargetInvocationException tie) when (tie.InnerException != null)
{
- throw tie.InnerException ?? tie;
+ Rethrow(tie.InnerException);
+ return null;
}
}
+ [DoesNotReturn]
+ private static void Rethrow(Exception ex) => ExceptionDispatchInfo.Capture(ex).Throw();
+
+ private static readonly string[] ReadOnlyPrefixes = { "Get", "Load", "Calc", "Open", "Check", "Enumerate", "SearchMessages" };
+
+ ///
+ /// Можно ли безопасно повторить вызов после reconnect: читающие методы — всегда;
+ /// остальные — только если цель была disposed (запрос на сервер не уходил).
+ /// После таймаута/обрыва записи (ChangeAsync, SendMessage, InvokeCommand...) сервер мог уже
+ /// выполнить вызов, повтор дал бы дубликат.
+ ///
+ private static bool CanReplay(MethodInfo method, Exception ex)
+ {
+ if (ReadOnlyPrefixes.Any(p => method.Name.StartsWith(p, StringComparison.Ordinal))) return true;
+ for (var e = ex; e != null; e = e.InnerException)
+ if (e is ObjectDisposedException) return true;
+ return false;
+ }
+
///
/// Определяет, является ли ошибка транспортной (соединение потеряно/закрыто) —
/// используется также PilotConnection для админ-подключения.
@@ -143,13 +173,12 @@ private static bool IsRecoverable(Exception? ex)
{
if (ex == null) return false;
if (ex is ObjectDisposedException) return true;
- if (ex is TimeoutException) return true;
+ if (ex is TimeoutException or TransportException) return true;
var msg = ex.Message;
if (msg != null && (
msg.Contains("disposed", StringComparison.OrdinalIgnoreCase) ||
msg.Contains("Transport closed", StringComparison.OrdinalIgnoreCase) ||
- msg.Contains("TransportClient", StringComparison.OrdinalIgnoreCase) ||
- msg.Contains("transport", StringComparison.OrdinalIgnoreCase)))
+ msg.Contains("TransportClient", StringComparison.OrdinalIgnoreCase)))
return true;
if (ex.InnerException != null) return IsRecoverable(ex.InnerException);
return false;
diff --git a/Infrastructure/ToolLogger.cs b/Infrastructure/ToolLogger.cs
index afaa1db..f4b50d8 100644
--- a/Infrastructure/ToolLogger.cs
+++ b/Infrastructure/ToolLogger.cs
@@ -27,13 +27,25 @@ public static void Log(string toolName, string args, string result)
entry.AppendLine($" Result: {resultPreview}");
entry.AppendLine();
- lock (Lock)
+ // Логирование — вспомогательная функция: сбой записи (общий файл у нескольких процессов,
+ // нет прав, диск) не должен превращать уже выполненный вызов инструмента в ошибку.
+ try
{
- File.AppendAllText(LogPath, entry.ToString(), Encoding.UTF8);
- }
+ lock (Lock)
+ {
+ // FileShare.ReadWrite: лог общий для всех процессов PilotMCP.
+ using var fs = new FileStream(LogPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
+ var bytes = Encoding.UTF8.GetBytes(entry.ToString());
+ fs.Write(bytes, 0, bytes.Length);
+ }
- // Also write to stderr for MCP client visibility
- Console.Error.WriteLine($"[PilotMCP] {toolName}({args}) → {(result.Length > 200 ? result[..200] + "..." : result)}");
+ // Also write to stderr for MCP client visibility
+ Console.Error.WriteLine($"[PilotMCP] {toolName}({args}) → {(result.Length > 200 ? result[..200] + "..." : result)}");
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ObjectDisposedException)
+ {
+ Console.Error.WriteLine($"[PilotMCP] ToolLogger: не удалось записать лог ({ex.GetType().Name}: {ex.Message})");
+ }
}
public static void LogError(string toolName, string args, Exception ex)
diff --git a/PilotConnection.cs b/PilotConnection.cs
index 0319375..38f8ed1 100644
--- a/PilotConnection.cs
+++ b/PilotConnection.cs
@@ -4,6 +4,7 @@
using Ascon.Pilot.Server.Api;
using Ascon.Pilot.Server.Api.Contracts;
using Ascon.Pilot.Transport;
+using System.Collections.Concurrent;
using IConnectionLostListener = Ascon.Pilot.Transport.IConnectionLostListener;
namespace PilotMCP;
@@ -24,6 +25,8 @@ public class PilotConnection : IDisposable
private volatile bool _connectionLost;
private readonly object _reconnectLock = new();
private volatile bool _reconnectInProgress;
+ private volatile bool _metadataStale; // сервер сообщил об изменении метаданных — перечитать при следующем обращении
+ private readonly SemaphoreSlim _metadataLock = new(1, 1); // сериализует read-modify-write метаданных
private readonly List _lastErrors = new();
private Backend? _backend;
private FileSystemStorageProvider? _storageProvider;
@@ -107,6 +110,15 @@ public IModifier CreateModifier()
public int CurrentPersonId => _dbInfo?.Person?.Id ?? 0;
public string Connect(string serverUrl, string login, string password, string? databaseName = null, int licenseType = 100)
+ {
+ // Тот же lock, что у DoReconnect/EnsureConnected: параллельные логины с одной учёткой выбивают сессии друг друга.
+ lock (_reconnectLock)
+ {
+ return ConnectCore(serverUrl, login, password, databaseName, licenseType);
+ }
+ }
+
+ private string ConnectCore(string serverUrl, string login, string password, string? databaseName, int licenseType)
{
_savedServerUrl = serverUrl;
_savedLogin = login;
@@ -141,7 +153,7 @@ public string Connect(string serverUrl, string login, string password, string? d
Console.Error.WriteLine("[PilotMCP] HTTP клиент подключён");
_authApi = _client.GetAuthenticationApi();
- _callback = new ServerCallback();
+ _callback = new ServerCallback(() => _metadataStale = true);
_rawServerApi = _client.GetServerAsyncApi(_callback);
_rawSyncServerApi = _client.GetServerApi(_callback);
_rawFileApi = _client.GetFileArchiveApi();
@@ -286,19 +298,20 @@ private void DoReconnectWithRetry()
}
}
+ // Все попытки провалились: не оставляем полуинициализированный клиент (без логина/БД),
+ // который IsConnected считал бы живым. После сброса EnsureConnected сделает полный Connect.
+ TearDownClient();
+ _connectionLost = true;
+
throw new InvalidOperationException(
$"Не удалось переподключиться после {maxAttempts} попыток: {lastError!.Message}", lastError);
}
///
- /// Ядро переподключения — один атомарный цикл: disconnect → connect → login → open.
+ /// Сбрасывает клиент и все производные raw API (после этого IsConnected == false).
///
- private void DoReconnectCore()
+ private void TearDownClient()
{
- _connectionLost = false;
-
- Console.Error.WriteLine("[PilotMCP] Полное переподключение...");
-
var oldClient = _client;
_client = null;
_rawServerApi = null;
@@ -320,6 +333,18 @@ private void DoReconnectCore()
disconnectTask.Wait(5000); // Ждём макс 5 секунд
Console.Error.WriteLine($"[PilotMCP] Старый клиент отключён: {(disconnectTask.IsCompleted ? "ok" : "timeout")}");
}
+ }
+
+ ///
+ /// Ядро переподключения — один атомарный цикл: disconnect → connect → login → open.
+ ///
+ private void DoReconnectCore()
+ {
+ _connectionLost = false;
+
+ Console.Error.WriteLine("[PilotMCP] Полное переподключение...");
+
+ TearDownClient();
if (string.IsNullOrEmpty(_savedServerUrl) || string.IsNullOrEmpty(_savedLogin))
throw new InvalidOperationException("Нет сохранённых креденшалов для переподключения.");
@@ -342,7 +367,7 @@ private void DoReconnectCore()
Console.Error.WriteLine("[PilotMCP] DoReconnect: HTTP клиент создан");
_authApi = _client.GetAuthenticationApi();
- _callback = new ServerCallback();
+ _callback = new ServerCallback(() => _metadataStale = true);
_rawServerApi = _client.GetServerAsyncApi(_callback);
_rawSyncServerApi = _client.GetServerApi(_callback);
_rawFileApi = _client.GetFileArchiveApi();
@@ -410,15 +435,27 @@ public async Task WithAdminApiAsync(Func> ac
public async Task UpdateMetadataViaAdminAsync(Action mutate)
{
EnsureConnected();
- return await WithAdminApiAsync(async admin =>
+ // Read-modify-write всего объекта метаданных: без сериализации параллельные вызовы
+ // (CreateType + AddTypeAttribute) читают одну версию и затирают изменения друг друга.
+ // Между процессами PilotMCP это не защищает.
+ await _metadataLock.WaitAsync();
+ try
{
- var meta = await admin.GetMetadataAsync(DatabaseName, 0);
- mutate(meta);
- var newVersion = await admin.UpdateMetadataAsync(DatabaseName, meta);
- meta.Version = newVersion;
- _metadata = meta;
- return newVersion;
- });
+ return await WithAdminApiAsync(async admin =>
+ {
+ var meta = await admin.GetMetadataAsync(DatabaseName, 0);
+ mutate(meta);
+ var newVersion = await admin.UpdateMetadataAsync(DatabaseName, meta);
+ meta.Version = newVersion;
+ _metadata = meta;
+ _metadataStale = true; // Backend SDK кеширует типы — пересоздать при следующем обращении
+ return newVersion;
+ });
+ }
+ finally
+ {
+ _metadataLock.Release();
+ }
}
private IServerAdminAsyncApi GetOrCreateAdminApi()
@@ -485,10 +522,70 @@ private void DisposeAdminClientLocked()
public async Task SearchAsync(DSearchDefinition searchDef, int timeoutMs = 30000)
{
EnsureConnected();
- _callback!.PrepareForSearch(searchDef.Id);
- await ServerApi.AddSearchAsync(searchDef);
- var result = await _callback.WaitForSearchResultAsync(searchDef.Id, timeoutMs);
- return result;
+ var cb = _callback ?? throw new InvalidOperationException(NotConnectedMessage);
+ cb.PrepareForSearch(searchDef.Id);
+ try
+ {
+ await ServerApi.AddSearchAsync(searchDef);
+ return await cb.WaitForSearchResultAsync(searchDef.Id, timeoutMs);
+ }
+ finally
+ {
+ cb.ForgetSearch(searchDef.Id);
+ }
+ }
+
+ ///
+ /// Применяет изменения (apply — вызов modifier.Apply(...), возвращающий Identity changeset-а)
+ /// и ждёт ответа сервера: Backend.Apply только отправляет ChangeAsync, а результат приходит
+ /// в NotifyChangeAsyncCompleted/NotifyChangeAsyncError с тем же Identity.
+ /// Отказ сервера или отсутствие ответа за timeoutMs → исключение с понятным текстом.
+ ///
+ public Guid ApplyAndWait(Func apply, int timeoutMs = 60000)
+ {
+ var id = apply();
+ var cb = _callback ?? throw new InvalidOperationException(NotConnectedMessage);
+ var tcs = cb.ChangeResult(id);
+ try
+ {
+ if (!tcs.Task.Wait(timeoutMs))
+ throw new TimeoutException(
+ $"Сервер не подтвердил изменение за {timeoutMs / 1000} с (changeset {id}). " +
+ "Результат неизвестен: проверьте состояние объекта перед повторной попыткой.");
+ }
+ finally
+ {
+ cb.ForgetChange(id);
+ }
+
+ var error = tcs.Task.Result;
+ if (error != null)
+ throw new InvalidOperationException($"Сервер отклонил изменение: {error}");
+ return id;
+ }
+
+ ///
+ /// Вызывает серверную команду и ждёт NotifyCommandResult. null — результат не пришёл за timeoutMs.
+ ///
+ public async Task<(bool Success, byte[] Data)?> InvokeCommandAsync(
+ string commandName, Guid requestId, byte[] data, int timeoutMs = 15000)
+ {
+ EnsureConnected();
+ var cb = _callback ?? throw new InvalidOperationException(NotConnectedMessage);
+ var tcs = cb.CommandResult(requestId);
+ try
+ {
+ await ServerApi.InvokeCommandAsync(commandName, requestId, data);
+ return await tcs.Task.WaitAsync(TimeSpan.FromMilliseconds(timeoutMs));
+ }
+ catch (TimeoutException) when (!tcs.Task.IsCompleted)
+ {
+ return null;
+ }
+ finally
+ {
+ cb.ForgetCommand(requestId);
+ }
}
public void Disconnect()
@@ -521,14 +618,44 @@ public void Disconnect()
public void EnsureConnected()
{
- if (IsConnected)
+ // Под тем же lock, что DoReconnect/Connect: пока другой поток переподключается (клиент временно null),
+ // параллельные вызовы ждут, а не запускают конкурирующие логины.
+ lock (_reconnectLock)
{
- if (_backend == null)
- RebuildBackend();
- return;
+ if (IsConnected)
+ {
+ if (_backend == null)
+ RebuildBackend();
+ if (_metadataStale)
+ RefreshMetadata();
+ return;
+ }
+
+ Reconnect();
}
+ }
- Reconnect();
+ ///
+ /// Перечитывает метаданные после NotifyDMetadataChangeset (или записи через админ-API)
+ /// и пересоздаёт Backend, который кеширует типы. При сбое остаёмся на старых данных и повторим при следующем вызове.
+ ///
+ private void RefreshMetadata()
+ {
+ _metadataStale = false;
+ try
+ {
+ var api = _rawServerApi!;
+ var info = Task.Run(() => api.OpenDatabaseAsync()).GetAwaiter().GetResult();
+ var meta = Task.Run(() => api.GetMetadataAsync(info?.MetadataVersion ?? 0)).GetAwaiter().GetResult();
+ _dbInfo = info;
+ _metadata = meta;
+ RebuildBackend();
+ }
+ catch (Exception ex)
+ {
+ _metadataStale = true;
+ Console.Error.WriteLine($"[PilotMCP] Не удалось обновить метаданные: {ex.GetType().Name}: {ex.Message}");
+ }
}
private void Reconnect()
@@ -564,21 +691,35 @@ private void Reconnect()
private class ServerCallback : IServerCallback
{
- private readonly Dictionary> _searchWaiters = new();
+ private readonly ConcurrentDictionary> _searchWaiters = new();
+ // null в результате = успех, строка = текст ошибки сервера. GetOrAdd с обеих сторон:
+ // ответ может прийти раньше, чем вызывающий начнёт ждать.
+ private readonly ConcurrentDictionary> _changeResults = new();
+ private readonly ConcurrentDictionary> _commandResults = new();
+ private readonly Action _onMetadataChanged;
- public void PrepareForSearch(Guid searchId)
- {
- _searchWaiters[searchId] = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
- }
+ public ServerCallback(Action onMetadataChanged) => _onMetadataChanged = onMetadataChanged;
+
+ private static TaskCompletionSource NewTcs() => new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public void PrepareForSearch(Guid searchId) => _searchWaiters[searchId] = NewTcs();
+
+ public void ForgetSearch(Guid searchId) => _searchWaiters.TryRemove(searchId, out _);
+
+ /// Ждёт результат поиска; по таймауту бросает TimeoutException (а не возвращает «пусто»).
public async Task WaitForSearchResultAsync(Guid searchId, int timeoutMs)
{
if (!_searchWaiters.TryGetValue(searchId, out var tcs))
return null;
- var completed = await Task.WhenAny(tcs.Task, Task.Delay(timeoutMs));
- _searchWaiters.Remove(searchId);
- return completed == tcs.Task ? tcs.Task.Result : null;
+ try
+ {
+ return await tcs.Task.WaitAsync(TimeSpan.FromMilliseconds(timeoutMs));
+ }
+ catch (TimeoutException)
+ {
+ throw new TimeoutException($"Сервер не вернул результат поиска за {timeoutMs / 1000} с.");
+ }
}
public void NotifySearchResult(DSearchResult searchResult)
@@ -589,15 +730,22 @@ public void NotifySearchResult(DSearchResult searchResult)
}
}
+ public TaskCompletionSource ChangeResult(Guid identity) => _changeResults.GetOrAdd(identity, _ => NewTcs());
+ public void ForgetChange(Guid identity) => _changeResults.TryRemove(identity, out _);
+ public TaskCompletionSource<(bool, byte[])?> CommandResult(Guid requestId) => _commandResults.GetOrAdd(requestId, _ => NewTcs<(bool, byte[])?>());
+ public void ForgetCommand(Guid requestId) => _commandResults.TryRemove(requestId, out _);
+
public void NotifyChangeset(DChangeset changeset) { }
public void NotifyOrganisationUnitChangeset(OrganisationUnitChangeset changeset) { }
public void NotifyPersonChangeset(PersonChangeset changeset) { }
- public void NotifyDMetadataChangeset(DMetadataChangeset changeset) { }
+ public void NotifyDMetadataChangeset(DMetadataChangeset changeset) => _onMetadataChanged();
public void NotifyGeometrySearchResult(DGeometrySearchResult searchResult) { }
public void NotifyDNotificationChangeset(DNotificationChangeset changeset) { }
- public void NotifyCommandResult(Guid requestId, byte[] data, ServerCommandResult result) { }
- public void NotifyChangeAsyncCompleted(DChangeset changeset) { }
- public void NotifyChangeAsyncError(Guid identity, ProtoExceptionInfo exception) { }
+ public void NotifyCommandResult(Guid requestId, byte[] data, ServerCommandResult result)
+ => CommandResult(requestId).TrySetResult((result == ServerCommandResult.Success, data));
+ public void NotifyChangeAsyncCompleted(DChangeset changeset) => ChangeResult(changeset.Identity).TrySetResult(null);
+ public void NotifyChangeAsyncError(Guid identity, ProtoExceptionInfo exception)
+ => ChangeResult(identity).TrySetResult(ProtoExceptionInfo.Deserialize(exception).Message);
public void NotifyCustomNotification(string name, byte[] data) { }
public void NotifyAccessChangeset(Guid objectId) { }
public void NotifySettingsChangeset(string settingKey) { }
@@ -643,6 +791,7 @@ public void NotifyLicenseChanged() { }
private class MessageCallback : IMessageCallback
{
public void NotifyMessageCreated(NotifiableDMessage message) { }
+ public void NotifyMessagesCreated(List messages) { }
public void NotifyTypingMessage(Guid chatId, int personId) { }
public void NotifyOnline(int personId) { }
public void NotifyOffline(int personId) { }
diff --git a/PilotMCP.Tests/AdminValidationTests.cs b/PilotMCP.Tests/AdminValidationTests.cs
new file mode 100644
index 0000000..134505d
--- /dev/null
+++ b/PilotMCP.Tests/AdminValidationTests.cs
@@ -0,0 +1,45 @@
+using System.Text.Json.Nodes;
+
+namespace PilotMCP.Tests;
+
+/// Проверки входа админских инструментов: ошибка возвращается до обращения к данным сервера.
+[Collection("Pilot")]
+[Trait("Category", "Integration")]
+public class AdminValidationTests
+{
+ private readonly McpTestClient _client;
+ public AdminValidationTests(PilotFixture fixture) => _client = fixture.Client;
+
+ [Fact]
+ public async Task ChangeSettings_WithoutTarget_ReturnsError()
+ {
+ var r = await _client.CallToolAsync("ChangeSettings", new JsonObject { ["key"] = "mcp_test_key", ["value"] = "x" });
+ r.AssertError();
+ }
+
+ [Fact]
+ public async Task UpdatePerson_WithoutFields_ReturnsError()
+ {
+ var r = await _client.CallToolAsync("UpdatePerson", new JsonObject { ["personId"] = 1 });
+ r.AssertError();
+ }
+
+ [Fact]
+ public async Task UpdatePerson_WithBadBool_ReturnsError()
+ {
+ var r = await _client.CallToolAsync("UpdatePerson", new JsonObject { ["personId"] = 1, ["isInactive"] = "yes" });
+ r.AssertError();
+ }
+
+ [Theory]
+ [InlineData("CreateType", "kind", "99")]
+ [InlineData("CreateUserState", "color", "42")]
+ public async Task NumericEnumString_IsRejected(string tool, string param, string value)
+ {
+ var args = new JsonObject { ["name"] = $"mcp_test_{Guid.NewGuid():N}", [param] = value };
+ if (tool == "CreateType") args["title"] = "t";
+ if (tool == "CreateUserState") args["title"] = "t";
+ var r = await _client.CallToolAsync(tool, args, 60000);
+ r.AssertError();
+ }
+}
diff --git a/PilotMCP.Tests/AnnotationToolsTests.cs b/PilotMCP.Tests/AnnotationToolsTests.cs
new file mode 100644
index 0000000..dd25c66
--- /dev/null
+++ b/PilotMCP.Tests/AnnotationToolsTests.cs
@@ -0,0 +1,316 @@
+using System.Text.Json.Nodes;
+using System.Text.RegularExpressions;
+
+namespace PilotMCP.Tests;
+
+///
+/// Интеграционные тесты замечаний. Все созданные замечания удаляются в WithCleanup (DeleteObject).
+/// Тестовый документ ищется через инструменты: первый документ с .xps-файлом и словом на странице 0.
+///
+[Collection("Pilot")]
+[Trait("Category", "Integration")]
+public class AnnotationToolsTests
+{
+ private readonly McpTestClient _client;
+ public AnnotationToolsTests(PilotFixture fixture) => _client = fixture.Client;
+
+ private static (string DocId, string Word)? _testDoc;
+
+ private async Task<(string DocId, string Word)> FindTestDocument()
+ {
+ if (_testDoc != null) return _testDoc.Value;
+
+ var search = await _client.CallToolAsync("Search", new JsonObject { ["query"] = "*", ["maxResults"] = 2000 });
+ search.AssertOk();
+ Assert.NotNull(search.ResultFile);
+
+ var candidates = File.ReadLines(search.ResultFile!)
+ .Where(l => !string.IsNullOrWhiteSpace(l))
+ .Select(l => JsonNode.Parse(l)!.AsObject())
+ .Where(o => (o["filesCount"]?.GetValue() ?? 0) > 0)
+ .Select(o => o["id"]!.GetValue())
+ .Take(300);
+
+ foreach (var id in candidates)
+ {
+ var obj = await _client.CallToolAsync("GetObject", new JsonObject { ["objectId"] = id });
+ if (obj.IsError || !obj.RawText.Contains(".xps", StringComparison.OrdinalIgnoreCase)) continue;
+
+ var text = await _client.CallToolAsync("GetDocumentText", new JsonObject
+ {
+ ["documentId"] = id, ["page"] = 0, ["maxChars"] = 3000
+ });
+ if (text.IsError) continue;
+ var body = string.Join("\n", text.Message.Split('\n').Where(l => !l.StartsWith("Страница") && !l.StartsWith("===")));
+ var word = Regex.Matches(body, @"\p{L}{6,}").Select(m => m.Value).FirstOrDefault();
+ if (word == null) continue;
+
+ _testDoc = (id, word);
+ return _testDoc.Value;
+ }
+
+ Assert.Fail("В тестовой базе не найден документ с .xps-файлом и текстом (6+ букв) на странице 0 — тесты замечаний не могут выполняться.");
+ return default;
+ }
+
+ private async Task CreateRemark(string tool, JsonObject args, List created)
+ {
+ var result = await _client.CallToolAsync(tool, args, 60000);
+ result.AssertOk();
+ var m = Regex.Match(result.Message, @"ID: ([0-9a-fA-F-]{36})");
+ Assert.True(m.Success, $"В ответе {tool} нет ID замечания: {result.Message}");
+ created.Add(m.Groups[1].Value);
+ return m.Groups[1].Value;
+ }
+
+ ///
+ /// Выполняет тело теста и удаляет созданные замечания. Удаляются все, даже если часть удалений упала;
+ /// ошибки удаления собираются в AggregateException вместе с исходной ошибкой теста (она идёт первой и не теряется).
+ ///
+ private async Task WithCleanup(Func, Task> body)
+ {
+ var created = new List();
+ Exception? original = null;
+ try { await body(created); }
+ catch (Exception ex) { original = ex; }
+
+ var errors = new List();
+ if (original != null) errors.Add(original);
+ foreach (var id in created)
+ {
+ try { (await _client.CallToolAsync("DeleteObject", new JsonObject { ["objectId"] = id })).AssertOk(); }
+ catch (Exception ex) { errors.Add(new InvalidOperationException($"Не удалось удалить замечание {id}", ex)); }
+ }
+
+ if (errors.Count == 1 && original != null)
+ System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(original).Throw();
+ if (errors.Count > 0)
+ throw new AggregateException("Тест замечаний завершился с ошибками", errors);
+ }
+
+ private async Task GetAnnotations(string docId, int dpi = 150)
+ {
+ var result = await _client.CallToolAsync("GetAnnotations", new JsonObject { ["documentId"] = docId, ["dpi"] = dpi }, 60000);
+ result.AssertOk();
+ return JsonNode.Parse(result.Message)!.AsArray();
+ }
+
+ private static bool Contains(JsonArray all, string id) => all.Any(n => n!["id"]!.GetValue() == id);
+
+ private static HashSet Ids(JsonArray all) => all.Select(n => n!["id"]!.GetValue()).ToHashSet();
+
+ ///
+ /// Сервер применяет изменения асинхронно: сразу после создания/удаления список замечаний может быть
+ /// ещё прежним, поэтому ждём (до ~15 с), пока замечание появится или исчезнет.
+ ///
+ private async Task WaitForRemark(string docId, string id, bool present = true)
+ {
+ var all = await GetAnnotations(docId);
+ for (var i = 0; i < 30 && Contains(all, id) != present; i++)
+ {
+ await Task.Delay(500);
+ all = await GetAnnotations(docId);
+ }
+ return all;
+ }
+
+ private static JsonObject Remark(JsonArray all, string id)
+ => all.Select(n => n!.AsObject()).Single(o => o["id"]!.GetValue() == id);
+
+ private static void AssertBox(JsonObject shape, double x, double y, double w, double h)
+ {
+ Assert.InRange(shape["x"]!.GetValue(), x - 1, x + 1);
+ Assert.InRange(shape["y"]!.GetValue(), y - 1, y + 1);
+ Assert.InRange(shape["width"]!.GetValue(), w - 1, w + 1);
+ Assert.InRange(shape["height"]!.GetValue(), h - 1, h + 1);
+ }
+
+ [Fact]
+ public Task CreateAnnotation_Markup_RoundTripsThroughGetAnnotations() => WithCleanup(async created =>
+ {
+ var (docId, _) = await FindTestDocument();
+ var id = await CreateRemark("CreateAnnotation", new JsonObject
+ {
+ ["documentId"] = docId, ["shape"] = "rectangle", ["color"] = "blue",
+ ["x"] = 150, ["y"] = 200, ["width"] = 200, ["height"] = 100, ["page"] = 0,
+ ["content"] = "тест markup rectangle", ["strokeWidth"] = 3
+ }, created);
+
+ var remark = Remark(await WaitForRemark(docId, id), id);
+ Assert.Equal("markup", remark["format"]!.GetValue());
+ Assert.Equal("тест markup rectangle", remark["text"]!.GetValue());
+ Assert.True(remark["markupVersionIsCurrent"]!.GetValue());
+ Assert.False(string.IsNullOrEmpty(remark["creator"]!.GetValue()));
+ Assert.Null(remark["error"]);
+ var shape = Assert.Single(remark["shapes"]!.AsArray())!.AsObject();
+ Assert.Equal("Rectangle", shape["subtype"]!.GetValue());
+ Assert.Equal(0, shape["page"]!.GetValue());
+ AssertBox(shape, 150, 200, 200, 100);
+ Assert.Equal("#0000FF", shape["color"]!.GetValue());
+ Assert.Equal(3, shape["strokeWidth"]!.GetValue());
+
+ // На сервере: атрибуты нового формата и нет legacy-атрибута "annotation"
+ var obj = await _client.CallToolAsync("GetObject", new JsonObject { ["objectId"] = id });
+ obj.AssertOk();
+ Assert.Contains(" markups = ", obj.RawText);
+ Assert.Contains(" markups_version = ", obj.RawText);
+ Assert.DoesNotContain(" annotation = ", obj.RawText);
+ });
+
+ [Fact]
+ public Task CreateMarkupAnnotation_SeveralShapes_AreOneRemark() => WithCleanup(async created =>
+ {
+ var (docId, _) = await FindTestDocument();
+ var shapes = new JsonArray
+ {
+ new JsonObject { ["shape"] = "ellipse", ["x"] = 400, ["y"] = 400, ["width"] = 100, ["height"] = 60 },
+ new JsonObject { ["shape"] = "arrow", ["x"] = 300, ["y"] = 300, ["width"] = 120, ["height"] = 80, ["color"] = "black" },
+ new JsonObject { ["shape"] = "triangle", ["x"] = 100, ["y"] = 500, ["width"] = 80, ["height"] = 60 },
+ new JsonObject { ["shape"] = "polygon", ["points"] = "100,100;200,100;200,180;100,180", ["cloud"] = true },
+ new JsonObject { ["shape"] = "polyline", ["points"] = "50,50;80,90;120,60" },
+ new JsonObject { ["shape"] = "ink", ["points"] = "10,10;20,25;30,15;40,40" },
+ new JsonObject { ["shape"] = "point", ["x"] = 700, ["y"] = 700 },
+ };
+ var id = await CreateRemark("CreateMarkupAnnotation", new JsonObject
+ {
+ ["documentId"] = docId, ["shapesJson"] = shapes.ToJsonString(), ["content"] = "несколько фигур"
+ }, created);
+
+ var all = await WaitForRemark(docId, id);
+ Assert.Single(all, n => n!["id"]!.GetValue() == id);
+ var remark = Remark(all, id);
+ Assert.Equal("markup", remark["format"]!.GetValue());
+ var read = remark["shapes"]!.AsArray().Select(n => n!.AsObject()).ToList();
+ Assert.Equal(
+ new[] { "Ellipse", "Line", "Polygon", "Polygon", "Polyline", "Ink", "Text" },
+ read.Select(s => s["subtype"]!.GetValue()).ToArray());
+
+ AssertBox(read[0], 350, 370, 100, 60); // эллипс: (x, y) — центр
+ AssertBox(read[1], 300, 300, 120, 80); // стрелка: остриё (300,300), хвост (420,380)
+ AssertBox(read[3], 100, 100, 100, 80); // polygon
+ AssertBox(read[4], 50, 50, 70, 40); // polyline
+ Assert.Equal("#FF000000", read[1]["color"]!.GetValue()); // чёрный хранится с альфой, иначе 0 = прозрачный
+ });
+
+ [Theory]
+ [InlineData("highlight", "Highlight")]
+ [InlineData("underline", "Underline")]
+ [InlineData("strikeout", "StrikeOut")]
+ public Task AnnotateText_Markup_CreatesTextDecoration(string style, string subtype) => WithCleanup(async created =>
+ {
+ var (docId, word) = await FindTestDocument();
+ var id = await CreateRemark("AnnotateText", new JsonObject
+ {
+ ["documentId"] = docId, ["searchText"] = word, ["comment"] = $"тест {style}", ["page"] = 0, ["style"] = style
+ }, created);
+
+ var remark = Remark(await WaitForRemark(docId, id), id);
+ Assert.Equal("markup", remark["format"]!.GetValue());
+ Assert.Equal($"тест {style}", remark["text"]!.GetValue());
+ var shape = Assert.Single(remark["shapes"]!.AsArray())!.AsObject();
+ Assert.Equal(subtype, shape["subtype"]!.GetValue());
+ Assert.True(shape["width"]!.GetValue() > 0);
+ Assert.True(shape["height"]!.GetValue() > 0);
+ Assert.True(shape["y"]!.GetValue() >= 0);
+ });
+
+ [Fact]
+ public Task Legacy_Format_StillWorks() => WithCleanup(async created =>
+ {
+ var (docId, word) = await FindTestDocument();
+ var textId = await CreateRemark("AnnotateText", new JsonObject
+ {
+ ["documentId"] = docId, ["searchText"] = word, ["comment"] = "тест legacy text", ["page"] = 0, ["format"] = "legacy"
+ }, created);
+ var shapeId = await CreateRemark("CreateAnnotation", new JsonObject
+ {
+ ["documentId"] = docId, ["shape"] = "rectangle", ["color"] = "red",
+ ["x"] = 150, ["y"] = 150, ["width"] = 200, ["height"] = 100, ["page"] = 0,
+ ["content"] = "тест legacy rectangle", ["format"] = "legacy"
+ }, created);
+
+ await WaitForRemark(docId, textId);
+ var all = await WaitForRemark(docId, shapeId);
+ var text = Remark(all, textId);
+ Assert.Equal("legacy", text["format"]!.GetValue());
+ Assert.Equal("TextStickyNote", Assert.Single(text["shapes"]!.AsArray())!["kind"]!.GetValue());
+ var rect = Remark(all, shapeId);
+ Assert.Equal("legacy", rect["format"]!.GetValue());
+ Assert.Equal("RedPencil", Assert.Single(rect["shapes"]!.AsArray())!["kind"]!.GetValue());
+
+ var obj = await _client.CallToolAsync("GetObject", new JsonObject { ["objectId"] = shapeId });
+ Assert.Contains(" annotation = ", obj.RawText);
+ Assert.DoesNotContain(" markups = ", obj.RawText);
+ });
+
+ [Fact]
+ public Task GetAnnotations_SkipsRemarksInRecycleBin() => WithCleanup(async created =>
+ {
+ var (docId, _) = await FindTestDocument();
+ var id = await CreateRemark("CreateAnnotation", new JsonObject
+ {
+ ["documentId"] = docId, ["shape"] = "point", ["color"] = "red", ["x"] = 120, ["y"] = 120
+ }, created);
+ Assert.True(Contains(await WaitForRemark(docId, id), id));
+
+ (await _client.CallToolAsync("DeleteObject", new JsonObject { ["objectId"] = id })).AssertOk();
+ created.Remove(id); // уже в корзине
+ // Сравниваем по ID (а не по количеству): параллельно могут исчезать замечания других тестов.
+ Assert.DoesNotContain(id, Ids(await WaitForRemark(docId, id, present: false)));
+ });
+
+ [Fact]
+ public Task InvalidInput_ReturnsErrors() => WithCleanup(async created =>
+ {
+ var (docId, word) = await FindTestDocument();
+
+ async Task ExpectError(string tool, JsonObject args)
+ {
+ var result = await _client.CallToolAsync(tool, args, 60000);
+ result.AssertError();
+ // ошибка не должна оставлять замечание
+ var m = Regex.Match(result.Message, @"ID: ([0-9a-fA-F-]{36})");
+ if (m.Success) created.Add(m.Groups[1].Value);
+ }
+
+ Task ExpectShapes(string shapesJson)
+ => ExpectError("CreateMarkupAnnotation", new() { ["documentId"] = docId, ["shapesJson"] = shapesJson });
+
+ var before = Ids(await GetAnnotations(docId));
+
+ await ExpectShapes("не json");
+ await ExpectShapes("[]");
+ await ExpectShapes("[null]");
+ await ExpectShapes("[{\"shape\":\"hexagon\"}]");
+ await ExpectShapes("[{\"shape\":\"freetext\",\"width\":150,\"height\":40}]");
+ await ExpectShapes("[{\"shape\":\"rectangle\",\"colour\":\"red\"}]");
+ await ExpectShapes("[{\"shape\":\"rectangle\",\"fillColor\":\"yellow\"}]");
+ await ExpectShapes("[{\"shape\":\"rectangle\",\"lineStyle\":\"dashed\"}]");
+ await ExpectShapes("[{\"shape\":\"rectangle\",\"text\":\"t\"}]");
+ await ExpectShapes("[{\"shape\":\"polygon\",\"points\":\"1,1;2,2\"}]");
+ await ExpectShapes("[{\"shape\":\"polyline\",\"points\":\"1,1;a,b\"}]");
+ await ExpectShapes("[{\"shape\":\"rectangle\",\"cloud\":true}]");
+ await ExpectShapes("[{\"shape\":\"arrow\",\"endEnding\":\"closedarrow\"}]");
+ await ExpectShapes("[{\"shape\":\"rectangle\",\"color\":\"notacolor\"}]");
+ await ExpectShapes("[{\"shape\":\"rectangle\",\"color\":\"#GGGGGG\"}]");
+ await ExpectShapes("[{\"shape\":\"rectangle\",\"width\":0}]");
+ await ExpectShapes("[{\"shape\":null}]");
+ await ExpectShapes("[{\"shape\":\"polygon\",\"points\":null}]");
+ await ExpectShapes("[{\"shape\":\"rectangle\",\"page\":9999}]");
+ await ExpectError("CreateMarkupAnnotation", new() { ["documentId"] = Guid.NewGuid().ToString(), ["shapesJson"] = "[{\"shape\":\"rectangle\"}]" });
+ await ExpectError("CreateMarkupAnnotation", new() { ["documentId"] = "не-guid", ["shapesJson"] = "[{\"shape\":\"rectangle\"}]" });
+
+ await ExpectError("CreateAnnotation", new() { ["documentId"] = docId, ["shape"] = "rectangle", ["color"] = "red", ["x"] = 1, ["y"] = 1, ["format"] = "xml" });
+ await ExpectError("CreateAnnotation", new() { ["documentId"] = docId, ["shape"] = "freetext", ["color"] = "red", ["x"] = 1, ["y"] = 1 });
+ await ExpectError("CreateAnnotation", new() { ["documentId"] = docId, ["shape"] = "arrow", ["color"] = "red", ["x"] = 1, ["y"] = 1, ["endEnding"] = "closedarrow" });
+ await ExpectError("CreateAnnotation", new() { ["documentId"] = docId, ["shape"] = "polygon", ["color"] = "red", ["x"] = 1, ["y"] = 1, ["points"] = "1,1;2,2;3,1", ["format"] = "legacy" });
+ await ExpectError("AnnotateText", new() { ["documentId"] = docId, ["searchText"] = word, ["comment"] = "c", ["page"] = 0, ["style"] = "bold" });
+ await ExpectError("AnnotateText", new() { ["documentId"] = docId, ["searchText"] = word, ["comment"] = "c", ["page"] = 0, ["color"] = "notacolor" });
+ await ExpectError("AnnotateText", new() { ["documentId"] = docId, ["searchText"] = "x", ["comment"] = "c", ["format"] = "xml" });
+ await ExpectError("GetAnnotations", new() { ["documentId"] = Guid.NewGuid().ToString() });
+ await ExpectError("GetAnnotations", new() { ["documentId"] = "не-guid" });
+
+ // Новых замечаний не появилось (исчезнуть могут только удалённые другими тестами).
+ Assert.Empty(Ids(await GetAnnotations(docId)).Except(before));
+ });
+}
diff --git a/PilotMCP.Tests/CoreInfrastructureTests.cs b/PilotMCP.Tests/CoreInfrastructureTests.cs
new file mode 100644
index 0000000..d9c0224
--- /dev/null
+++ b/PilotMCP.Tests/CoreInfrastructureTests.cs
@@ -0,0 +1,220 @@
+using Ascon.Pilot.DataClasses;
+using Ascon.Pilot.Server.Api.Contracts;
+using Ascon.Pilot.Transport;
+using PilotMCP;
+
+namespace PilotMCP.Tests;
+
+/// Чистые unit-тесты инфраструктуры (FormatDValue, ParseAttributes, DownloadToFile, ReconnectingProxy) без сервера.
+public class CoreInfrastructureTests
+{
+ // ---- FormatDValue ----
+
+ [Fact]
+ public void FormatDValue_ShowsEveryValueKind()
+ {
+ Assert.Equal("5", Helpers.FormatDValue(new DValue { IntValue = 5 }));
+ Assert.Equal("0", Helpers.FormatDValue(new DValue { IntValue = 0 }));
+ Assert.Equal("2.5", Helpers.FormatDValue(new DValue { DoubleValue = 2.5 }));
+ Assert.Equal("3", Helpers.FormatDValue(new DValue { DecimalValue = 3m }));
+ Assert.Equal("a, b", Helpers.FormatDValue(new DValue { ArrayValue = new[] { "a", "b" } }));
+ Assert.Equal("1, 2", Helpers.FormatDValue(new DValue { ArrayIntValue = new[] { 1, 2 } }));
+ var g = Guid.NewGuid();
+ Assert.Equal(g.ToString(), Helpers.FormatDValue(new DValue { GuidValue = g }));
+ Assert.Equal("text", Helpers.FormatDValue(new DValue { StrValue = "text" }));
+ Assert.Equal("", Helpers.FormatDValue(new DValue()));
+ Assert.Equal("", Helpers.FormatDValue(null));
+ }
+
+ [Fact]
+ public void FormatDValue_DoubleIsCultureInvariant()
+ {
+ var old = System.Globalization.CultureInfo.CurrentCulture;
+ try
+ {
+ System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("ru-RU");
+ Assert.Equal("1.5", Helpers.FormatDValue(new DValue { DoubleValue = 1.5 }));
+ }
+ finally { System.Globalization.CultureInfo.CurrentCulture = old; }
+ }
+
+ // ---- ParseAttributes ----
+
+ [Fact]
+ public void ParseAttributes_MapsKindsAndSkipsNull()
+ {
+ var d = Helpers.ParseAttributes("""{"s":"x","i":7,"f":1.5,"b":true,"n":null,"ints":[1,2],"strs":["a","b"]}""")!;
+ Assert.Equal("x", d["s"].StrValue);
+ Assert.Equal(7, d["i"].IntValue);
+ Assert.Equal(1.5, d["f"].DoubleValue);
+ Assert.Equal(1, d["b"].IntValue);
+ Assert.False(d.ContainsKey("n"));
+ Assert.Equal(new[] { 1, 2 }, d["ints"].ArrayIntValue);
+ Assert.Equal(new[] { "a", "b" }, d["strs"].ArrayValue);
+ }
+
+ [Fact]
+ public void ParseAttributes_EmptyInput_ReturnsNull()
+ {
+ Assert.Null(Helpers.ParseAttributes(""));
+ Assert.Null(Helpers.ParseAttributes(" "));
+ }
+
+ [Theory]
+ [InlineData("{bad json")]
+ [InlineData("[1,2]")]
+ [InlineData("""{"a":{"x":1}}""")]
+ [InlineData("""{"a":[1,"x"]}""")]
+ [InlineData("""{"a":[]}""")]
+ public void ParseAttributes_InvalidInput_Throws(string json)
+ => Assert.Throws(() => Helpers.ParseAttributes(json));
+
+ // ---- DownloadToFile ----
+
+ private sealed class FakeFileApi : IFileArchiveApi
+ {
+ public Func Chunk = _ => null;
+ public byte[] GetFileChunk(Guid id, long pos, int count) => Chunk(pos)!;
+ public void PutFileChunk(Guid id, byte[] buffer, long pos) => throw new NotSupportedException();
+ public void PutFileChunk(Guid id, byte[] buffer, long pos, bool isLast) => throw new NotSupportedException();
+ public long GetFilePosition(Guid id) => throw new NotSupportedException();
+ [Obsolete]
+ public void PutFileInArchive(DFileBody fileBody) => throw new NotSupportedException();
+ public (Guid ListId, int FileCount) PrepareFileList() => throw new NotSupportedException();
+ public IEnumerable<(Guid fileId, Guid objectId)> EnumerateFileList(Guid listId, int offset, int count) => throw new NotSupportedException();
+ public void CloseFileList(Guid listId) => throw new NotSupportedException();
+ }
+
+ private static string TempFile() => Path.Combine(Path.GetTempPath(), "pilotmcp-test-" + Guid.NewGuid().ToString("N"));
+
+ [Fact]
+ public void DownloadToFile_Success_ReplacesTargetAndLeavesNoPart()
+ {
+ var path = TempFile();
+ try
+ {
+ File.WriteAllText(path, "old");
+ var api = new FakeFileApi { Chunk = pos => pos == 0 ? new byte[] { 1, 2, 3 } : null };
+ Assert.Equal(3, Helpers.DownloadToFile(api, Guid.NewGuid(), path));
+ Assert.Equal(new byte[] { 1, 2, 3 }, File.ReadAllBytes(path));
+ Assert.False(File.Exists(path + ".part"));
+ }
+ finally { File.Delete(path); File.Delete(path + ".part"); }
+ }
+
+ [Fact]
+ public void DownloadToFile_ServerFails_KeepsExistingFile()
+ {
+ var path = TempFile();
+ try
+ {
+ File.WriteAllText(path, "PRECIOUS");
+ var api = new FakeFileApi { Chunk = _ => throw new InvalidOperationException("boom") };
+ Assert.Throws(() => Helpers.DownloadToFile(api, Guid.NewGuid(), path));
+ Assert.Equal("PRECIOUS", File.ReadAllText(path));
+ Assert.False(File.Exists(path + ".part"));
+ }
+ finally { File.Delete(path); File.Delete(path + ".part"); }
+ }
+
+ [Fact]
+ public void DownloadToFile_EmptyContent_IsErrorAndKeepsExistingFile()
+ {
+ var path = TempFile();
+ try
+ {
+ File.WriteAllText(path, "PRECIOUS");
+ var api = new FakeFileApi { Chunk = _ => Array.Empty() };
+ Assert.Throws(() => Helpers.DownloadToFile(api, Guid.NewGuid(), path));
+ Assert.Equal("PRECIOUS", File.ReadAllText(path));
+ }
+ finally { File.Delete(path); File.Delete(path + ".part"); }
+ }
+
+ // ---- ReconnectingProxy ----
+
+ public interface IFakeApi
+ {
+ int GetValue();
+ void SendMessage();
+ Task GetValueAsync();
+ Task SendMessageAsync();
+ }
+
+ private sealed class FakeApi : IFakeApi
+ {
+ public Func FailOnCall = _ => null; // по номеру вызова (с 1)
+ public int Calls;
+
+ private void Step()
+ {
+ var ex = FailOnCall(++Calls);
+ if (ex != null) throw ex;
+ }
+
+ public int GetValue() { Step(); return 42; }
+ public void SendMessage() => Step();
+ public async Task GetValueAsync() { await Task.Yield(); Step(); return 42; }
+ public async Task SendMessageAsync() { await Task.Yield(); Step(); }
+ }
+
+ private static (IFakeApi Proxy, FakeApi Target, Func Restores) MakeProxy(Func fail)
+ {
+ var target = new FakeApi { FailOnCall = fail };
+ var restores = 0;
+ var proxy = ReconnectingProxy.Create(target, () => target, () => restores++, () => false);
+ return (proxy, target, () => restores);
+ }
+
+ [Fact]
+ public void Proxy_ReadAfterTransportError_ReconnectsAndRetries()
+ {
+ var (proxy, target, restores) = MakeProxy(n => n == 1 ? new TransportException("Canceled by transport") : null);
+ Assert.Equal(42, proxy.GetValue());
+ Assert.Equal(2, target.Calls);
+ Assert.Equal(1, restores());
+ }
+
+ [Fact]
+ public void Proxy_WriteAfterTimeout_ReconnectsButIsNotReplayed()
+ {
+ var (proxy, target, restores) = MakeProxy(_ => new TimeoutException("slow"));
+ Assert.Throws(() => proxy.SendMessage());
+ Assert.Equal(1, target.Calls);
+ Assert.Equal(1, restores());
+ }
+
+ [Fact]
+ public async Task Proxy_AsyncWriteAfterTransportError_IsNotReplayed()
+ {
+ var (proxy, target, _) = MakeProxy(_ => new TransportException("Canceled by transport"));
+ await Assert.ThrowsAsync(() => proxy.SendMessageAsync());
+ Assert.Equal(1, target.Calls);
+ }
+
+ [Fact]
+ public async Task Proxy_AsyncReadAfterTransportError_Retries()
+ {
+ var (proxy, target, _) = MakeProxy(n => n == 1 ? new TransportException("Transport closed") : null);
+ Assert.Equal(42, await proxy.GetValueAsync());
+ Assert.Equal(2, target.Calls);
+ }
+
+ [Fact]
+ public void Proxy_WriteOnDisposedTarget_IsReplayed()
+ {
+ var (proxy, target, _) = MakeProxy(n => n == 1 ? new ObjectDisposedException("TransportClient") : null);
+ proxy.SendMessage();
+ Assert.Equal(2, target.Calls);
+ }
+
+ [Fact]
+ public void Proxy_NonTransportError_IsUnwrappedFromTargetInvocationException()
+ {
+ var (proxy, target, restores) = MakeProxy(_ => new InvalidOperationException("access denied"));
+ var ex = Assert.Throws(() => proxy.GetValue());
+ Assert.Equal("access denied", ex.Message);
+ Assert.Equal(1, target.Calls);
+ Assert.Equal(0, restores());
+ }
+}
diff --git a/PilotMCP.Tests/DataPipeToolsTests.cs b/PilotMCP.Tests/DataPipeToolsTests.cs
index d88a833..04651b7 100644
--- a/PilotMCP.Tests/DataPipeToolsTests.cs
+++ b/PilotMCP.Tests/DataPipeToolsTests.cs
@@ -3,6 +3,7 @@
namespace PilotMCP.Tests;
[Collection("Pilot")]
+[Trait("Category", "Integration")]
public class DataPipeToolsTests
{
private readonly McpTestClient _client;
@@ -107,4 +108,88 @@ public async Task ExportCsv_WritesFile()
File.Delete(csvPath);
}
}
+
+ private static string TempJsonl(params string[] lines)
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"pipe_{Guid.NewGuid():N}.jsonl");
+ File.WriteAllLines(path, lines);
+ return path;
+ }
+
+ [Fact]
+ public async Task Writers_SameInputAndOutput_ReturnErrorAndKeepInput()
+ {
+ var input = TempJsonl("{\"a\":1,\"b\":\"x\"}", "{\"a\":2,\"b\":\"y\"}");
+ var before = File.ReadAllText(input);
+ try
+ {
+ foreach (var (tool, extra) in new[]
+ {
+ ("ExtractFields", new JsonObject { ["fields"] = "a" }),
+ ("FilterObjects", new JsonObject { ["field"] = "a", ["value"] = "1" }),
+ ("ExtractFieldToText", new JsonObject { ["field"] = "a" }),
+ ("ExportCsv", new JsonObject()),
+ })
+ {
+ extra["inputFile"] = input;
+ extra["outputFile"] = input;
+ (await _client.CallToolAsync(tool, extra)).AssertError();
+ Assert.Equal(before, File.ReadAllText(input));
+ }
+ }
+ finally { File.Delete(input); }
+ }
+
+ [Fact]
+ public async Task ExportCsv_UnionOfKeysAndQuotedHeader_AndNewOutputDir()
+ {
+ var input = TempJsonl("{\"a\":1}", "{\"a\":2,\"b;c\":\"x\\ry\"}");
+ var dir = Path.Combine(Path.GetTempPath(), $"csv_{Guid.NewGuid():N}");
+ var output = Path.Combine(dir, "out.csv");
+ try
+ {
+ (await _client.CallToolAsync("ExportCsv", new JsonObject { ["inputFile"] = input, ["outputFile"] = output })).AssertOk();
+ var text = File.ReadAllText(output);
+ Assert.Contains("a;\"b;c\"", text);
+ Assert.Contains("2;\"x\ry\"", text);
+ }
+ finally
+ {
+ File.Delete(input);
+ if (Directory.Exists(dir)) Directory.Delete(dir, true);
+ }
+ }
+
+ [Fact]
+ public async Task ExtractFields_NotJsonl_ReturnsErrorAndNoOutputFile()
+ {
+ var input = Path.Combine(Path.GetTempPath(), $"notjsonl_{Guid.NewGuid():N}.txt");
+ var output = Path.Combine(Path.GetTempPath(), $"notjsonl_out_{Guid.NewGuid():N}.jsonl");
+ File.WriteAllText(input, "plain text, not json");
+ try
+ {
+ (await _client.CallToolAsync("ExtractFields", new JsonObject
+ { ["inputFile"] = input, ["fields"] = "a", ["outputFile"] = output })).AssertError();
+ Assert.False(File.Exists(output));
+ }
+ finally { File.Delete(input); }
+ }
+
+ [Fact]
+ public async Task ReadFileAndPreviewFile_NegativeOffsets_AreClamped()
+ {
+ var input = TempJsonl("{\"a\":1}", "{\"a\":2}");
+ try
+ {
+ var read = await _client.CallToolAsync("ReadFile", new JsonObject { ["filePath"] = input, ["offset"] = -5 });
+ read.AssertOk();
+ Assert.Contains("\"a\":1", read.Message);
+ var preview = await _client.CallToolAsync("PreviewFile", new JsonObject { ["inputFile"] = input, ["skip"] = -3, ["take"] = 1 });
+ Assert.False(preview.IsError);
+ Assert.Contains("Показано 1", preview.RawText);
+ var past = await _client.CallToolAsync("PreviewFile", new JsonObject { ["inputFile"] = input, ["skip"] = 50 });
+ Assert.Contains("за пределами", past.RawText);
+ }
+ finally { File.Delete(input); }
+ }
}
diff --git a/PilotMCP.Tests/DocumentToolsTests.cs b/PilotMCP.Tests/DocumentToolsTests.cs
index c06f0e2..f32b210 100644
--- a/PilotMCP.Tests/DocumentToolsTests.cs
+++ b/PilotMCP.Tests/DocumentToolsTests.cs
@@ -3,6 +3,7 @@
namespace PilotMCP.Tests;
[Collection("Pilot")]
+[Trait("Category", "Integration")]
public class DocumentToolsTests
{
private readonly McpTestClient _client;
@@ -35,6 +36,33 @@ public async Task ExtractPageText_WithInvalidId_ReturnsError()
result.AssertError();
}
+ [Fact]
+ public async Task FindTextOnPage_WithEmptyText_ReturnsError()
+ {
+ var result = await _client.CallToolAsync("FindTextOnPage", new JsonObject
+ {
+ ["documentId"] = Guid.NewGuid().ToString(),
+ ["searchText"] = ""
+ });
+
+ result.AssertError();
+ Assert.Contains("пустым", result.Message, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(10000)]
+ public async Task GetDocumentPageImage_WithDpiOutOfRange_ReturnsError(int dpi)
+ {
+ var result = await _client.CallToolAsync("GetDocumentPageImage", new JsonObject
+ {
+ ["documentId"] = Guid.NewGuid().ToString(),
+ ["dpi"] = dpi
+ });
+
+ Assert.Contains("dpi должен быть", result.Message, StringComparison.OrdinalIgnoreCase);
+ }
+
[Fact]
public async Task GetDocumentPageImage_WithInvalidId_ReturnsError()
{
diff --git a/PilotMCP.Tests/MarkupBuilderTests.cs b/PilotMCP.Tests/MarkupBuilderTests.cs
new file mode 100644
index 0000000..0c64644
--- /dev/null
+++ b/PilotMCP.Tests/MarkupBuilderTests.cs
@@ -0,0 +1,156 @@
+using Ascon.Pilot.DataClasses.Markups;
+
+namespace PilotMCP.Tests;
+
+/// Чистые unit-тесты MarkupBuilder (без сервера): ожидаемые числа посчитаны вручную.
+public class MarkupBuilderTests
+{
+ // Страница высотой 1000 DIP, 96 dpi: 1 пиксель = 1 DIP = 0.75 pt; Y в Markup направлена вверх.
+ private const double PageH = 1000;
+
+ private static ShapeSpec Spec(string shape, Action? tune = null)
+ {
+ var s = new ShapeSpec { Shape = shape };
+ tune?.Invoke(s);
+ return s;
+ }
+
+ [Fact]
+ public void Rectangle_ConvertsPixelsToPointsWithFlippedY()
+ {
+ var m = Assert.IsType(MarkupBuilder.Build(7, Spec("rectangle", s =>
+ {
+ s.X = 96; s.Y = 96; s.Width = 96; s.Height = 48; s.Page = 2; s.Color = "red";
+ }), 96, PageH));
+
+ Assert.Equal(7, m.Id);
+ Assert.Equal(3, m.Page); // страница с 0 → Markup.Page с 1
+ Assert.Equal(72f, m.Bounds.X);
+ Assert.Equal(678f, m.Bounds.Y); // (1000 - 96) * 0.75
+ Assert.Equal(72f, m.Bounds.Width);
+ Assert.Equal(-36f, m.Bounds.Height); // клиент хранит прямоугольник с отрицательной высотой
+ Assert.Equal(0xFF0000, m.Style.ColorRgb);
+ }
+
+ [Fact]
+ public void Rectangle_ScalesByDpi()
+ {
+ // 192 dpi: 192 px = 96 DIP = 72 pt
+ var m = Assert.IsType(MarkupBuilder.Build(1, Spec("rectangle", s =>
+ {
+ s.X = 192; s.Y = 192; s.Width = 192; s.Height = 96;
+ }), 192, PageH));
+ Assert.Equal(72f, m.Bounds.X);
+ Assert.Equal(678f, m.Bounds.Y);
+ Assert.Equal(72f, m.Bounds.Width);
+ Assert.Equal(-36f, m.Bounds.Height);
+ }
+
+ [Fact]
+ public void BlackColor_IsStoredWithAlpha()
+ {
+ var m = MarkupBuilder.Build(1, Spec("point", s => s.Color = "black"), 96, PageH);
+ Assert.Equal(unchecked((int)0xFF000000), m.Style.ColorRgb);
+ }
+
+ [Theory]
+ [InlineData("#FF0000", 0xFF0000)]
+ [InlineData("#00ff00", 0x00FF00)]
+ [InlineData("#80FF0000", unchecked((int)0x80FF0000))]
+ [InlineData("#00FF0000", 0)] // нулевая альфа: клиент считает прозрачным только 0
+ public void ParseColor_AcceptsHex(string color, int expected) => Assert.Equal(expected, MarkupBuilder.ParseColor(color));
+
+ [Theory]
+ [InlineData("notacolor")]
+ [InlineData("")]
+ [InlineData("#12")]
+ [InlineData("#GGGGGG")]
+ [InlineData("#FF00")]
+ public void ParseColor_RejectsUnknown(string color) => Assert.Throws(() => MarkupBuilder.ParseColor(color));
+
+ [Theory]
+ [InlineData(0, "transparent")]
+ [InlineData(0xFF0000, "#FF0000")]
+ [InlineData(unchecked((int)0xFF000000), "#FF000000")]
+ [InlineData(unchecked((int)0x80FF0000), "#80FF0000")]
+ public void FormatColor_Formats(int color, string expected) => Assert.Equal(expected, MarkupBuilder.FormatColor(color));
+
+ [Fact]
+ public void TextDecoration_QuadOrderIsTopLeftTopRightBottomRightBottomLeft()
+ {
+ var m = Assert.IsType(
+ MarkupBuilder.TextDecoration(1, 0, 96, 100, 200, 20, "highlight", "black", PageH));
+
+ Assert.Equal(1, m.Page);
+ Assert.Equal(unchecked((int)0xFF000000), m.Style.ColorRgb);
+ var q = m.QuadPoints.ToArray();
+ Assert.Equal(4, q.Length);
+ Assert.Equal((72f, 675f), (q[0].X, q[0].Y)); // TL: (1000 - 100) * 0.75
+ Assert.Equal((222f, 675f), (q[1].X, q[1].Y)); // TR
+ Assert.Equal((222f, 660f), (q[2].X, q[2].Y)); // BR: (1000 - 120) * 0.75
+ Assert.Equal((72f, 660f), (q[3].X, q[3].Y)); // BL
+ }
+
+ [Theory]
+ [InlineData("bold")]
+ [InlineData("squiggly")] // список замечаний клиента 26.20 падает на Squiggly
+ public void TextDecoration_UnsupportedStyle_Throws(string style)
+ => Assert.Throws(() => MarkupBuilder.TextDecoration(1, 0, 0, 0, 10, 10, style, "red", PageH));
+
+ [Fact]
+ public void Arrow_HasOpenArrowAtTip()
+ {
+ var m = Assert.IsType(MarkupBuilder.Build(1, Spec("arrow", s =>
+ {
+ s.X = 96; s.Y = 96; s.Width = 96; s.Height = 0;
+ }), 96, PageH));
+ Assert.Equal(MarkupLineEndings.OpenArrow, m.EndEnding);
+ Assert.Equal(MarkupLineEndings.None, m.StartEnding);
+ }
+
+ [Theory]
+ [InlineData("freetext")]
+ [InlineData("hexagon")]
+ [InlineData("")]
+ public void UnsupportedShape_Throws(string shape)
+ => Assert.Throws(() => MarkupBuilder.Build(1, Spec(shape), 96, PageH));
+
+ [Theory]
+ [InlineData("closedarrow")]
+ [InlineData("circle")]
+ [InlineData("square")]
+ [InlineData("diamond")]
+ public void UnsupportedEnding_Throws(string ending)
+ => Assert.Throws(() => MarkupBuilder.Build(1, Spec("arrow", s => s.EndEnding = ending), 96, PageH));
+
+ [Fact]
+ public void NullStrings_BecomeDefaultsOrArgumentException()
+ {
+ var m = MarkupBuilder.Build(1, Spec("rectangle", s =>
+ {
+ s.Color = null!; s.Points = null!; s.StartEnding = null!; s.EndEnding = null!;
+ }), 96, PageH);
+ Assert.Equal(0xFF0000, m.Style.ColorRgb); // красный по умолчанию
+
+ Assert.Throws(() => MarkupBuilder.Build(1, new ShapeSpec { Shape = null! }, 96, PageH));
+ Assert.Throws(() => MarkupBuilder.Build(1, Spec("polygon", s => s.Points = null!), 96, PageH));
+ }
+
+ [Theory]
+ [InlineData("rectangle")]
+ [InlineData("ellipse")]
+ [InlineData("triangle")]
+ public void NonPositiveSize_Throws(string shape)
+ {
+ Assert.Throws(() => MarkupBuilder.Build(1, Spec(shape, s => s.Width = 0), 96, PageH));
+ Assert.Throws(() => MarkupBuilder.Build(1, Spec(shape, s => s.Height = -5), 96, PageH));
+ }
+
+ [Fact]
+ public void NonFiniteNumbers_Throw()
+ {
+ Assert.Throws(() => MarkupBuilder.Build(1, Spec("point", s => s.X = double.NaN), 96, PageH));
+ Assert.Throws(() => MarkupBuilder.Build(1, Spec("point", s => s.StrokeWidth = double.PositiveInfinity), 96, PageH));
+ Assert.Throws(() => MarkupBuilder.Build(1, Spec("polyline", s => s.Points = "1,1;NaN,2"), 96, PageH));
+ }
+}
diff --git a/PilotMCP.Tests/MessageHelpersTests.cs b/PilotMCP.Tests/MessageHelpersTests.cs
new file mode 100644
index 0000000..41a5152
--- /dev/null
+++ b/PilotMCP.Tests/MessageHelpersTests.cs
@@ -0,0 +1,58 @@
+using Ascon.Pilot.DataClasses;
+using static Ascon.Pilot.Common.DMessageExtensions;
+
+namespace PilotMCP.Tests;
+
+/// Чистые unit-тесты MessageHelpers (без сервера).
+public class MessageHelpersTests
+{
+ private static DMessage Text(string text, bool markdown, MessageType type = MessageType.TextMessage, DateTime? server = null)
+ {
+ var m = new DMessage { Id = Guid.NewGuid(), Type = type, ServerDate = server, LocalDate = server ?? DateTime.UtcNow };
+ m.SetTextData(new DTextMessageData { Text = text, IsMarkdown = markdown });
+ return m;
+ }
+
+ [Fact]
+ public void FormatText_PlainText_ReturnedAsIs()
+ => Assert.Equal("hello", MessageHelpers.FormatText(Text("hello", false)));
+
+ [Fact]
+ public void FormatText_Markdown_IsFlagged()
+ => Assert.Equal("**b** [markdown]", MessageHelpers.FormatText(Text("**b**", true)));
+
+ [Fact]
+ public void FormatText_UsesLatestEditAndMarksIt()
+ {
+ var m = Text("old", false);
+ var t0 = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+ m.RelatedMessages.Add(Text("second", false, MessageType.EditTextMessage, t0.AddMinutes(2)));
+ m.RelatedMessages.Add(Text("first", false, MessageType.EditTextMessage, t0.AddMinutes(1)));
+
+ Assert.Equal("second (ред.)", MessageHelpers.FormatText(m));
+ }
+
+ [Fact]
+ public void FormatText_NonTextMessage_ShowsType()
+ => Assert.Equal("[ChatCreation]", MessageHelpers.FormatText(new DMessage { Type = MessageType.ChatCreation, Data = new byte[] { 1 } }));
+
+ [Fact]
+ public void TryParseGuids_RejectsAnyBadItem()
+ {
+ var g = Guid.NewGuid();
+ Assert.True(MessageHelpers.TryParseGuids($"{g}, ", out var ok, out _));
+ Assert.Equal(new[] { g }, ok);
+ Assert.False(MessageHelpers.TryParseGuids($"{g},zzz", out _, out var bad));
+ Assert.Equal("zzz", bad);
+ }
+
+ [Fact]
+ public void TryParseDeadline_IsEndOfLocalDay_AndStrictFormat()
+ {
+ Assert.True(MessageHelpers.TryParseDeadline("2026-12-01", out var utc));
+ var local = utc.ToLocalTime();
+ Assert.Equal(new DateTime(2026, 12, 1, 23, 59, 59), local);
+ Assert.False(MessageHelpers.TryParseDeadline("01.12.2026", out _));
+ Assert.False(MessageHelpers.TryParseDeadline("12/01/2026", out _));
+ }
+}
diff --git a/PilotMCP.Tests/MessengerToolsTests.cs b/PilotMCP.Tests/MessengerToolsTests.cs
index f16da8f..445ff25 100644
--- a/PilotMCP.Tests/MessengerToolsTests.cs
+++ b/PilotMCP.Tests/MessengerToolsTests.cs
@@ -3,6 +3,7 @@
namespace PilotMCP.Tests;
[Collection("Pilot")]
+[Trait("Category", "Integration")]
public class MessengerToolsTests
{
private readonly McpTestClient _client;
@@ -20,16 +21,63 @@ public async Task GetChats_ReturnsChats()
}
[Fact]
- public async Task GetChat_WithInvalidId_ReturnsResult()
+ public async Task GetChat_WithUnknownId_ReturnsError()
{
- // Pilot returns an empty/default chat for unknown IDs, not an error
- var randomId = Guid.NewGuid().ToString();
var result = await _client.CallToolAsync("GetChat", new JsonObject
{
- ["chatId"] = randomId
+ ["chatId"] = Guid.NewGuid().ToString()
+ });
+
+ result.AssertError();
+ }
+
+ [Fact]
+ public async Task GetPersonalChat_WithoutChat_ReturnsErrorOrChat()
+ {
+ // чата может не быть (тогда ошибка), но нулевой GUID как «успех» отдаваться не должен
+ var result = await _client.CallToolAsync("GetPersonalChat", new JsonObject { ["personId"] = 999999 });
+
+ if (!result.IsError)
+ Assert.DoesNotContain("00000000-0000-0000-0000-000000000000", result.RawText);
+ }
+
+ [Fact]
+ public async Task SearchMessages_WithInvalidChatGuid_ReturnsError()
+ {
+ var result = await _client.CallToolAsync("SearchMessages", new JsonObject
+ {
+ ["query"] = "test",
+ ["chatIds"] = "not-a-guid"
+ });
+
+ result.AssertError();
+ }
+
+ [Fact]
+ public async Task GetMessages_WithNegativeSkip_ReturnsError()
+ {
+ var result = await _client.CallToolAsync("GetMessages", new JsonObject
+ {
+ ["chatId"] = Guid.NewGuid().ToString(),
+ ["skip"] = -1
+ });
+
+ result.AssertError();
+ }
+
+ [Theory]
+ [InlineData("deadline", "01.12.2026")]
+ [InlineData("attachmentIds", "not-a-guid")]
+ [InlineData("attributes", "{name: x}")]
+ public async Task CreateTask_WithInvalidArguments_ReturnsError(string param, string value)
+ {
+ var result = await _client.CallToolAsync("CreateTask", new JsonObject
+ {
+ ["typeName"] = "task_simple",
+ [param] = value
});
- Assert.False(result.IsError);
+ result.AssertError();
}
[Fact]
diff --git a/PilotMCP.Tests/MetadataAdminToolsTests.cs b/PilotMCP.Tests/MetadataAdminToolsTests.cs
index 733d184..15b7f4e 100644
--- a/PilotMCP.Tests/MetadataAdminToolsTests.cs
+++ b/PilotMCP.Tests/MetadataAdminToolsTests.cs
@@ -9,6 +9,7 @@ namespace PilotMCP.Tests;
/// Если админ-авторизация недоступна — тесты логируют причину и мягко пропускаются.
///
[Collection("Pilot")]
+[Trait("Category", "Integration")]
public class MetadataAdminToolsTests
{
private readonly McpTestClient _client;
diff --git a/PilotMCP.Tests/MiscToolsTests.cs b/PilotMCP.Tests/MiscToolsTests.cs
index b997e2c..c55bbff 100644
--- a/PilotMCP.Tests/MiscToolsTests.cs
+++ b/PilotMCP.Tests/MiscToolsTests.cs
@@ -3,6 +3,7 @@
namespace PilotMCP.Tests;
[Collection("Pilot")]
+[Trait("Category", "Integration")]
public class MiscToolsTests
{
private readonly McpTestClient _client;
@@ -73,6 +74,18 @@ public async Task GetChangesets_ReturnsChangesets()
result.AssertOk();
}
+ [Fact]
+ public async Task GetChangesets_TooWideRange_ReturnsError()
+ {
+ var result = await _client.CallToolAsync("GetChangesets", new JsonObject
+ {
+ ["first"] = 1,
+ ["last"] = 100000
+ });
+
+ result.AssertError();
+ }
+
// ── PeopleTools ──
[Fact]
diff --git a/PilotMCP.Tests/ObjectHelpersTests.cs b/PilotMCP.Tests/ObjectHelpersTests.cs
new file mode 100644
index 0000000..d8c4e7f
--- /dev/null
+++ b/PilotMCP.Tests/ObjectHelpersTests.cs
@@ -0,0 +1,111 @@
+using Ascon.Pilot.DataClasses;
+using Ascon.Pilot.Server.Api.Contracts;
+
+namespace PilotMCP.Tests;
+
+/// Чистые unit-тесты BuildTypedValue и MeasureArchiveFile (без сервера).
+public class ObjectHelpersTests
+{
+ private static MAttribute Attr(MAttrType t) => new() { Name = "a", Type = t };
+
+ [Fact]
+ public void BuildTypedValue_Integer_UsesLongValue()
+ {
+ var v = Helpers.BuildTypedValue(Attr(MAttrType.Integer), " 42 ");
+ Assert.Equal(42L, v.IntValue);
+ Assert.Null(v.StrValue);
+ }
+
+ [Fact]
+ public void BuildTypedValue_DoubleAndDecimal_UseInvariantCulture()
+ {
+ Assert.Equal(12.5, Helpers.BuildTypedValue(Attr(MAttrType.Double), "12.5").DoubleValue);
+ Assert.Equal(3.25m, Helpers.BuildTypedValue(Attr(MAttrType.Decimal), "3.25").DecimalValue);
+ }
+
+ [Fact]
+ public void BuildTypedValue_DateTime_IsUtc()
+ {
+ var d = Helpers.BuildTypedValue(Attr(MAttrType.DateTime), "2025-01-31T10:00:00Z").DateValue!.Value;
+ Assert.Equal(new DateTime(2025, 1, 31, 10, 0, 0, DateTimeKind.Utc), d);
+ Assert.Equal(DateTimeKind.Utc, d.Kind);
+ }
+
+ [Fact]
+ public void BuildTypedValue_Boolean_AcceptsWordsAndDigits()
+ {
+ Assert.Equal(1L, Helpers.BuildTypedValue(Attr(MAttrType.Boolean), "true").IntValue);
+ Assert.Equal(0L, Helpers.BuildTypedValue(Attr(MAttrType.Boolean), "0").IntValue);
+ Assert.Throws(() => Helpers.BuildTypedValue(Attr(MAttrType.Boolean), "maybe"));
+ }
+
+ [Fact]
+ public void BuildTypedValue_UserStateOrgUnitArray()
+ {
+ var id = Guid.NewGuid();
+ Assert.Equal(id, Helpers.BuildTypedValue(Attr(MAttrType.UserState), id.ToString()).GuidValue);
+ Assert.Equal(new[] { 1, 2, 3 }, Helpers.BuildTypedValue(Attr(MAttrType.OrgUnit), "1, 2;3").ArrayIntValue);
+ Assert.Equal(new[] { "x", "y" }, Helpers.BuildTypedValue(Attr(MAttrType.Array), "x; y").ArrayValue);
+ }
+
+ [Fact]
+ public void BuildTypedValue_StringKinds_KeepStrValue()
+ {
+ Assert.Equal("abc", Helpers.BuildTypedValue(Attr(MAttrType.String), "abc").StrValue);
+ Assert.Equal("N-1", Helpers.BuildTypedValue(Attr(MAttrType.Numerator), "N-1").StrValue);
+ }
+
+ [Theory]
+ [InlineData(MAttrType.Integer, "abc")]
+ [InlineData(MAttrType.Integer, "99999999999999999999")]
+ [InlineData(MAttrType.Double, "1,5x")]
+ [InlineData(MAttrType.DateTime, "не дата")]
+ [InlineData(MAttrType.UserState, "not-a-guid")]
+ [InlineData(MAttrType.OrgUnit, "1,a")]
+ public void BuildTypedValue_BadValue_ThrowsArgumentException(MAttrType type, string value)
+ {
+ var ex = Assert.Throws(() => Helpers.BuildTypedValue(Attr(type), value));
+ Assert.Contains("'a'", ex.Message);
+ }
+
+ [Fact]
+ public void BuildTypedValue_ByteArray_IsRejected()
+ => Assert.Throws(() => Helpers.BuildTypedValue(Attr(MAttrType.ByteArray), "00"));
+
+ private sealed class FakeFileApi : IFileArchiveApi
+ {
+ public Func Chunk = _ => null;
+ public byte[] GetFileChunk(Guid id, long pos, int count) => Chunk(pos)!;
+ public void PutFileChunk(Guid id, byte[] buffer, long pos) => throw new NotSupportedException();
+ public void PutFileChunk(Guid id, byte[] buffer, long pos, bool isLast) => throw new NotSupportedException();
+ public long GetFilePosition(Guid id) => throw new NotSupportedException();
+ [Obsolete]
+ public void PutFileInArchive(DFileBody fileBody) => throw new NotSupportedException();
+ public (Guid ListId, int FileCount) PrepareFileList() => throw new NotSupportedException();
+ public IEnumerable<(Guid fileId, Guid objectId)> EnumerateFileList(Guid listId, int offset, int count) => throw new NotSupportedException();
+ public void CloseFileList(Guid listId) => throw new NotSupportedException();
+ }
+
+ [Fact]
+ public void MeasureArchiveFile_SumsChunks()
+ {
+ const int chunk = 1024 * 1024;
+ var api = new FakeFileApi
+ {
+ Chunk = pos => pos switch
+ {
+ 0 => new byte[chunk],
+ chunk => new byte[chunk],
+ _ => new byte[100]
+ }
+ };
+ Assert.Equal(2L * chunk + 100, Helpers.MeasureArchiveFile(api, Guid.NewGuid()));
+ }
+
+ [Fact]
+ public void MeasureArchiveFile_EmptyOrMissing_ReturnsZero()
+ {
+ Assert.Equal(0, Helpers.MeasureArchiveFile(new FakeFileApi(), Guid.NewGuid()));
+ Assert.Equal(0, Helpers.MeasureArchiveFile(new FakeFileApi { Chunk = _ => Array.Empty() }, Guid.NewGuid()));
+ }
+}
diff --git a/PilotMCP.Tests/ObjectToolsTests.cs b/PilotMCP.Tests/ObjectToolsTests.cs
index ffd9703..847e1e4 100644
--- a/PilotMCP.Tests/ObjectToolsTests.cs
+++ b/PilotMCP.Tests/ObjectToolsTests.cs
@@ -3,6 +3,7 @@
namespace PilotMCP.Tests;
[Collection("Pilot")]
+[Trait("Category", "Integration")]
public class ObjectToolsTests
{
private readonly McpTestClient _client;
@@ -119,15 +120,128 @@ public async Task MoveObject_WithInvalidId_ReturnsError()
}
[Fact]
- public async Task GetFileSize_WithInvalidId_ReturnsResult()
+ public async Task MoveObject_ToMissingParent_ReturnsClearError()
+ {
+ var roots = await _client.CallToolAsync("GetRootObjects", new JsonObject());
+ roots.AssertOk();
+ Assert.False(string.IsNullOrEmpty(roots.ResultFile), $"Нет файла результатов: {roots.RawText}");
+ var firstLine = File.ReadLines(roots.ResultFile!).FirstOrDefault();
+ Assert.False(string.IsNullOrEmpty(firstLine), $"Нет корневых объектов: {roots.RawText}");
+ var objectId = JsonNode.Parse(firstLine!)!["id"]!.GetValue();
+
+ var result = await _client.CallToolAsync("MoveObject", new JsonObject
+ {
+ ["objectId"] = objectId,
+ ["newParentId"] = "11111111-2222-3333-4444-555555555555"
+ });
+
+ result.AssertError();
+ Assert.Contains("не найден", result.Message);
+ }
+
+ [Fact]
+ public async Task CreateObject_UnderMissingParent_ReturnsClearError()
+ {
+ var result = await _client.CallToolAsync("CreateObject", new JsonObject
+ {
+ ["parentId"] = "11111111-2222-3333-4444-555555555555",
+ ["typeName"] = "document",
+ ["attributeName"] = "sheet_number",
+ ["attributeValue"] = "1"
+ });
+
+ result.AssertError();
+ Assert.Contains("Родительский объект", result.Message);
+ }
+
+ [Fact]
+ public async Task GetFileSize_WithUnknownBody_ReturnsError()
{
var result = await _client.CallToolAsync("GetFileSize", new JsonObject
{
["fileBodyId"] = Guid.NewGuid().ToString()
});
- // May return 0 for non-existent file or error
- Assert.False(result.IsError && result.RawText.Contains("disposed"),
- $"Connection error: {result.RawText}");
+ // Несуществующий файл — ошибка, а не «0 байт».
+ result.AssertError();
+ Assert.DoesNotContain("disposed", result.RawText);
+ }
+
+ private const string Root = "00000001-0001-0001-0001-000000000001";
+
+ [Theory]
+ [InlineData("UnlockObject", "Alive")]
+ [InlineData("UnfreezeObject", "Alive")]
+ public async Task StateTools_RejectWrongState(string tool, string state)
+ {
+ // Корень в состоянии Alive: Unlock/Unfreeze не применимы и ничего не меняют.
+ var result = await _client.CallToolAsync(tool, new JsonObject { ["objectId"] = Root });
+
+ result.AssertError();
+ AssertWriteGuardOrContains(result, state);
+ }
+
+ [Fact]
+ public async Task SetAttribute_UnknownAttribute_ReturnsError()
+ {
+ var result = await _client.CallToolAsync("SetAttribute", new JsonObject
+ {
+ ["objectId"] = Root,
+ ["attributeName"] = "no_such_attribute_xyz",
+ ["attributeValue"] = "1"
+ });
+
+ result.AssertError();
+ AssertWriteGuardOrContains(result, "не определён");
+ }
+
+ [Fact]
+ public async Task CreateLink_NumericOrServiceType_ReturnsError()
+ {
+ foreach (var type in new[] { "99", "1", "Publish" })
+ {
+ var result = await _client.CallToolAsync("CreateLink", new JsonObject
+ {
+ ["objectId1"] = Root,
+ ["objectId2"] = Root,
+ ["relationType"] = type
+ });
+
+ result.AssertError();
+ AssertWriteGuardOrContains(result, "Неизвестный тип связи");
+ }
+ }
+
+ [Fact]
+ public async Task GetObjectsWithRights_InvalidGuid_ReturnsError()
+ {
+ var result = await _client.CallToolAsync("GetObjectsWithRights", new JsonObject
+ {
+ ["objectIds"] = $"{Root}, typo"
+ });
+
+ result.AssertError();
+ Assert.Contains("typo", result.Message);
+ }
+
+ [Fact]
+ public async Task AddSignatureRequest_OnObjectWithoutFiles_ReturnsError()
+ {
+ var result = await _client.CallToolAsync("AddSignatureRequest", new JsonObject
+ {
+ ["objectId"] = Root,
+ ["positionId"] = 1,
+ ["role"] = "Согласующий",
+ ["fileName"] = "nope.pdf"
+ });
+
+ result.AssertError();
+ }
+
+ // В режиме ReadOnly запись блокируется раньше проверки — тогда достаточно самого факта ошибки.
+ private static void AssertWriteGuardOrContains(ToolCallResult result, string fragment)
+ {
+ if (result.Message.Contains("ReadOnly", StringComparison.OrdinalIgnoreCase)) return;
+ Assert.Contains(fragment, result.Message);
}
}
diff --git a/PilotMCP.Tests/PeopleAdminToolsTests.cs b/PilotMCP.Tests/PeopleAdminToolsTests.cs
index 8bbb5d3..422b0fe 100644
--- a/PilotMCP.Tests/PeopleAdminToolsTests.cs
+++ b/PilotMCP.Tests/PeopleAdminToolsTests.cs
@@ -9,6 +9,7 @@ namespace PilotMCP.Tests;
/// Если админ-авторизация недоступна — тесты логируют причину и мягко пропускаются.
///
[Collection("Pilot")]
+[Trait("Category", "Integration")]
public class PeopleAdminToolsTests
{
private readonly McpTestClient _client;
diff --git a/PilotMCP.Tests/PilotMCP.Tests.csproj b/PilotMCP.Tests/PilotMCP.Tests.csproj
index cde128c..c087df6 100644
--- a/PilotMCP.Tests/PilotMCP.Tests.csproj
+++ b/PilotMCP.Tests/PilotMCP.Tests.csproj
@@ -5,17 +5,31 @@
enable
enable
false
+ $(MSBuildProjectDirectory)\test.runsettings
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/PilotMCP.Tests/QueryHelpersTests.cs b/PilotMCP.Tests/QueryHelpersTests.cs
new file mode 100644
index 0000000..3056254
--- /dev/null
+++ b/PilotMCP.Tests/QueryHelpersTests.cs
@@ -0,0 +1,92 @@
+namespace PilotMCP.Tests;
+
+/// Чистые unit-тесты хелперов поиска и файловых инструментов (без сервера).
+public class QueryHelpersTests
+{
+ [Fact]
+ public void EscapeLucene_EscapesEverySpecialChar()
+ {
+ Assert.Equal(@"a\:b", QueryHelpers.EscapeLucene("a:b"));
+ Assert.Equal(@"\(x\)", QueryHelpers.EscapeLucene("(x)"));
+ Assert.Equal(@"\-\+\*\?\\\/\""", QueryHelpers.EscapeLucene("-+*?\\/\""));
+ Assert.Equal("Договор", QueryHelpers.EscapeLucene("Договор"));
+ // операторы Lucene в верхнем регистре не должны уходить в запрос как операторы
+ Assert.Equal("and", QueryHelpers.EscapeLucene("AND"));
+ Assert.Equal("or", QueryHelpers.EscapeLucene("OR"));
+ Assert.Equal("not", QueryHelpers.EscapeLucene("NOT"));
+ Assert.Equal("Or", QueryHelpers.EscapeLucene("Or"));
+ }
+
+ [Fact]
+ public void QuoteLucene_KeepsMultiWordValueAsOnePhrase()
+ {
+ Assert.Equal("\"Рабочая документация\"", QueryHelpers.QuoteLucene("Рабочая документация"));
+ Assert.Equal("\"a \\\"b\\\" \\\\c\"", QueryHelpers.QuoteLucene("a \"b\" \\c"));
+ }
+
+ [Fact]
+ public void EscapedWords_SplitsAndEscapes_EmptyForBlank()
+ {
+ Assert.Equal(new[] { "a", @"b\:c" }, QueryHelpers.EscapedWords(" a b:c "));
+ Assert.Empty(QueryHelpers.EscapedWords(" "));
+ }
+
+ [Fact]
+ public void ParseRange_DateOnlyUpperBoundIncludesWholeDay_AndIsCultureIndependent()
+ {
+ var old = System.Globalization.CultureInfo.CurrentCulture;
+ System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("ru-RU");
+ try
+ {
+ Assert.Null(QueryHelpers.ParseRange("2025-01-01", "2025-01-31", "from", "to", out var f, out var t));
+ Assert.Equal(new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc), f);
+ Assert.Equal(new DateTime(2025, 1, 31, 23, 59, 59, DateTimeKind.Utc), t);
+ }
+ finally { System.Globalization.CultureInfo.CurrentCulture = old; }
+ }
+
+ [Fact]
+ public void ParseRange_ExplicitTimeUpperBoundIsKept_EmptyMeansOpen()
+ {
+ Assert.Null(QueryHelpers.ParseRange("", "2025-01-31T10:00:00Z", "from", "to", out var f, out var t));
+ Assert.Equal(DateTime.MinValue, f);
+ Assert.Equal(new DateTime(2025, 1, 31, 10, 0, 0, DateTimeKind.Utc), t);
+ Assert.Null(QueryHelpers.ParseRange("", "", "from", "to", out _, out var t2));
+ Assert.Equal(DateTime.MaxValue, t2);
+ }
+
+ [Theory]
+ [InlineData("garbage", "")]
+ [InlineData("", "32.13.2025")]
+ [InlineData("2025-02-01", "2025-01-01")]
+ public void ParseRange_InvalidOrInverted_ReturnsError(string from, string to)
+ => Assert.NotNull(QueryHelpers.ParseRange(from, to, "from", "to", out _, out _));
+
+ [Fact]
+ public void CsvEscape_QuotesSeparatorQuoteAndLineBreaks()
+ {
+ Assert.Equal("plain", QueryHelpers.CsvEscape("plain", ";"));
+ Assert.Equal("\"a;b\"", QueryHelpers.CsvEscape("a;b", ";"));
+ Assert.Equal("\"a\"\"b\"", QueryHelpers.CsvEscape("a\"b", ";"));
+ Assert.Equal("\"a\rb\"", QueryHelpers.CsvEscape("a\rb", ";"));
+ Assert.Equal("\"a\nb\"", QueryHelpers.CsvEscape("a\nb", ";"));
+ }
+
+ [Fact]
+ public void PrepareOutput_SamePath_IsErrorAndCreatesDirForOthers()
+ {
+ var dir = Path.Combine(Path.GetTempPath(), $"qh_{Guid.NewGuid():N}");
+ var input = Path.Combine(dir, "in.jsonl");
+ Directory.CreateDirectory(dir);
+ try
+ {
+ Assert.NotNull(QueryHelpers.PrepareOutput(input, input));
+ if (OperatingSystem.IsWindows())
+ Assert.NotNull(QueryHelpers.PrepareOutput(input, Path.Combine(dir, ".", "IN.JSONL")));
+ var nested = Path.Combine(dir, "sub", "out.jsonl");
+ Assert.Null(QueryHelpers.PrepareOutput(input, nested));
+ Assert.True(Directory.Exists(Path.Combine(dir, "sub")));
+ }
+ finally { Directory.Delete(dir, true); }
+ }
+}
diff --git a/PilotMCP.Tests/QueryToolsTests.cs b/PilotMCP.Tests/QueryToolsTests.cs
index ec989b6..4fa70e1 100644
--- a/PilotMCP.Tests/QueryToolsTests.cs
+++ b/PilotMCP.Tests/QueryToolsTests.cs
@@ -3,6 +3,7 @@
namespace PilotMCP.Tests;
[Collection("Pilot")]
+[Trait("Category", "Integration")]
public class QueryToolsTests
{
private readonly McpTestClient _client;
@@ -136,4 +137,35 @@ public async Task GetStateMachines_ReturnsMachines()
result.AssertOk();
Assert.Contains("Машины состояний", result.Message);
}
+
+ [Theory]
+ [InlineData("Search", "context", "not-a-guid")]
+ [InlineData("Search", "stateId", "not-a-guid")]
+ [InlineData("Search", "createdFrom", "garbage")]
+ [InlineData("Search", "attribute", "noequals")]
+ [InlineData("SearchByDate", "from", "garbage")]
+ [InlineData("SearchByDate", "to", "garbage")]
+ [InlineData("GetChildren", "parentId", "00000000-0000-0000-0000-000000000000")]
+ public async Task InvalidFilterArgument_ReturnsError(string tool, string arg, string value)
+ {
+ var result = await _client.CallToolAsync(tool, new JsonObject { [arg] = value });
+ result.AssertError();
+ }
+
+ [Fact]
+ public async Task SearchByText_WithLuceneSpecials_DoesNotFailAsSyntaxError()
+ {
+ var result = await _client.CallToolAsync("SearchByText", new JsonObject { ["text"] = "a:b (" });
+ result.AssertOk();
+ Assert.Equal(0, result.Count);
+ }
+
+ [Fact]
+ public async Task SearchByDate_DateOnlyUpperBound_IsAccepted()
+ {
+ var result = await _client.CallToolAsync("SearchByDate", new JsonObject
+ { ["from"] = "2000-01-01", ["to"] = "2100-01-01", ["maxResults"] = 3 });
+ result.AssertOk();
+ Assert.True(result.Count > 0);
+ }
}
diff --git a/PilotMCP.Tests/ReportToolsTests.cs b/PilotMCP.Tests/ReportToolsTests.cs
index 4abe6b4..1b7b234 100644
--- a/PilotMCP.Tests/ReportToolsTests.cs
+++ b/PilotMCP.Tests/ReportToolsTests.cs
@@ -4,6 +4,7 @@
namespace PilotMCP.Tests;
[Collection("Pilot")]
+[Trait("Category", "Integration")]
public class ReportToolsTests
{
private readonly McpTestClient _client;
@@ -110,4 +111,16 @@ public async Task GetReportSample_WithInvalidName_ReturnsError()
result.AssertError();
}
+
+ [Fact]
+ public async Task GetReportSample_WithPathSegments_ReturnsError()
+ {
+ var result = await _client.CallToolAsync("GetReportSample", new JsonObject
+ {
+ ["sampleName"] = "../../secret"
+ });
+
+ result.AssertError();
+ Assert.Contains("путь", result.Message);
+ }
}
diff --git a/PilotMCP.Tests/XpsGlyphWidthTests.cs b/PilotMCP.Tests/XpsGlyphWidthTests.cs
new file mode 100644
index 0000000..1d3078d
--- /dev/null
+++ b/PilotMCP.Tests/XpsGlyphWidthTests.cs
@@ -0,0 +1,150 @@
+using System.IO.Compression;
+using System.Text;
+using SkiaSharp;
+
+namespace PilotMCP.Tests;
+
+/// Ширина совпадения по натуральному advance последнего глифа из встроенного шрифта (без сервера).
+public class XpsGlyphWidthTests : IDisposable
+{
+ private const string FontGuid = "0C8E9A6D-1B2F-4A3C-9D5E-7F8091A2B3C4";
+ private static readonly string ArialPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf");
+ private readonly string _path = Path.Combine(Path.GetTempPath(), $"xps-glyph-{Guid.NewGuid():N}.xps");
+
+ public void Dispose() => File.Delete(_path);
+
+ /// Пакет с одной страницей; fontPart/fontBytes — встроенный шрифт (null — шрифта в пакете нет).
+ private void WritePackage(string glyphs, string? fontPart, byte[]? fontBytes)
+ {
+ using var zip = ZipFile.Open(_path, ZipArchiveMode.Create);
+ using (var w = new StreamWriter(zip.CreateEntry("Documents/1/Pages/1.fpage").Open(), Encoding.UTF8))
+ w.Write("" + glyphs + "");
+ if (fontPart != null)
+ using (var s = zip.CreateEntry(fontPart).Open()) s.Write(fontBytes!);
+ }
+
+ private static string Glyphs(string fontUri, string text, string indices) =>
+ $"";
+
+ private static byte[] ObfuscatedArial()
+ {
+ var data = File.ReadAllBytes(ArialPath);
+ XpsTextExtractor.Deobfuscate(data, FontGuid); // симметрична
+ return data;
+ }
+
+ private static (double A, double B) ArialWidths(string chars)
+ {
+ using var tf = SKTypeface.FromFile(ArialPath);
+ using var font = new SKFont(tf, 10) { Subpixel = true, LinearMetrics = true, Hinting = SKFontHinting.None };
+ var w = font.GetGlyphWidths(tf.GetGlyphs(chars));
+ return (w[0], w[1]);
+ }
+
+ [Fact]
+ public void FindText_LastGlyphWithGapAdvance_UsesNaturalWidth_Obfuscated_NoGlyphIndex()
+ {
+ // Индексов глифов нет (",adv") — шрифт выбирается по cmap; у "B" advance 8 em включает зазор колонки
+ WritePackage(Glyphs($"/Resources/Fonts/{FontGuid}.odttf", "AB", ",100;,800"),
+ $"Resources/Fonts/{FontGuid}.odttf", ObfuscatedArial());
+ var (_, natB) = ArialWidths("AB");
+
+ var hit = Assert.Single(XpsTextExtractor.FindText(_path, "AB"));
+
+ Assert.Equal(10 + natB, hit.Width, 3);
+ Assert.InRange(natB, 6, 7); // реальный advance Arial "B" ~0.667 em
+ Assert.Equal(10, hit.X, 6);
+ }
+
+ [Fact]
+ public void FindText_ExplicitGlyphIndices_PlainTtf_RelativeFontUri_InnerAdvancesStay()
+ {
+ using var tf = SKTypeface.FromFile(ArialPath);
+ var g = tf.GetGlyphs("ABC");
+ var (natA, natB) = ArialWidths("AB");
+ WritePackage(Glyphs("../../../Resources/Fonts/arial.ttf", "ABC", $"{g[0]},200;{g[1]},300;{g[2]},900"),
+ "Resources/Fonts/arial.ttf", File.ReadAllBytes(ArialPath));
+
+ var ab = Assert.Single(XpsTextExtractor.FindText(_path, "AB"));
+ var abc = Assert.Single(XpsTextExtractor.FindText(_path, "ABC"));
+
+ Assert.Equal(20 + natB, ab.Width, 3); // A: из Indices (2 em), последний B: натуральный (< 3 em)
+ Assert.Equal(20 + 30 + ArialWidths("CA").A, abc.Width, 3);
+ Assert.True(natA > 0);
+ }
+
+ [Fact]
+ public void FindText_NaturalWidthLargerThanAdvance_KeepsIndicesAdvance()
+ {
+ WritePackage(Glyphs($"/Resources/Fonts/{FontGuid}.odttf", "AB", ",100;,10"),
+ $"Resources/Fonts/{FontGuid}.odttf", ObfuscatedArial());
+
+ var hit = Assert.Single(XpsTextExtractor.FindText(_path, "AB"));
+
+ Assert.Equal(11, hit.Width, 6); // 1 em + 0.1 em: натуральная ширина шире — не расширяем
+ }
+
+ [Fact]
+ public void FindText_FontMissingInPackage_KeepsIndicesWidthAndReportsToStderr()
+ {
+ WritePackage(Glyphs("/Resources/Fonts/missing.ttf", "AB", ",100;,800"), null, null);
+ var prev = Console.Error;
+ var err = new StringWriter();
+ Console.SetError(err);
+ try
+ {
+ var hit = Assert.Single(XpsTextExtractor.FindText(_path, "AB"));
+ Assert.Equal(90, hit.Width, 6);
+ }
+ finally { Console.SetError(prev); }
+
+ Assert.Contains("missing.ttf", err.ToString());
+ }
+
+ [Fact]
+ public void FindText_AcrossRuns_LastRunUsesNaturalWidth()
+ {
+ var fontUri = $"/Resources/Fonts/{FontGuid}.odttf";
+ var tail = $"";
+ WritePackage(Glyphs(fontUri, "A", ",100") + tail, $"Resources/Fonts/{FontGuid}.odttf", ObfuscatedArial());
+ var (_, natB) = ArialWidths("AB");
+
+ var hit = Assert.Single(XpsTextExtractor.FindText(_path, "AB"));
+
+ Assert.Equal(10 + natB, hit.Width, 3);
+ }
+
+ [Fact]
+ public void Deobfuscate_RoundTrip_ChangesOnlyFirst32Bytes_AndSkiaAcceptsResult()
+ {
+ var original = File.ReadAllBytes(ArialPath);
+ var data = (byte[])original.Clone();
+
+ XpsTextExtractor.Deobfuscate(data, FontGuid);
+
+ Assert.NotEqual(original[..32], data[..32]);
+ Assert.Equal(original[32..], data[32..]);
+ using (var broken = SKData.CreateCopy(data)) Assert.Null(SKTypeface.FromData(broken));
+ XpsTextExtractor.Deobfuscate(data, FontGuid);
+ Assert.Equal(original, data);
+ using var ok = SKData.CreateCopy(data);
+ using var tf = SKTypeface.FromData(ok);
+ Assert.NotNull(tf);
+ }
+
+ [Fact]
+ public void Deobfuscate_KeyIsGuidHexInStringOrderReversed()
+ {
+ var data = new byte[32];
+ XpsTextExtractor.Deobfuscate(data, "00112233-4455-6677-8899-AABBCCDDEEFF");
+
+ // ключ в порядке строки 00 11 .. FF; применяется с конца: data[0] = key[15] = FF
+ Assert.Equal(0xFF, data[0]);
+ Assert.Equal(0x00, data[15]);
+ Assert.Equal(data[..16], data[16..]);
+ }
+
+ [Fact]
+ public void Deobfuscate_NotGuidName_Throws() =>
+ Assert.Throws(() => XpsTextExtractor.Deobfuscate(new byte[32], "not-a-guid"));
+}
diff --git a/PilotMCP.Tests/XpsPageOrderTests.cs b/PilotMCP.Tests/XpsPageOrderTests.cs
new file mode 100644
index 0000000..74df76b
--- /dev/null
+++ b/PilotMCP.Tests/XpsPageOrderTests.cs
@@ -0,0 +1,115 @@
+using System.IO.Compression;
+using System.Text;
+
+namespace PilotMCP.Tests;
+
+/// Порядок страниц XPS берётся из FixedDocument, а не из имён файлов (без сервера).
+public class XpsPageOrderTests : IDisposable
+{
+ private readonly string _path = Path.Combine(Path.GetTempPath(), $"xps-order-{Guid.NewGuid():N}.xps");
+
+ public void Dispose() => File.Delete(_path);
+
+ private void WriteXps(params (string Name, string Content)[] parts)
+ {
+ using var zip = ZipFile.Open(_path, ZipArchiveMode.Create);
+ foreach (var (name, content) in parts)
+ {
+ using var w = new StreamWriter(zip.CreateEntry(name).Open(), Encoding.UTF8);
+ w.Write(content);
+ }
+ }
+
+ private static string Page(int w, int h) =>
+ $"";
+
+ private const string Rels =
+ "" +
+ "" +
+ "";
+
+ private const string Seq =
+ "" +
+ "";
+
+ [Fact]
+ public void GetPageSizes_FollowsFixedDocumentOrder()
+ {
+ // Порядок в FixedDocument: 10, 2, 1 — не совпадает ни со строковой, ни с числовой сортировкой имён.
+ WriteXps(
+ ("_rels/.rels", Rels),
+ ("FixedDocSeq.fdseq", Seq),
+ ("Documents/1/FixedDoc.fdoc",
+ "" +
+ "" +
+ ""),
+ ("Documents/1/Pages/1.fpage", Page(100, 101)),
+ ("Documents/1/Pages/2.fpage", Page(200, 202)),
+ ("Documents/1/Pages/10.fpage", Page(1000, 1010)));
+
+ Assert.Equal(new[] { (1000.0, 1010.0), (200.0, 202.0), (100.0, 101.0) }, XpsTextExtractor.GetPageSizes(_path));
+ }
+
+ [Fact]
+ public void GetPageSizes_JoinsInterleavedPiecesInIndexOrder()
+ {
+ var page = Page(300, 400);
+ WriteXps(
+ ("_rels/.rels", Rels),
+ ("FixedDocSeq.fdseq", Seq),
+ ("Documents/1/FixedDoc.fdoc",
+ ""),
+ ("Documents/1/Pages/1.fpage/[10].last.piece", page[20..]),
+ ("Documents/1/Pages/1.fpage/[2].piece", page[..20]));
+
+ Assert.Equal(new[] { (300.0, 400.0) }, XpsTextExtractor.GetPageSizes(_path));
+ }
+
+ [Fact]
+ public void GetPageSizes_ZipBombPage_ThrowsInsteadOfExhaustingMemory()
+ {
+ WriteXps(
+ ("_rels/.rels", Rels),
+ ("FixedDocSeq.fdseq", Seq),
+ ("Documents/1/FixedDoc.fdoc",
+ ""));
+ using (var zip = ZipFile.Open(_path, ZipArchiveMode.Update))
+ using (var s = zip.CreateEntry("Documents/1/Pages/1.fpage", CompressionLevel.Optimal).Open())
+ {
+ // ~65 МБ пробелов сжимаются в десятки КБ: часть больше лимита 64 МБ после распаковки
+ var chunk = new byte[1 << 20];
+ Array.Fill(chunk, (byte)' ');
+ for (var i = 0; i < 65; i++) s.Write(chunk);
+ }
+
+ var ex = Assert.Throws(() => XpsTextExtractor.GetPageSizes(_path));
+ Assert.Contains("превышает допустимый размер", ex.Message);
+ }
+
+ [Fact]
+ public void GetPageSizes_TooManyPageReferences_Throws()
+ {
+ var refs = string.Concat(Enumerable.Repeat("", 10_001));
+ WriteXps(
+ ("_rels/.rels", Rels),
+ ("FixedDocSeq.fdseq", Seq),
+ ("Documents/1/FixedDoc.fdoc", $"{refs}"),
+ ("Documents/1/Pages/1.fpage", Page(100, 100)));
+
+ var ex = Assert.Throws(() => XpsTextExtractor.GetPageSizes(_path));
+ Assert.Contains("страниц", ex.Message);
+ }
+
+ [Fact]
+ public void GetPageSizes_MissingSize_Throws()
+ {
+ WriteXps(
+ ("_rels/.rels", Rels),
+ ("FixedDocSeq.fdseq", Seq),
+ ("Documents/1/FixedDoc.fdoc",
+ ""),
+ ("Documents/1/Pages/1.fpage", ""));
+
+ Assert.Throws(() => XpsTextExtractor.GetPageSizes(_path));
+ }
+}
diff --git a/PilotMCP.Tests/XpsTextTests.cs b/PilotMCP.Tests/XpsTextTests.cs
new file mode 100644
index 0000000..360cf61
--- /dev/null
+++ b/PilotMCP.Tests/XpsTextTests.cs
@@ -0,0 +1,96 @@
+using System.IO.Compression;
+using System.Text;
+
+namespace PilotMCP.Tests;
+
+/// Разбор Glyphs и поиск текста в XPS (без сервера).
+public class XpsTextTests : IDisposable
+{
+ private readonly string _path = Path.Combine(Path.GetTempPath(), $"xps-text-{Guid.NewGuid():N}.xps");
+
+ public void Dispose() => File.Delete(_path);
+
+ // Пакет без FixedDocumentSequence: страница берётся по имени .fpage
+ private void WritePage(string body)
+ {
+ using var zip = ZipFile.Open(_path, ZipArchiveMode.Create);
+ using var w = new StreamWriter(zip.CreateEntry("Documents/1/Pages/1.fpage").Open(), Encoding.UTF8);
+ w.Write("" + body + "");
+ }
+
+ private static string Glyphs(string text, double x, double y, string extra = "", string children = "") =>
+ FormattableString.Invariant($"{children}");
+
+ [Fact]
+ public void FindText_ReturnsEveryMatchInsideOneRun()
+ {
+ WritePage(Glyphs("foo bar foo", 10, 100)); // без Indices: 5 единиц на символ
+
+ var found = XpsTextExtractor.FindText(_path, "foo");
+
+ Assert.Equal(2, found.Count);
+ Assert.Equal(10, found[0].X, 6);
+ Assert.Equal(50, found[1].X, 6);
+ Assert.All(found, f => Assert.Equal(15, f.Width, 6));
+ Assert.All(found, f => Assert.Equal(90, f.Y, 6));
+ }
+
+ [Fact]
+ public void FindText_EmptyText_Throws()
+ {
+ WritePage(Glyphs("foo", 10, 100));
+ Assert.Throws(() => XpsTextExtractor.FindText(_path, ""));
+ }
+
+ [Fact]
+ public void FindText_AcrossRuns_KeepsTopYAndMeasuresWidthByAdvances()
+ {
+ // Базовые линии 102.4 и 102.6 раньше попадали в разные корзины Round(Y/5)*5
+ WritePage(Glyphs("ab", 10, 102.4) + Glyphs("cd", 20, 102.6));
+
+ var found = XpsTextExtractor.FindText(_path, "bc");
+
+ var hit = Assert.Single(found);
+ Assert.Equal("bc", hit.Text);
+ Assert.Equal(15, hit.X, 6);
+ Assert.Equal(10, hit.Width, 6);
+ Assert.Equal(92.4, hit.Y, 6); // верх текста, без повторного вычитания размера шрифта
+ }
+
+ [Fact]
+ public void ExtractText_StripsEscapePrefix()
+ {
+ WritePage(Glyphs("{}foo", 10, 100));
+ Assert.Equal("foo", Assert.Single(XpsTextExtractor.ExtractText(_path)).Text);
+ }
+
+ [Fact]
+ public void ExtractText_ClusterMapSharesAdvanceBetweenCharacters()
+ {
+ // "fi" — один глиф шириной 30 (300/100 * 10), затем "x" шириной 10
+ WritePage(Glyphs("fix", 10, 100, "Indices=\"(2:1)5,300;3,100\""));
+
+ var block = Assert.Single(XpsTextExtractor.ExtractText(_path));
+
+ Assert.Equal(new[] { 15.0, 15.0, 10.0 }, block.Advances);
+ var hit = Assert.Single(XpsTextExtractor.FindText(_path, "x"));
+ Assert.Equal(40, hit.X, 6);
+ Assert.Equal(10, hit.Width, 6);
+ }
+
+ [Fact]
+ public void ExtractText_ReadsRenderTransformPropertyElement()
+ {
+ WritePage(Glyphs("foo", 10, 100, children:
+ ""));
+
+ Assert.Equal(110, Assert.Single(XpsTextExtractor.ExtractText(_path)).X, 6);
+ }
+
+ [Fact]
+ public void GetPageCount_CountsPages()
+ {
+ WritePage(Glyphs("foo", 10, 100));
+ Assert.Equal(1, XpsTextExtractor.GetPageCount(_path));
+ }
+}
diff --git a/PilotMCP.csproj b/PilotMCP.csproj
index 529a6ff..f1596e4 100644
--- a/PilotMCP.csproj
+++ b/PilotMCP.csproj
@@ -7,7 +7,8 @@
PilotMCP
enable
enable
- 0.0.0.4
+
+ 0.1.0
@@ -18,10 +19,13 @@
+
+
+
-
+
@@ -57,8 +61,8 @@
-
-
+
+
diff --git a/PilotMCP.slnx b/PilotMCP.slnx
index 87f27da..f629da1 100644
--- a/PilotMCP.slnx
+++ b/PilotMCP.slnx
@@ -1,4 +1,5 @@
+
diff --git a/README.md b/README.md
index f6cd355..6a69a66 100644
--- a/README.md
+++ b/README.md
@@ -2,11 +2,40 @@
MCP-сервер для работы с Pilot через Server API. Позволяет LLM-агентам подключаться к серверу Pilot, выполнять поиск, создавать и изменять объекты, работать с документами, историей изменений, правами доступа и чатами.
+Документация: https://mahach666.github.io/PilotMCP/
+
## Требования
- .NET 8.0
- Доступ к серверу Pilot
+## Установка
+
+Подробнее об установке и настройке клиентов — в [документации](https://mahach666.github.io/PilotMCP/getting-started.html).
+
+Готовые сборки (Windows x64) — на странице [Releases](https://github.com/mahach666/PilotMCP/releases):
+
+| Файл | Для чего |
+| ---- | -------- |
+| `PilotMCP-vX.Y.Z-win-x64.mcpb` | MCP Bundle: установка в Claude Desktop в один клик, параметры подключения вводятся в форме |
+| `PilotMCP-vX.Y.Z-win-x64-selfcontained.zip` | Распаковать и указать `PilotMCP.exe` в конфигурации клиента; .NET не нужен |
+| `PilotMCP-vX.Y.Z-win-x64.zip` | То же, но нужен установленный .NET 8 Runtime |
+
+Сервер также опубликован в официальном [MCP Registry](https://registry.modelcontextprotocol.io) под именем `io.github.mahach666/pilotmcp`.
+
+### Выпуск релиза
+
+Релиз собирается GitHub Actions по тегу вида `vX.Y.Z` (semver, допускается суффикс `-beta.1`):
+
+```
+git tag v0.1.0
+git push origin v0.1.0
+```
+
+Workflow [`release.yml`](.github/workflows/release.yml) прогоняет unit-тесты, собирает zip-архивы и `.mcpb`, создаёт GitHub Release и публикует [`server.json`](server.json) в MCP Registry (вход по OIDC, секреты не нужны). Версия берётся из тега. Манифест бандла — [`mcpb/manifest.json`](mcpb/manifest.json).
+
+На каждый push и pull request [`ci.yml`](.github/workflows/ci.yml) собирает проект и прогоняет unit-тесты. Интеграционные тесты (`Category=Integration`) требуют живой сервер Pilot и запускаются локально: `dotnet test PilotMCP.slnx` с параметрами из `PilotMCP.Tests/test.runsettings`.
+
## Подключение к MCP-клиенту
@@ -46,11 +75,17 @@ MCP-сервер для работы с Pilot через Server API. Позво
}
```
+### Надёжность записи
+
+- Операции записи через Modifier/Backend (создание и изменение объектов, связей, задач, замечаний и т.д.) дожидаются ответа сервера (до 60 с). Отказ сервера возвращается как ошибка с его текстом; по таймауту сообщается, что результат неизвестен.
+- При обрыве соединения PilotMCP переподключается и повторяет только читающие вызовы. Записи после таймаута или обрыва автоматически не повторяются, чтобы не создать дубликаты, — проверьте состояние и повторите вручную.
+- Метаданные перечитываются, когда сервер сообщает об их изменении; параллельные изменения метаданных внутри одного процесса PilotMCP выполняются последовательно.
+
### Режим только чтения
При `PILOT_READONLY=true` сервер сообщает модели об ограничениях через системный промпт при инициализации. Модель не будет пытаться выполнять операции записи и сразу сообщит пользователю об ограничении.
-Заблокированы: `CreateObject`, `SetAttribute`, `DeleteObject`, `RestoreObject`, `MoveObject`, `LockObject`, `UnlockObject`, `FreezeObject`, `UnfreezeObject`, `MakeSecret`, `MakePublic`, `DeleteFile`, `SetUserState`, `Subscribe`, `Unsubscribe`, `AnnotateText`, `CreateAnnotation`, `SendMessage`, `EditMessage`, `ReplyMessage`, `CreateChat`, `UploadFile`, `InvokeCommand`, `CreateLink`, `DeleteRelation`, `AddAccessRecord`, `RemoveAllAccessRecords`, `UpdatePerson`, `ChangeSettings`, `CreateReport`, `UpdateReport`, `CreateTask`, `CreateWorkflow`, `AddSignatureRequest`, `CreateAutomationConfig`, `UpdateAutomationConfig`, `DeleteAutomationConfig`, `CreateType`, `UpdateType`, `DeleteType`, `AddTypeChildren`, `AddTypeAttribute`, `UpdateTypeAttribute`, `DeleteTypeAttribute`, `CreateUserState`, `UpdateUserState`, `DeleteUserState`, `CreateStateMachine`, `UpdateStateMachine`, `DeleteStateMachine`, `CreatePerson`, `UpdatePersonAdmin`, `DeletePerson`, `CreateOrgUnit`, `UpdateOrgUnit`, `DeleteOrgUnit`, `MoveOrgUnits`, `SetPersonOnPosition`, `RemovePersonFromPosition`.
+Заблокированы: `CreateObject`, `SetAttribute`, `DeleteObject`, `RestoreObject`, `MoveObject`, `LockObject`, `UnlockObject`, `FreezeObject`, `UnfreezeObject`, `MakeSecret`, `MakePublic`, `DeleteFile`, `SetUserState`, `Subscribe`, `Unsubscribe`, `AnnotateText`, `CreateAnnotation`, `CreateMarkupAnnotation`, `SendMessage`, `EditMessage`, `ReplyMessage`, `CreateChat`, `UploadFile`, `InvokeCommand`, `CreateLink`, `DeleteRelation`, `AddAccessRecord`, `RemoveAllAccessRecords`, `UpdatePerson`, `ChangeSettings`, `CreateReport`, `UpdateReport`, `CreateTask`, `CreateWorkflow`, `AddSignatureRequest`, `CreateAutomationConfig`, `UpdateAutomationConfig`, `DeleteAutomationConfig`, `CreateType`, `UpdateType`, `DeleteType`, `AddTypeChildren`, `AddTypeAttribute`, `UpdateTypeAttribute`, `DeleteTypeAttribute`, `CreateUserState`, `UpdateUserState`, `DeleteUserState`, `CreateStateMachine`, `UpdateStateMachine`, `DeleteStateMachine`, `CreatePerson`, `UpdatePersonAdmin`, `DeletePerson`, `CreateOrgUnit`, `UpdateOrgUnit`, `DeleteOrgUnit`, `MoveOrgUnits`, `SetPersonOnPosition`, `RemovePersonFromPosition`.
---
@@ -89,24 +124,24 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| `GetAttribute` | Прочитать полное значение одного атрибута без обрезки (когда GetObject обрезал значение) |
| `GetType` | Информация о типе объекта по системному имени |
| `GetTypes` | Все типы объектов базы → JSONL-файл |
-| `CreateObject` | Создать объект (родитель, тип, атрибут) |
-| `SetAttribute` | Установить значение атрибута объекта |
+| `CreateObject` | Создать объект (родитель, тип, атрибут; значение разбирается по типу атрибута, неизвестный атрибут — ошибка) |
+| `SetAttribute` | Установить значение атрибута объекта (значение разбирается по типу атрибута: числа/даты в инвариантном формате; неизвестный атрибут — ошибка) |
| `DeleteObject` | Удалить объект (в корзину) |
| `RestoreObject` | Восстановить объект из корзины |
| `MoveObject` | Переместить объект в другую папку |
-| `LockObject` | Заблокировать объект (эксклюзивное редактирование) |
-| `UnlockObject` | Разблокировать объект |
-| `FreezeObject` | Заморозить объект (запретить редактирование) |
-| `UnfreezeObject` | Разморозить объект (разрешить редактирование) |
+| `LockObject` | Заблокировать объект (эксклюзивное редактирование); только из состояния Alive |
+| `UnlockObject` | Разблокировать объект; только из LockRequested/LockAccepted |
+| `FreezeObject` | Заморозить объект (запретить редактирование); только из состояния Alive |
+| `UnfreezeObject` | Разморозить объект (разрешить редактирование); только из состояния Frozen |
| `MakeSecret` | Сделать объект секретным (ограниченный доступ) |
| `MakePublic` | Снять секретность с объекта |
| `SetUserState` | Установить пользовательское состояние (UserState) на объекте |
| `Subscribe` | Подписаться на уведомления об изменениях объекта |
| `Unsubscribe` | Отписаться от уведомлений об изменениях объекта |
-| `DownloadFile` | Скачать файл из Pilot на диск |
-| `UploadFile` | Загрузить файл с диска и прикрепить к объекту |
+| `DownloadFile` | Скачать файл из Pilot на диск (через `.part`: существующий файл не затирается при сбое; пустое содержимое — ошибка) |
+| `UploadFile` | Загрузить файл с диска в объект: новая версия, прежние файлы сохраняются, одноимённый заменяется |
| `DeleteFile` | Удалить файл из объекта по его Body.Id |
-| `GetFileSize` | Проверить размер файла в архиве Pilot (без скачивания) |
+| `GetFileSize` | Размер файла в архиве Pilot по Body.Id (считается чтением по частям, без сохранения на диск; пустой/несуществующий — ошибка) |
| `ComputeFileMd5` | Вычислить MD5-хэш файла из архива Pilot (по Body.Id) или локального файла |
@@ -115,16 +150,16 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| Инструмент | Описание |
| ------------------- | ------------------------------------------------------------------------ |
-| `Search` | Поиск объектов по атрибутам → JSONL-файл |
-| `SearchByText` | Полнотекстовый поиск по всем атрибутам и содержимому |
+| `Search` | Комбинированный поиск → JSONL-файл. Некорректные фильтры (GUID, даты, атрибут) — ошибка, а не более широкий поиск |
+| `SearchByText` | Полнотекстовый поиск; спецсимволы Lucene (`: ( ) " -` и др.) ищутся буквально |
| `SearchInContext` | Поиск объектов внутри папки (рекурсивно по всем вложенным) |
| `SearchByType` | Поиск объектов по типу (typeId из GetTypes) |
-| `SearchByAttribute` | Поиск объектов по значению атрибута |
+| `SearchByAttribute` | Поиск по значению СТРОКОВОГО атрибута (фраза из нескольких слов — одним термом) |
| `SearchByState` | Поиск объектов по пользовательскому состоянию (UserState) |
| `SearchByCreator` | Поиск объектов по создателю (personId) |
-| `SearchByDate` | Поиск объектов по дате создания (диапазон) |
+| `SearchByDate` | Диапазон дат создания (ISO 8601, UTC; `to` без времени включает весь день; пустая граница — открытая) |
| `GetAllObjects` | Получить все объекты базы (поиск в контексте корня) |
-| `GetChildren` | Дочерние объекты по GUID → JSONL-файл |
+| `GetChildren` | Дочерние объекты по GUID → JSONL-файл (при недоступных объектах пишет «загружено X из Y») |
| `GetRootObjects` | Корневые объекты базы → JSONL-файл |
| `GetObjectsToFile` | Несколько объектов по списку GUID → JSONL-файл |
| `GetUserStates` | Список пользовательских состояний (UserStates) — для задач и workflow |
@@ -141,7 +176,7 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| `GetPeopleByIds` | Подробная информация о пользователях по списку ID |
| `GetOrgUnitsByIds` | Подробная информация об оргединицах по списку ID |
| `GetPersonOnPosition` | Узнать кто занимает указанную позицию (по positionId) |
-| `UpdatePerson` | Обновить email, phone, comment, isInactive пользователя |
+| `UpdatePerson` | Обновить email, phone, comment, isInactive пользователя по personId (админский API) |
#### Управление пользователями и оргструктурой (админский API)
@@ -171,13 +206,13 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| Инструмент | Описание |
| -------------------- | ------------------------------------------------------------------------ |
-| `ExtractFields` | Извлечь выбранные поля из JSONL → новый JSONL |
+| `ExtractFields` | Извлечь выбранные поля из JSONL → новый JSONL (отсутствующее поле = null). `outputFile` не может совпадать с `inputFile` (во всех инструментах записи) |
| `FilterObjects` | Отфильтровать записи по значению поля → новый JSONL |
| `ExtractFieldToText` | Извлечь одно поле построчно в текстовый файл |
| `PreviewFile` | Просмотреть N записей из файла (до 20) |
-| `ReadFile` | Прочитать текстовый файл (или его часть) с пагинацией через offset/limit |
+| `ReadFile` | Прочитать текстовый файл (или его часть) с пагинацией через offset/limit (отрицательный offset = 0) |
| `CountFile` | Количество записей в файле |
-| `ExportCsv` | Экспортировать JSONL в CSV |
+| `ExportCsv` | Экспортировать JSONL в CSV (колонки по умолчанию — объединение ключей всех записей) |
| `SaveResult` | Скопировать файл результатов в указанное место |
@@ -186,13 +221,22 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| Инструмент | Описание |
| ---------------------- | ----------------------------------------------------------------------------- |
-| `GetDocumentText` | Извлечь текст документа (XPS или PDF) для анализа |
-| `FindTextOnPage` | Найти текст на страницах и получить его координаты |
-| `ExtractPageText` | Извлечь все текстовые блоки со страницы с координатами → JSONL |
-| `GetDocumentPageImage` | Получить изображение страницы документа (PDF или XPS) для визуального анализа |
-| `AnnotateText` | Создать текстовое замечание к слову/фразе в документе (XPS или PDF) |
-| `CreateAnnotation` | Создать графическое замечание (прямоугольник, эллипс, стрелка и т.п.) |
-| `BuildAnnotationXml` | Сгенерировать XML-разметку аннотации без создания объекта |
+| `GetDocumentText` | Извлечь текст документа (XPS или PDF) для анализа; число страниц берётся из файла, `page` вне диапазона — ошибка, для документа без текстового слоя (скан) сообщается об этом; `maxChars` действует и на превью |
+| `FindTextOnPage` | Найти все вхождения текста и получить координаты; пустой `searchText` — ошибка. Единицы: XPS — 1/96 дюйма, PDF — пункты (1/72 дюйма), y — верх текста сверху вниз (указаны в ответе) |
+| `ExtractPageText` | Извлечь все текстовые блоки со страницы с координатами → JSONL (единицы те же, что у `FindTextOnPage`) |
+| `GetDocumentPageImage` | Получить изображение страницы документа (PDF или XPS); `dpi` 36-300, длинная сторона не больше 2000 px (при превышении dpi снижается, фактический указан в ответе), `page` вне диапазона — ошибка; PNG сохраняется в `%TEMP%\pilot-mcp` и удаляется через сутки |
+| `AnnotateText` | Замечание к слову/фразе (XPS или PDF): `style` = `highlight` (по умолчанию), `underline`, `strikeout` |
+| `CreateAnnotation` | Графическое замечание: `rectangle`, `ellipse`, `triangle`, `arrow`, `line`, `polyline`, `polygon`, `ink`, `point`; параметры `strokeWidth`, `points` (`x1,y1;x2,y2;...`), `cloud`, `startEnding`/`endEnding` |
+| `CreateMarkupAnnotation` | ОДНО замечание из нескольких фигур: `shapesJson` — JSON-массив с полями как у `CreateAnnotation` |
+| `GetAnnotations` | Прочитать замечания документа (формат markup/legacy, фигуры, страница, прямоугольник в пикселях, автор, версия файла); замечания из корзины пропускаются; нечитаемое замечание выводится с полем `error` |
+| `BuildAnnotationXml` | Сгенерировать XML-разметку аннотации в старом (legacy) формате без создания объекта |
+
+**Формат замечаний.** По умолчанию `AnnotateText`, `CreateAnnotation` и `CreateMarkupAnnotation` создают замечания
+в формате Markup (клиент Pilot 26.20+: атрибуты `markups` и `markups_version`). Параметр `format=legacy`
+(`AnnotateText`, `CreateAnnotation`) создаёт замечание в старом формате (атрибут `annotation`) для серверов и клиентов
+старше 26.20; новые фигуры и параметры в нём недоступны. Координаты фигур — в пикселях изображения от
+`GetDocumentPageImage` (тот же `dpi`); размеры страниц берутся из того же файла (XPS, иначе PDF).
+Окончания линий: `none`, `openarrow` (у `arrow` по умолчанию `openarrow` на острие).
### История и версии
@@ -201,7 +245,7 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| Инструмент | Описание |
| --------------- | ----------------------------------------- |
| `GetHistory` | История изменений объектов по списку GUID |
-| `GetChangesets` | Changesets в диапазоне ID |
+| `GetChangesets` | Changesets в диапазоне ID (номер, identity, GUID изменённых; не более 1000 номеров) |
### Права доступа
@@ -214,7 +258,7 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| `GetAccessRecords` | Записи прав доступа для объекта (кому и какие) |
| `AddAccessRecord` | Добавить запись прав доступа к объекту |
| `RemoveAllAccessRecords` | Удалить все ограничения доступа (сделать объект публичным) |
-| `GetObjectsWithRights` | Объекты с информацией о правах текущего пользователя |
+| `GetObjectsWithRights` | Объекты с информацией о правах текущего пользователя (до 20 записей прав на объект; некорректный GUID — ошибка) |
| `GetSubscribers` | Подписчики объекта (personIds пользователей) |
@@ -223,7 +267,7 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| Инструмент | Описание |
| ---------------- | ------------------------------------------------ |
-| `CreateLink` | Создать двустороннюю связь между двумя объектами |
+| `CreateLink` | Создать двустороннюю связь между двумя объектами (дубликат с тем же типом и именем не создаётся; допустимы только перечисленные типы) |
| `DeleteRelation` | Удалить связь между объектами |
@@ -233,13 +277,13 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| Инструмент | Описание |
| ----------------- | ------------------------------------------------------------------ |
| `GetChats` | Список чатов текущего пользователя |
-| `GetChat` | Информация о конкретном чате (тип, описание, связи, непрочитанные) |
-| `GetPersonalChat` | Найти личный чат с пользователем по personId |
+| `GetChat` | Информация о конкретном чате (тип, описание, связи, непрочитанные); несуществующий чат — ошибка |
+| `GetPersonalChat` | Личный чат с пользователем по personId (ошибка, если чата ещё нет; инструмент его не создаёт) |
| `GetChatMembers` | Участники чата (роли, статусы уведомлений) |
| `CreateChat` | Создать групповой чат |
-| `GetMessages` | Сообщения в чате |
+| `GetMessages` | Сообщения чата, skip=0 — самые новые; skip растёт назад по истории. Правки показываются с пометкой (ред.), реакции и markdown помечаются |
| `GetMessage` | Одно сообщение по GUID (автор, дата, тип, текст) |
-| `SearchMessages` | Поиск сообщений по тексту во всех или указанных чатах |
+| `SearchMessages` | Поиск сообщений по тексту в указанных или (при пустом chatIds) во всех чатах пользователя; некорректный GUID — ошибка |
| `GetRelatedChats` | Чаты, связанные с объектом (обсуждение задачи/документа) |
| `SendMessage` | Отправить сообщение в чат |
| `EditMessage` | Редактировать ранее отправленное сообщение |
@@ -254,7 +298,7 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| --------------------- | ---------------------------------------------- |
| `GetPersonalSettings` | Персональные настройки пользователя по разделу |
| `GetCommonSettings` | Общие настройки базы |
-| `ChangeSettings` | Изменить персональную или общую настройку |
+| `ChangeSettings` | Изменить настройку пользователя (personId) или оргединицы (orgUnitId); нужен один из двух |
### Отчёты (.repx)
@@ -313,8 +357,8 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| Инструмент | Описание |
| ---------------- | ------------------------------------------------------ |
-| `CreateTask` | Создать задачу (тип начинается с 'task_', из GetTypes) |
-| `CreateWorkflow` | Создать workflow (процесс) со стадиями и задачами |
+| `CreateTask` | Создать задачу (тип с префиксом 'task_'). deadline — yyyy-MM-dd, срок до 23:59:59 этого дня; некорректные deadline, attachmentIds (в т.ч. несуществующие объекты) и attributes дают ошибку |
+| `CreateWorkflow` | Создать пустой workflow (тип с префиксом 'workflow_', без стадий); инициатор по умолчанию — первая позиция пользователя |
### Подписи
@@ -322,7 +366,7 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| Инструмент | Описание |
| --------------------- | -------------------------------------------- |
-| `AddSignatureRequest` | Добавить запрос на подпись к файлу в объекте |
+| `AddSignatureRequest` | Добавить запрос на подпись к файлу в объекте (имя файла не найдено — ошибка) |
### Прочее
@@ -330,7 +374,7 @@ ExportCsv("tmp/filter_x.jsonl", "C:/result/docs.csv", "name,typeName,created")
| Инструмент | Описание |
| --------------- | ---------------------------------- |
-| `InvokeCommand` | Вызвать команду серверного расширения Pilot Server (только заранее зарегистрированные команды) |
+| `InvokeCommand` | Вызвать команду серверного расширения Pilot Server (только заранее зарегистрированные команды); ждёт и возвращает результат до 15 с |
---
diff --git a/Tools/AccessTools.cs b/Tools/AccessTools.cs
index 9bc23e5..75178f6 100644
--- a/Tools/AccessTools.cs
+++ b/Tools/AccessTools.cs
@@ -11,9 +11,16 @@ public class AccessTools
private readonly PilotConnection _connection;
public AccessTools(PilotConnection connection) => _connection = connection;
+ // Шкала прав с Pilot 26.20: Edit разбит на EditAttributes/EditFiles/Delete
+ private const string AccessLevelsHelp =
+ "Флаги: None, Create, EditAttributes, View, Freeze, Approve, Share, EditFiles, Delete. " +
+ "Комбинации: Edit = EditAttributes+EditFiles+Delete, ViewCreate, ViewEdit = View+Create+Edit, " +
+ "ViewEditApprove, Full. Agreement и ViewEditAgrement — устаревшие синонимы Approve и ViewEditApprove " +
+ "(в выводе могут печататься под старыми именами).";
+
[McpServerTool, Description(
"Проверить права доступа пользователя к объекту. " +
- "Уровни: None, Create, Edit, View, ViewCreate, ViewEdit, Freeze, Agreement, Share, Full.")]
+ AccessLevelsHelp)]
public Task CheckAccess(
[Description("GUID объекта")] string objectId,
[Description("ID пользователя (personId). Если 0, проверяет текущего.")] int personId = 0)
@@ -102,12 +109,11 @@ public Task GetAccessRecords(
}
[McpServerTool, Description(
- "Добавить запись прав доступа к объекту. " +
- "Уровни: None, Create, Edit, View, ViewCreate, ViewEdit, Freeze, Agreement, ViewEditAgrement, Share, Full.")]
+ "Добавить запись прав доступа к объекту. " + AccessLevelsHelp)]
public Task AddAccessRecord(
[Description("GUID объекта")] string objectId,
[Description("ID позиции (orgUnitId)")] int positionId,
- [Description("Уровень доступа: None, Create, Edit, View, ViewCreate, ViewEdit, Freeze, Agreement, ViewEditAgrement, Share, Full")] string accessLevel,
+ [Description("Уровень доступа: имя флага или несколько через запятую, например 'View,EditAttributes'")] string accessLevel,
[Description("Наследование: None, InheritUntilSecret, InheritWholeSubtree")] string inheritance = "InheritWholeSubtree",
[Description("Тип: Allow или Deny")] string accessType = "Allow")
{
@@ -123,8 +129,8 @@ public Task AddAccessRecord(
return ToolResult.Error($"Неизвестный тип доступа: {accessType}");
var modifier = _connection.CreateModifier();
- modifier.EditObject(guid).AddAccessRecord(positionId, level, DateTime.MaxValue, inh, aType, Array.Empty());
- if (modifier.AnyChanges()) modifier.Apply(null);
+ modifier.EditObject(guid).AddAccessRecord(positionId, level, DateTime.MaxValue, inh, aType);
+ if (modifier.AnyChanges()) _connection.ApplyAndWait(() => modifier.Apply(null));
return ToolResult.Ok($"Право доступа добавлено: позиция #{positionId}, уровень {accessLevel}.");
});
}
@@ -140,7 +146,7 @@ public Task RemoveAllAccessRecords(
var modifier = _connection.CreateModifier();
modifier.EditObject(guid).RemoveAccessRecords(_ => true);
- if (modifier.AnyChanges()) modifier.Apply(null);
+ if (modifier.AnyChanges()) _connection.ApplyAndWait(() => modifier.Apply(null));
return ToolResult.Ok($"Все записи доступа удалены с объекта {objectId}.");
});
}
diff --git a/Tools/AdminTools.cs b/Tools/AdminTools.cs
index 3624edc..ebe76de 100644
--- a/Tools/AdminTools.cs
+++ b/Tools/AdminTools.cs
@@ -1,4 +1,5 @@
using Ascon.Pilot.DataClasses;
+using Ascon.Pilot.Common;
using ModelContextProtocol.Server;
using System.ComponentModel;
@@ -11,34 +12,48 @@ public class AdminTools
public AdminTools(PilotConnection connection) => _connection = connection;
[McpServerTool, Description(
- "Обновить данные пользователя: email, телефон, комментарий, статус активности. " +
+ "Обновить данные пользователя по personId через админский API: email, телефон, комментарий, " +
+ "признак неактивности. Требует учётку администратора сервера. " +
"Все параметры, кроме personId, необязательны — обновляются только указанные.")]
public Task UpdatePerson(
[Description("ID пользователя (personId)")] int personId,
[Description("Новый email (пусто = не менять)")] string email = "",
[Description("Новый телефон (пусто = не менять)")] string phone = "",
[Description("Новый комментарий (пусто = не менять)")] string comment = "",
- [Description("Сделать неактивным (true/false, пусто = не менять)")] string isInactive = "")
+ [Description("Сделать неактивным: true/false (пусто = не менять)")] string isInactive = "")
{
return ToolRunner.RunWriteAsync(_connection, "UpdatePerson",
$"person={personId}, email={email}, phone={phone}, comment={comment}, isInactive={isInactive}", async () =>
{
- var updateInfo = new DPersonUpdateInfo { Id = Guid.NewGuid() };
-
- bool hasChanges = false;
- if (!string.IsNullOrEmpty(email)) { updateInfo.Email = email; hasChanges = true; }
- if (!string.IsNullOrEmpty(phone)) { updateInfo.Phone = phone; hasChanges = true; }
- if (!string.IsNullOrEmpty(comment)) { updateInfo.Comment = comment; hasChanges = true; }
- if (!string.IsNullOrEmpty(isInactive))
- {
- updateInfo.IsInactive = isInactive.Equals("true", StringComparison.OrdinalIgnoreCase);
- hasChanges = true;
- }
-
- if (!hasChanges)
+ if (personId <= 0)
+ return ToolResult.Error("personId должен быть положительным числом.");
+ if (string.IsNullOrEmpty(email) && string.IsNullOrEmpty(phone)
+ && string.IsNullOrEmpty(comment) && string.IsNullOrEmpty(isInactive))
return ToolResult.Error("Не указаны поля для обновления.");
- await _connection.ServerApi.UpdatePersonAsync(updateInfo);
+ // Клиентский UpdatePersonAsync правит только подключённого пользователя и запрещает email/phone,
+ // поэтому изменение идёт через админский API, как в UpdatePersonAdmin.
+ bool? inactive = string.IsNullOrEmpty(isInactive)
+ ? null : PeopleAdminTools.ParseBool(isInactive, "isInactive");
+
+ _connection.EnsureConnected();
+ await _connection.WithAdminApiAsync