### Example BinlogMcp tool interactions Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt These examples illustrate how to interact with the binlogmcp server using MCP tool calls. They show loading a binlog, searching for errors, retrieving node details, listing children, searching properties, preprocessing files, and printing a subtree. ```plaintext load_binlog(path: "/repo/msbuild.binlog") → path: /repo/msbuild.binlog fileSize: 2,345,678 bytes succeeded: True duration: 00:01:23.456 msbuildVersion: 17.8.3 ``` ```plaintext search(path: "/repo/msbuild.binlog", query: "$error") → 3 results (skip=0, take=200, matched=3) Error CS0246: The type or namespace 'Foo' could not be found [142] Error MSB4062: The task "Bar" could not be loaded [187] Build failed. ``` ```plaintext get_node(path: "/repo/msbuild.binlog", id: "142") → Error CS0246: The type or namespace 'Foo' could not be found [142] sourceFile: /repo/src/MyProject/Program.cs line: 10 parent: Project MyProject.csproj net8.0 → Build [88] childCount: 0 ``` ```plaintext get_children(path: "/repo/msbuild.binlog", id: "88", kind: "target") → parent: Project MyProject.csproj net8.0 → Build [88] filter: $target children: 12 (skip=0, take=200, total=12, unfiltered=245) Target _GenerateCompileDependencyCache [89] Target CoreCompile [97] ... ``` ```plaintext search_properties_and_items(path: "/repo/msbuild.binlog", contextId: "88", query: "OutputPath") → query: OutputPath context: Project MyProject.csproj net8.0 → Build [88] returned: 1 (skip=0, take=200, matched=1) OutputPath=bin\Debug\net8.0\ [211] ``` ```plaintext preprocess_file(path: "/repo/msbuild.binlog", evaluationId: "55") → file: /repo/src/MyProject/MyProject.csproj evaluation: [55] MyProject.csproj totalLines: 8432 lines: 1-500 1 | ... ``` ```plaintext print_subtree(path: "/repo/msbuild.binlog", id: "97", maxDepth: 2) → Target CoreCompile [97] Task Csc [98] ... 47 more (depth limit; call get_children(path, "98") to drill in) ``` -------------------------------- ### Install StructuredLogViewer with Homebrew Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/README.md Use this command to install the StructuredLogViewer application on macOS using Homebrew. ```bash brew install structuredlogviewer ``` -------------------------------- ### Install Binlog MCP Tool Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/readme.md Update the binlogmcp tool to the latest version using the dotnet CLI. ```bash dotnet tool update -g binlogmcp ``` -------------------------------- ### Hierarchical Scoping Examples Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/SearchSyntax.md Use 'under', 'notunder', 'project', and 'not' to define hierarchical search scopes. These can be nested. ```text $csc under($project Core) ``` ```text $error project(MyApp) ``` ```text $warning notunder($task Csc) ``` ```text $rar under(A) notunder(B) notunder(Evaluation) ``` ```text $metadata name=CopyToOutputDirectory value=PreserveNewest under($item .txt under($additem None)) ``` -------------------------------- ### Configure BinlogMcp server for VS Code Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt This JSON configuration sets up the binlogmcp server to be used as a tool within VS Code via the Model Context Protocol (MCP). Ensure the binlogmcp tool is installed globally. ```json // .vscode/mcp.json — configure the MCP server for VS Code { "servers": { "binlogmcp": { "type": "stdio", "command": "binlogmcp" } } } ``` -------------------------------- ### Read Records from Binary Log Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Use `BinaryLog.ReadRecords` for low-level, lazy access to build events. Suitable for scanning without loading the entire build tree. Examples show reading from files, streams, and byte arrays. ```csharp using Microsoft.Build.Logging.StructuredLogger; using Microsoft.Build.Framework; // Read all C# source files passed to the Csc compiler task foreach (var record in BinaryLog.ReadRecords("msbuild.binlog")) { if (record.Args is TaskCommandLineEventArgs cmd && cmd.TaskName == "Csc") { Console.WriteLine($"[Csc] {cmd.CommandLine}"); } } // Read from a stream (e.g., downloaded from a CI artifact) using var http = new HttpClient(); await using var stream = await http.GetStreamAsync("https://example.com/msbuild.binlog"); foreach (var record in BinaryLog.ReadRecords(stream)) { if (record.Args is BuildErrorEventArgs error) { Console.WriteLine($"ERROR {error.Code}: {error.Message} ({error.File}:{error.LineNumber})"); } } // Read from a byte array byte[] bytes = File.ReadAllBytes("msbuild.binlog"); int taskCount = BinaryLog.ReadRecords(bytes) .Count(r => r.Args is TaskStartedEventArgs); Console.WriteLine($"Total tasks executed: {taskCount}"); ``` -------------------------------- ### Read Compiler Invocations from .binlog Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Reading-Compiler-invocations Use this method to read compiler invocations from a specified .binlog file path. Ensure the MSBuild.StructuredLogger NuGet package is installed. ```csharp using Microsoft.Build.Logging.StructuredLogger; ... CompilerInvocationsReader.ReadInvocations(string binlogFilePath) ``` -------------------------------- ### Time Annotations for Display and Sort Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/SearchSyntax.md Append flags like $time, $start, or $end to include duration, start time, or end time in results and sort by them. These are not filters. ```text $task $time ``` ```text $target $time under($project MyApp) ``` -------------------------------- ### Compare Build Performance Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md Load two binlogs using `load_binlog` and run identical queries against each to compare build performance. Useful for identifying performance regressions or differences between builds. ```text count $error and count $warning per file ``` ```text search $task $time with maxResults=20 per file ``` ```text search $target Build $time per file ``` ```text count $project per file ``` -------------------------------- ### Build and Run Avalonia Version on Mac/Linux Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/README.md Clone the repository and run the provided script to build and launch the Avalonia version of the viewer on macOS or Linux. ```bash git clone https://github.com/KirillOsenkov/MSBuildStructuredLog cd MSBuildStructuredLog ./run.sh ``` -------------------------------- ### Generate Binary Log from Command Line Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/README.md Use the `/bl` switch with `msbuild.exe` to generate a binary log file. The log file will be created in the same directory as the project or solution being built. ```cmd msbuild solution.sln /t:Rebuild /v:diag /noconlog /logger:BinaryLogger,%localappdata%\MSBuildStructuredLogViewer\app-2.1.596\StructuredLogger.dll;1.binlog ``` -------------------------------- ### Time Interval Filters Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/SearchSyntax.md Filter results by start or end timestamps. Timestamps must be quoted and can use any DateTime.Parse-able format. ```text start<"2024-01-15 14:30:00" ``` ```text start>"2024-01-15 14:30:00" ``` ```text end<"2024-01-15 14:30:00.500" ``` ```text end>"2024-01-15 14:30:00.500" ``` -------------------------------- ### List Project Dependencies Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Search-Syntax Lists all dependencies, both direct and transitive, for a specified project. Use `project(.)` or `project(.csproj)` to search across all projects, though this can be slow. ```text $nuget project(MyProject.csproj) ``` -------------------------------- ### BinlogTool CLI: List NuGet Packages Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Uses the `BinlogTool` CLI to list all NuGet packages referenced during the build and save the report to a text file. ```bash binlogtool listnuget msbuild.binlog nuget-report.txt ``` -------------------------------- ### Get Ancestors of a Build Node Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md Retrieve the hierarchical ancestors of a specific build node (e.g., an error, task, or target) using its ID. This is useful for understanding the context of a particular event in the build log. ```text get_ancestors ``` -------------------------------- ### BinlogTool CLI: List Property Values Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Uses the `BinlogTool` CLI to list all property values set during the build process. ```bash binlogtool listproperties msbuild.binlog ``` -------------------------------- ### Read Build Tree from Binlog Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Reading-binlog-files-programmatically Use `BinaryLog.ReadBuild` to construct a complete build tree. This higher-level API is useful for understanding the overall build structure, including project dependencies, targets, and tasks. ```csharp using Microsoft.Build.Logging.StructuredLogger; // ... var build = BinaryLog.ReadBuild("path/to/your.binlog"); // Now you have a build tree structure to analyze Console.WriteLine($"Build started at: {build.StartTime}"); Console.WriteLine($"Number of projects: {build.Projects.Count}"); ``` -------------------------------- ### Enumerate Low-Level Records with Offsets Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Use BinLogReader.ReadRecords to enumerate all records from a .binlog file, including their byte position and length in the decompressed stream. This provides access to the deserialized BuildEventArgs, record kind, start offset, and length. ```csharp using Microsoft.Build.Logging.StructuredLogger; var reader = new BinLogReader(); // Enumerate with byte position metadata foreach (var record in reader.ReadRecords("msbuild.binlog")) { // record.Kind, record.Start, record.Length, record.Args if (record.Args is ProjectStartedEventArgs proj) { Console.WriteLine($" Project: {proj.ProjectFile} @ byte {record.Start} (len={record.Length})"); } } // Chunk the binlog by record boundary (useful for splitting/analysis tools) foreach (var chunk in reader.ChunkBinlog("msbuild.binlog")) { Console.WriteLine($"Kind={chunk.RecordKind} start={chunk.Start} len={chunk.Length}"); } ``` -------------------------------- ### Analyze Build Tree Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Reading-binlog-files-programmatically After reading a build using `BinaryLog.ReadBuild`, call `AnalyzeBuild` to perform various analyses on the build tree. This includes assigning node IDs, computing durations, and identifying performance bottlenecks. ```csharp using Microsoft.Build.Logging.StructuredLogger; // ... var build = BinaryLog.ReadBuild("path/to/your.binlog"); build.AnalyzeBuild(); // Now the build object is enriched with analysis data // For example, you can find the most expensive tasks: var expensiveTasks = build.FindMostExpensiveTasks(10); foreach (var task in expensiveTasks) { Console.WriteLine($"Task: {task.Name}, Duration: {task.Duration}"); } ``` -------------------------------- ### Find MSBuild Task Call Chain Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md Use `get_ancestors` starting from a deep `Project` node to trace the call chain of `MSBuild` tasks back to the entry project. `notunder($task MSBuild)` can help filter out redundant calls. ```text get_ancestors ``` ```text notunder($task MSBuild) ``` -------------------------------- ### Load Build Tree from Binary Log Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Use `BinaryLog.ReadBuild` to deserialize a `.binlog` into a structured `Build` object graph. Supports progress reporting and custom `ReaderSettings` for handling unknown data. ```csharp using Microsoft.Build.Logging.StructuredLogger; // Basic load Build build = BinaryLog.ReadBuild("msbuild.binlog"); Console.WriteLine($"Succeeded: {build.Succeeded}, Duration: {build.Duration}"); // With progress callback var progress = new Progress(update => Console.Write($"\rLoading... {update.Ratio:P0}")); Build build2 = BinaryLog.ReadBuild("large-build.binlog", progress); // With custom reader settings (tolerate unknown data from newer MSBuild) var settings = new ReaderSettings { UnknownDataBehavior = UnknownDataBehavior.Warning }; Build build3 = BinaryLog.ReadBuild("msbuild.binlog", settings); // From a stream with an embedded project imports archive using var stream = File.OpenRead("msbuild.binlog"); byte[] importsArchive = File.ReadAllBytes("msbuild.ProjectImports.zip"); Build build4 = BinaryLog.ReadBuild(stream, projectImportsArchive: importsArchive); // Enumerate all errors after loading build.VisitAllChildren(error => Console.WriteLine($"{error.Text}")); ``` -------------------------------- ### Standard Project SDK Import Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Exploding-Sdk-imports This is the standard way to import an SDK in an MSBuild project. Custom logic cannot be easily inserted after this import. ```xml ... ``` -------------------------------- ### BinlogTool - Search Tasks Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Reading-binlog-files-programmatically Use the `BinlogTool` command-line interface to list all tasks executed during the build within a .binlog file. ```bash binlogtool search msbuild.binlog $task ``` -------------------------------- ### Preprocess MSBuild Project File Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md The `preprocess_file` command generates the full, effective MSBuild XML for a project evaluation, inlining all imported files. This is useful for understanding the final state of properties and items, and which targets are in scope. ```text preprocess_file ``` ```text preprocess_file file= ``` -------------------------------- ### BinlogTool CLI: List MSBuild Tools Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Uses the `BinlogTool` CLI to list all MSBuild tasks and their originating assemblies. ```bash binlogtool listtools msbuild.binlog ``` -------------------------------- ### Configure .NET SDK Resolution Environment Variables Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/SDK-Resolution Set environment variables to control the .NET SDK resolution path and enable logging. Useful for debugging or custom SDK locations. ```batch set PATH=C:\msbuild\.dotnet;%PATH% set DOTNET_INSTALL_DIR=C:\msbuild\.dotnet set DOTNET_MULTILEVEL_LOOKUP=0 ``` -------------------------------- ### Publish Avalonia Version for Mac/Linux Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/README.md Build and publish the self-contained Avalonia version of the viewer. The output directory can be specified. ```bash dotnet build MSBuildStructuredLog.Avalonia.sln dotnet publish MSBuildStructuredLog.Avalonia.sln --self-contained -o ``` -------------------------------- ### xxHash64 Implementation Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/String-Hashing Implementation of the xxHash64 algorithm, known for its speed and good distribution. ```csharp public static ulong XxHash64(string s) { ulong hash = 0xcbf29ce484222325UL; foreach (var c in s) { hash ^= c; hash *= 0x100000001b3UL; } return hash; } ``` -------------------------------- ### Generate Binary Log with MSBuild Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Matrix Use the /bl flag with MSBuild to generate a binary log file. This is applicable for MSBuild versions 15.3 and newer. ```bash msbuild src.binlog /bl:dst.binlog ``` -------------------------------- ### Create Runner Script for Avalonia Version Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/README.md Create a shell script to execute the published Avalonia viewer application. This script should be added to your system's PATH. ```bash #! /bin/sh exec dotnet ${HOME}/tools/artifacts/StructuredLogViewer.Avalonia/publish/StructuredLogViewer.Avalonia.dll "$@" ``` -------------------------------- ### Search NuGet Packages by File Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Search-Syntax Searches for files originating from NuGet packages within a specific project. Use `project(.)` or `project(.csproj)` to search across all projects, though this can be slow. ```text $nuget project(MyProject.csproj) File.dll ``` -------------------------------- ### Search NuGet Packages by Version Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Search-Syntax Searches for NuGet packages matching a specific version or version range within a project's dependencies. Use `project(.)` or `project(.csproj)` to search across all projects, though this can be slow. ```text $nuget project(MyProject.csproj) 13.0.3 ``` -------------------------------- ### Exploded SDK Imports for Custom Logic Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Exploding-Sdk-imports Manually import Sdk.props and Sdk.targets to allow for custom logic insertion after Sdk.targets. This method gives explicit control over the import order. ```xml ... ``` -------------------------------- ### BinlogTool - Search Warnings Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Reading-binlog-files-programmatically Use the `BinlogTool` command-line interface to search for all warning messages within a .binlog file. ```bash binlogtool search msbuild.binlog $warning ``` -------------------------------- ### Command-line binlogtool operations Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt These commands demonstrate various functionalities of the binlogtool for analyzing MSBuild binary logs, such as detecting double-writes, saving strings, redacting secrets, and dumping record statistics. ```bash binlogtool doublewrites msbuild.binlog double-writes.txt ``` ```bash binlogtool savestrings msbuild.binlog strings.txt ``` ```bash binlogtool redact --input:msbuild.binlog --in-place -p:MySecretToken -p:AnotherSecret ``` ```bash binlogtool dumprecords msbuild.binlog --include-rollup --include-total ``` -------------------------------- ### Update and Run refdump Tool Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Graph Update the `refdump` tool globally and then run it to generate an assembly dependency graph. The output can be opened in the MSBuild Structured Log Viewer. ```bash dotnet tool update -g refdump ``` ```bash refdump -g ``` -------------------------------- ### BinaryLog.ReadBuild — High-level build tree loader Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Deserializes a `.binlog` into a fully structured `Build` object graph. Supports optional progress reporting and `ReaderSettings` to control behavior when encountering unknown data from newer MSBuild versions. ```APIDOC ## BinaryLog.ReadBuild ### Description Deserializes a `.binlog` into a fully structured `Build` object graph. Supports optional progress reporting and `ReaderSettings` to control behavior when encountering unknown data from newer MSBuild versions (`ThrowException`, `Ignore`, `Warning`, `Error`, or `Message`). ### Method ```csharp public static Build ReadBuild(string logFilePath, IProgress? progress = null, ReaderSettings? settings = null) public static Build ReadBuild(Stream stream, byte[]? projectImportsArchive = null, IProgress? progress = null, ReaderSettings? settings = null) ``` ### Parameters #### Path Parameters - **logFilePath** (string) - Path to the .binlog file. #### Request Body - **stream** (Stream) - Stream to read .binlog data from. - **projectImportsArchive** (byte[]) - Optional byte array containing the embedded project imports archive. - **progress** (IProgress?) - Optional progress reporter. - **settings** (ReaderSettings?) - Optional settings to control reader behavior. ### Request Example ```csharp // Basic load Build build = BinaryLog.ReadBuild("msbuild.binlog"); Console.WriteLine($"Succeeded: {build.Succeeded}, Duration: {build.Duration}"); // With progress callback var progress = new Progress(update => Console.Write($"\rLoading... {update.Ratio:P0}")); Build build2 = BinaryLog.ReadBuild("large-build.binlog", progress); // With custom reader settings (tolerate unknown data from newer MSBuild) var settings = new ReaderSettings { UnknownDataBehavior = UnknownDataBehavior.Warning }; Build build3 = BinaryLog.ReadBuild("msbuild.binlog", settings: settings); // From a stream with an embedded project imports archive using var stream = File.OpenRead("msbuild.binlog"); byte[] importsArchive = File.ReadAllBytes("msbuild.ProjectImports.zip"); Build build4 = BinaryLog.ReadBuild(stream, projectImportsArchive: importsArchive); // Enumerate all errors after loading build.VisitAllChildren(error => Console.WriteLine($"{error.Text}")); ``` ### Response #### Success Response - **Build** - A `Build` object representing the structured log data. ### Response Example ```json // The Build object contains a hierarchical structure of nodes like ProjectEvaluation, Project, Target, Task, Message, Error, Warning. // Example properties: // - Succeeded: bool // - Duration: TimeSpan ``` ``` -------------------------------- ### Configure VS Code for Binlog MCP Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/readme.md Add the binlogmcp server configuration to your VS Code settings file (.vscode/mcp.json) to enable MCP-aware client functionality. ```json { "servers": { "binlogmcp": { "type": "stdio", "command": "binlogmcp" } } } ``` -------------------------------- ### Display Project Dependency Graph in Dot Syntax Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Graph This Dot syntax represents the project dependency graph. It can be used to visualize the relationships between different projects in a build. ```dot digraph { "StructuredLogger.Tests" -> "StructuredLogViewer.Core" "StructuredLogger.Tests" -> StructuredLogger "StructuredLogger.Utils" -> StructuredLogger "StructuredLogViewer.Avalonia" -> "StructuredLogViewer.Core" "StructuredLogViewer.Avalonia" -> StructuredLogger "StructuredLogViewer.Core" -> StructuredLogger BinlogTool -> "StructuredLogger.Utils" BinlogTool -> StructuredLogger StructuredLogViewer -> "StructuredLogger.Utils" StructuredLogViewer -> "StructuredLogViewer.Core" StructuredLogViewer -> StructuredLogger StructuredLogViewer -> TaskRunner TaskRunner -> "StructuredLogViewer.Core" TaskRunner -> StructuredLogger } ``` -------------------------------- ### Traverse Project Reference Graph Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md Utilize the $projectreference token to explore the project-to-project dependency graph. This helps understand project relationships and identify what touches a specific project. ```text search $projectreference ``` ```text search $projectreference project(Foo.csproj) ``` -------------------------------- ### Search for Executed Targets in MSBuild Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md Use the `$target` search combined with `$time` to find targets sorted by duration, helping to identify performance bottlenecks. Scoping to a specific project is possible. ```text search $target $time project(Foo.csproj) ``` -------------------------------- ### Enrich Build Tree with BuildAnalyzer Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Call BuildAnalyzer.AnalyzeBuild after reading a build log to enrich the tree with node indices, double-write detection, task summaries, and more. This is required before performing searches. ```csharp using Microsoft.Build.Logging.StructuredLogger; using StructuredLogViewer; Build build = BinaryLog.ReadBuild("msbuild.binlog"); // Enrich the build tree — required before searching BuildAnalyzer.AnalyzeBuild(build); // Now the build has assigned node indices, double-write info, etc. Console.WriteLine($"Analyzed: {build.IsAnalyzed}"); // True // Find the top-level "DoubleWrites" folder if any double-writes occurred var doubleWritesFolder = build.FindChild(f => f.Name == "DoubleWrites"); if (doubleWritesFolder != null) { doubleWritesFolder.VisitAllChildren(item => Console.WriteLine($"Double write destination: {item.Text}")); } // Access task assembly registry (populated during analysis) foreach (var kvp in build.TaskAssemblies) { Console.WriteLine($"Assembly: {kvp.Key}"); foreach (var taskName in kvp.Value) Console.WriteLine($" Task: {taskName}"); } ``` -------------------------------- ### BinlogTool CLI: Search under a Specific Project Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Uses the `BinlogTool` CLI to search a `.binlog` file for `csc` tasks specifically within the `MyLib.csproj` project. ```bash binlogtool search msbuild.binlog "$csc under($project MyLib.csproj)" ``` -------------------------------- ### FNV-1a 64-bit Fast Hash Implementation Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/String-Hashing An optimized version of the FNV-1a 64-bit hash algorithm, potentially offering faster execution. ```csharp public static ulong Fnv1a64Fast(string s) { ulong hash = 14695981039346656037UL; foreach (var c in s) { hash ^= c; hash *= 1099511627776UL; } return hash; } ``` -------------------------------- ### Enable Property Tracking Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md Set the MSBUILDLOGPROPERTYTRACKING environment variable to a specific value (e.g., 15) before building to capture detailed property assignments and reassignments during evaluation. This requires a new binlog to be generated. ```powershell MSBUILDLOGPROPERTYTRACKING=15 ``` -------------------------------- ### BinLogReader.Replay Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Replays all BuildEventArgs from a .binlog file by firing standard MSBuild IEventSource events. This is useful for attaching existing MSBuild logger infrastructure to a recorded build file. ```APIDOC ## BinLogReader.Replay — Event-source replay ### Description Replays all `BuildEventArgs` from a `.binlog` by firing standard MSBuild `IEventSource` events (`TargetStarted`, `MessageRaised`, `ErrorRaised`, etc.). Useful for attaching existing MSBuild logger infrastructure to a recorded build file. ### Method `BinLogReader.Replay(string binlogFilePath, IProgress progress = null)` ### Parameters #### Path Parameters - **binlogFilePath** (string) - Required - The path to the `.binlog` file. - **progress** (IProgress) - Optional - A progress reporter to track replay progress. ### Event Handlers - **ErrorRaised**: Fired when an error event is encountered. - **WarningRaised**: Fired when a warning event is encountered. - **ProjectStarted**: Fired when a project starts. - **OnFileFormatVersionRead**: Fired when the binlog format version is read. - **OnException**: Fired when an exception occurs during reading. ### Request Example ```csharp using Microsoft.Build.Logging.StructuredLogger; using Microsoft.Build.Framework; var reader = new BinLogReader(); // Subscribe to individual event types reader.ErrorRaised += (sender, args) => Console.WriteLine($"ERROR [{args.Code}] {args.Message} in {args.File}:{args.LineNumber}"); reader.WarningRaised += (sender, args) => Console.WriteLine($"WARN [{args.Code}] {args.Message}"); reader.ProjectStarted += (sender, args) => Console.WriteLine($"Project started: {args.ProjectFile}"); reader.OnFileFormatVersionRead += version => Console.WriteLine($"Binlog format version: {version}"); reader.OnException += ex => Console.Error.WriteLine($"Read error: {ex.Message}"); // Replay with progress var progress = new Progress(u => Console.Write($"\r{u.Ratio:P0} ({u.BufferLength} buffered)")); reader.Replay("msbuild.binlog", progress); Console.WriteLine("\nDone."); ``` ### Response This method replays events and does not return a value directly, but triggers event handlers. ``` -------------------------------- ### Read Records from Binlog Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Reading-binlog-files-programmatically Use `BinaryLog.ReadRecords` for low-level access to individual build event records. This API is suitable when you need to process each event as it occurs. ```csharp using Microsoft.Build.Logging.StructuredLogger; // ... var log = BinaryLog.ReadRecords("path/to/your.binlog"); foreach (var record in log.Records) { // Process each record if (record.Type == RecordType.BuildError) { var errorRecord = (BuildErrorEventArgs)record.Data; Console.WriteLine($"Error: {errorRecord.Message}"); } } ``` -------------------------------- ### Replay Build Events with BinLogReader Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Use BinLogReader to replay all BuildEventArgs from a .binlog file by firing standard MSBuild IEventSource events. This is useful for attaching existing MSBuild logger infrastructure to a recorded build file. ```csharp using Microsoft.Build.Logging.StructuredLogger; using Microsoft.Build.Framework; var reader = new BinLogReader(); // Subscribe to individual event types reader.ErrorRaised += (sender, args) => Console.WriteLine($"ERROR [{args.Code}] {args.Message} in {args.File}:{args.LineNumber}"); reader.WarningRaised += (sender, args) => Console.WriteLine($"WARN [{args.Code}] {args.Message}"); reader.ProjectStarted += (sender, args) => Console.WriteLine($"Project started: {args.ProjectFile}"); reader.OnFileFormatVersionRead += version => Console.WriteLine($"Binlog format version: {version}"); reader.OnException += ex => Console.Error.WriteLine($"Read error: {ex.Message}"); // Replay with progress var progress = new Progress(u => Console.Write($"\r{u.Ratio:P0} ({u.BufferLength} buffered)")); reader.Replay("msbuild.binlog", progress); Console.WriteLine("\nDone."); ``` -------------------------------- ### Check Incremental Build Status Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md Use `msbuild /question` to determine if a subsequent build would be considered up-to-date or if it would perform work. This helps in understanding incremental build behavior. ```bash msbuild /question ``` -------------------------------- ### Search NuGet Packages by Name Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Search-Syntax Searches for NuGet packages by their name within a specific project's dependencies and resolved packages. Use `project(.)` or `project(.csproj)` to search across all projects, though this can be slow. ```text $nuget project(MyProject.csproj) Package.Name ``` -------------------------------- ### Search NuGet Dependencies Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md Use the $nuget token to search the synthetic NuGet dependency graph. Specify a project to narrow the search scope. Useful for finding which projects include a specific NuGet package and version. ```text search $nuget project(Foo.csproj) ``` ```text search $nuget Newtonsoft.Json ``` ```text search $nuget Newtonsoft.Json 13.0.3 ``` ```text search $nuget project(Foo.csproj) Newtonsoft.Json ``` ```text search $nuget project(Foo.csproj) File.dll ``` ```text search $nuget project(.) Newtonsoft.Json 13.0.3 ``` -------------------------------- ### Traverse MSBuild build tree with Build.VisitAllChildren Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt This C# code demonstrates using the `VisitAllChildren` method to traverse the MSBuild build tree and collect specific node types like errors, projects, tasks, and properties. Ensure the Microsoft.Build.Logging.StructuredLogger library is referenced. ```csharp using Microsoft.Build.Logging.StructuredLogger; Build build = BinaryLog.ReadBuild("msbuild.binlog"); BuildAnalyzer.AnalyzeBuild(build); // Collect all error texts var allErrors = new List(); build.VisitAllChildren(e => allErrors.Add(e.Text)); Console.WriteLine($"Total errors: {allErrors.Count}"); // Collect all project files built var projectFiles = new HashSet(StringComparer.OrdinalIgnoreCase); build.VisitAllChildren(p => { if (!string.IsNullOrEmpty(p.ProjectFile)) projectFiles.Add(p.ProjectFile); }); Console.WriteLine($"Projects built: {projectFiles.Count}"); foreach (var f in projectFiles) Console.WriteLine($" {f}"); // Find all tasks longer than 5 seconds build.VisitAllChildren(t => { if (t.Duration.TotalSeconds > 5) Console.WriteLine($"Slow task: {t.Name} in {t.GetNearestParent()?.ProjectFile} ({t.Duration:g})"); }); // Find all property reassignments build.VisitAllChildren(p => { // Properties inside a PropertyReassignment folder are overrides if (p.Parent?.Name == "PropertyReassignment") Console.WriteLine($"Reassigned: {p.Name} = {p.Value}"); }); ``` -------------------------------- ### 32-bit FNV-1a Collision Comparison (Console Output) Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/String-Hashing Compares the collision counts and elapsed times for the fast and canonical 32-bit FNV-1a hashing implementations. Results may vary. ```text Fnv1a32Fast Collisions: 15 Elapsed: 00:00:00.9699976 Fnv1a32 Collisions: 8 Elapsed: 00:00:01.7843502 ``` ```text Fnv1a32Fast Collisions: 9 Elapsed: 00:00:00.2443658 Fnv1a32 Collisions: 17 Elapsed: 00:00:00.4131953 ``` -------------------------------- ### Profile MSBuild Evaluation Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md Pass the `/profileevaluation` switch to MSBuild to gather detailed performance data for each project evaluation. This is useful for diagnosing slow evaluation times. ```bash /profileevaluation ``` -------------------------------- ### BinlogTool CLI: Search for Csc Task Invocations Source: https://context7.com/kirillosenkov/msbuildstructuredlog/llms.txt Uses the `BinlogTool` CLI to search a `.binlog` file for all invocations of the `Csc` task. ```bash binlogtool search msbuild.binlog $task Csc ``` -------------------------------- ### Marvin Hash Implementation Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/String-Hashing Implementation of the Marvin hash algorithm. This algorithm is noted for its collision resistance. ```csharp public static uint Marvin(string s) { uint hash = 0; foreach (var c in s) { hash = ((hash << 5) + hash) + c; } return hash; } ``` -------------------------------- ### Find Slowest Tasks in MSBuild Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md Use the `$task` search with `$time` to list tasks sorted by duration, highlighting the slowest executing tasks in the build process. A `Total duration` header is provided. ```text search $task $time ``` -------------------------------- ### FNV-1a 64-bit Hash Implementation Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/String-Hashing This snippet implements the FNV-1a 64-bit hash algorithm. It's a good choice for performance and low collision rates with large datasets. ```csharp public static ulong Fnv1a64(string s) { ulong hash = 14695981039346656037UL; foreach (var c in s) { hash ^= c; hash *= 1099511627776UL; } return hash; } ``` -------------------------------- ### Find Projects by Height/Depth Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Search-Syntax Filters projects based on their height or depth in the project reference graph. `height=0` finds projects with no references, and `height=max` displays the maximum height. ```text $project height=0 ``` ```text $project height=1 ``` ```text $project height=max ``` -------------------------------- ### Parse GitHub Release Assets with jq Source: https://github.com/kirillosenkov/msbuildstructuredlog/wiki/Stats This command uses `jq` to filter and extract specific information from a GitHub releases JSON file. It selects assets that are .nupkg files or contain 'RELEASES' in their name, and outputs their name, download count, and creation date. ```bash cat releases.json | jq '.[] | .assets[] | select((.name | endswith(".nupkg")) or (.name | contains("RELEASES"))) | { name: .name, download_count: .download_count, created_at: .created_at }' ``` -------------------------------- ### Search for Target Declarations in Preprocessed XML Source: https://github.com/kirillosenkov/msbuildstructuredlog/blob/main/src/BinlogMcp/LlmGuide.md After preprocessing a project file, you can search the resulting XML for target declarations to verify if a target was included or excluded due to conditions. ```text search_files "