Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,12 @@ jobs:
run: |
$serverDir = "mcp-server\AccUnit.McpServer\bin\Release\net48"
if (-not (Test-Path "$serverDir\AccUnit.McpServer.exe")) { throw "AccUnit.McpServer.exe not found in $serverDir" }
if (-not (Test-Path "$serverDir\skills\accunit-tests\SKILL.md")) { throw "Skill accunit-tests not found in $serverDir\skills" }
$files = @(Get-ChildItem -Path $serverDir -File | Where-Object { $_.Extension -ne '.pdb' })
$files | Format-Table Name, Length, LastWriteTime
$zipFile = "build\AccUnit.McpServer.$env:VERSION.zip"
Compress-Archive -Path $files.FullName -DestinationPath $zipFile -Force
# The folder skills (skill accunit-tests) is installed with the tool accunit_install_skill
Compress-Archive -Path (@($files.FullName) + "$serverDir\skills") -DestinationPath $zipFile -Force

# The artifact name is used by release.yml
- name: "Upload MCP server zip"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,9 @@
<InternalsVisibleTo Include="AccessCodeLib.AccUnit.McpServer.Tests" />
</ItemGroup>

<!-- The skill is shipped next to the exe (skills\accunit-tests) and installed with accunit_install_skill -->
<ItemGroup>
<None Include="..\skills\**\*" Link="skills\%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

</Project>
18 changes: 13 additions & 5 deletions mcp-server/AccUnit.McpServer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,24 @@ private static async Task Main(string[] args)
builder.Services.AddSingleton<TestRunService>();
builder.Services.AddSingleton<TestClassDraftService>();
builder.Services.AddSingleton<TestEnvironmentService>();
builder.Services.AddSingleton<TestClassImportService>();
builder.Services.AddSingleton<TestModuleExportService>();
builder.Services.AddSingleton(_ => new SkillInstaller());
builder.Services
.AddMcpServer(options => options.ServerInfo = new Implementation
.AddMcpServer(options =>
{
Name = ServerName,
// The server is released together with AccUnit and uses its version.
Version = typeof(AccessCodeLib.AccUnit.Interop.AccUnitFactory).Assembly.GetName().Version.ToString(3)
options.ServerInfo = new Implementation
{
Name = ServerName,
// The server is released together with AccUnit and uses its version.
Version = typeof(AccessCodeLib.AccUnit.Interop.AccUnitFactory).Assembly.GetName().Version.ToString(3)
};
options.ServerInstructions = TestAuthoringGuide.Text;
})
.WithStdioServerTransport()
.WithTools<SessionTools>()
.WithTools<TestTools>();
.WithTools<TestTools>()
.WithTools<SkillTools>();

await builder.Build().RunAsync();
}
Expand Down
161 changes: 161 additions & 0 deletions mcp-server/AccUnit.McpServer/SkillInstaller.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace AccessCodeLib.AccUnit.McpServer
{
/// <summary>
/// Installs the skill accunit-tests that is shipped with the server (folder skills next to the exe)
/// into a project or the user profile. An installed skill is never overwritten without overwrite = true,
/// because it may contain local improvements; overwritten files are backed up first.
/// </summary>
public sealed class SkillInstaller
{
public const string TargetClaude = "claude";
public const string TargetAgents = "agents";
public const string ScopeProject = "project";
public const string ScopeUser = "user";

private const string BackupExtension = ".bak";
private static readonly Dictionary<string, string> TargetFolders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ TargetClaude, ".claude" }, // Claude Code (also read by Copilot)
{ TargetAgents, ".agents" } // Codex, GitHub Copilot, Gemini CLI
};

private readonly string _bundledSkillDirectory;
private readonly string _userProfileDirectory;

public SkillInstaller()
: this(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "skills", TestAuthoringGuide.SkillName),
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))
{
}

public SkillInstaller(string bundledSkillDirectory, string userProfileDirectory)
{
_bundledSkillDirectory = bundledSkillDirectory;
_userProfileDirectory = userProfileDirectory;
}

public string GetTargetDirectory(string target, string scope, string projectPath)
{
if (string.IsNullOrWhiteSpace(target) || !TargetFolders.TryGetValue(target, out var agentFolder))
throw new DatabaseSessionException("Unknown target '" + target + "'. Allowed: " + TargetClaude + ", " + TargetAgents + ".");

string baseDirectory;
if (string.Equals(scope, ScopeUser, StringComparison.OrdinalIgnoreCase))
{
baseDirectory = _userProfileDirectory;
}
else if (string.IsNullOrWhiteSpace(scope) || string.Equals(scope, ScopeProject, StringComparison.OrdinalIgnoreCase))
{
baseDirectory = GetCheckedProjectDirectory(projectPath);
}
else
{
throw new DatabaseSessionException("Unknown scope '" + scope + "'. Allowed: " + ScopeProject + ", " + ScopeUser + ".");
}

return Path.Combine(baseDirectory, agentFolder, "skills", TestAuthoringGuide.SkillName);
}

public SkillInstallResult Install(string target, string scope, string projectPath, bool overwrite)
{
var sourceFiles = GetBundledSkillFiles();
var targetDirectory = GetTargetDirectory(target, scope, projectPath);
var result = new SkillInstallResult { TargetDirectory = targetDirectory };

var existingFiles = sourceFiles.Where(file => File.Exists(GetTargetFile(file, targetDirectory))).ToList();
var differingFiles = existingFiles.Where(file => !FilesAreEqual(file, GetTargetFile(file, targetDirectory))).ToList();

if (existingFiles.Count == 0)
{
CopyFiles(sourceFiles, targetDirectory, result);
result.Status = SkillInstallStatus.Installed;
}
else if (differingFiles.Count == 0 && existingFiles.Count == sourceFiles.Count)
{
result.Status = SkillInstallStatus.UpToDate;
}
else if (!overwrite)
{
result.Status = SkillInstallStatus.AlreadyInstalledDifferent;
result.Message = "The installed skill differs from the version shipped with the server (it may contain local changes). " +
"Nothing was changed; use overwrite = true to replace it (a backup is made).";
}
else
{
foreach (var file in differingFiles)
{
var targetFile = GetTargetFile(file, targetDirectory);
var backupFile = targetFile + BackupExtension;
File.Copy(targetFile, backupFile, true);
result.BackupFiles.Add(backupFile);
}
CopyFiles(sourceFiles, targetDirectory, result);
result.Status = SkillInstallStatus.Updated;
}
return result;
}

private List<string> GetBundledSkillFiles()
{
if (!Directory.Exists(_bundledSkillDirectory))
throw new DatabaseSessionException("The skill shipped with the server was not found: " + _bundledSkillDirectory);
return Directory.GetFiles(_bundledSkillDirectory, "*", SearchOption.AllDirectories).ToList();
}

private static string GetCheckedProjectDirectory(string projectPath)
{
if (string.IsNullOrWhiteSpace(projectPath))
throw new DatabaseSessionException("projectPath is required for scope project (the root directory of the project).");
if (!Path.IsPathRooted(projectPath))
throw new DatabaseSessionException("projectPath must be an absolute path.");
var fullPath = Path.GetFullPath(projectPath);
if (!Directory.Exists(fullPath))
throw new DatabaseSessionException("The project directory does not exist: " + fullPath);
return fullPath;
}

private string GetTargetFile(string sourceFile, string targetDirectory)
{
var relativePath = sourceFile.Substring(_bundledSkillDirectory.TrimEnd(Path.DirectorySeparatorChar).Length + 1);
return Path.Combine(targetDirectory, relativePath);
}

private void CopyFiles(IEnumerable<string> sourceFiles, string targetDirectory, SkillInstallResult result)
{
foreach (var file in sourceFiles)
{
var targetFile = GetTargetFile(file, targetDirectory);
Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
File.Copy(file, targetFile, true);
result.Files.Add(targetFile);
}
}

private static bool FilesAreEqual(string file1, string file2)
{
return File.ReadAllBytes(file1).SequenceEqual(File.ReadAllBytes(file2));
}
}

public enum SkillInstallStatus
{
Installed,
UpToDate,
AlreadyInstalledDifferent,
Updated
}

public class SkillInstallResult
{
public SkillInstallStatus Status { get; set; }
public string TargetDirectory { get; set; }
public List<string> Files { get; set; } = new List<string>();
public List<string> BackupFiles { get; set; } = new List<string>();
public string Message { get; set; }
}
}
39 changes: 39 additions & 0 deletions mcp-server/AccUnit.McpServer/SkillTools.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.ComponentModel;
using ModelContextProtocol;
using ModelContextProtocol.Server;

namespace AccessCodeLib.AccUnit.McpServer
{
[McpServerToolType]
public class SkillTools
{
private readonly SkillInstaller _skillInstaller;

public SkillTools(SkillInstaller skillInstaller)
{
_skillInstaller = skillInstaller;
}

[McpServerTool(Name = "accunit_install_skill")]
[Description("Installs the skill accunit-tests (guide for writing and running AccUnit tests) shipped with this server. " +
"target \"claude\": .claude/skills (Claude Code, also read by GitHub Copilot); target \"agents\": .agents/skills " +
"(Codex, GitHub Copilot, Gemini CLI). scope \"project\" (default) installs into the project directory, so the skill is " +
"only active in projects that use AccUnit; scope \"user\" installs into the user profile. An installed skill is not " +
"overwritten unless overwrite = true (it may contain local improvements); changed files are backed up as .bak first.")]
public SkillInstallResult InstallSkill(
[Description("\"claude\" or \"agents\".")] string target = SkillInstaller.TargetClaude,
[Description("\"project\" (default) or \"user\".")] string scope = SkillInstaller.ScopeProject,
[Description("Absolute path of the project root directory (required for scope \"project\").")] string projectPath = null,
[Description("Replace an installed skill that differs from the shipped version (backup as .bak).")] bool overwrite = false)
{
try
{
return _skillInstaller.Install(target, scope, projectPath, overwrite);
}
catch (DatabaseSessionException ex)
{
throw new McpException(ex.Message);
}
}
}
}
23 changes: 23 additions & 0 deletions mcp-server/AccUnit.McpServer/SourceFileBackup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.IO;

namespace AccessCodeLib.AccUnit.McpServer
{
/// <summary>
/// Keeps a copy of a source file before an export writes over it (the file may contain work not yet imported).
/// </summary>
public static class SourceFileBackup
{
private const string BackupExtension = ".bak";

/// <returns>Path of the backup, or null if the file does not exist.</returns>
public static string BackupIfExists(string filePath)
{
if (!File.Exists(filePath))
return null;

var backupPath = filePath + BackupExtension;
File.Copy(filePath, backupPath, true);
return backupPath;
}
}
}
38 changes: 38 additions & 0 deletions mcp-server/AccUnit.McpServer/TestAuthoringGuide.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
namespace AccessCodeLib.AccUnit.McpServer
{
/// <summary>
/// Server instructions sent to every MCP client. Kept short: the full guide is the skill accunit-tests
/// (skills/accunit-tests/SKILL.md). Only the rules that depend on the AccUnit core are repeated here,
/// so clients without skill support get them as well.
/// </summary>
public static class TestAuthoringGuide
{
public const string SkillName = "accunit-tests";

public const string Text =
@"AccUnit MCP server: run and write AccUnit tests for the VBA code of a Microsoft Access database.

To write tests for a module, start with accunit_generate_test_class. Do not read the source of the module under test
first, neither the exported source files nor through other tools.

Use the skill accunit-tests for writing and running tests. If it is not available in the project, offer to install it
with accunit_install_skill (target ""claude"" for Claude Code, ""agents"" for Codex, Copilot and Gemini).

Essential rules if the skill is not available:
- For methods with parameters prefer ONE row test with several 'AccUnit:Row(inputs..., expected).Name(""case"") lines
above the test Sub over one test per case.
- Row values are VB.NET expressions, not VBA: no constants or enums of the own VBA project (use the numeric value),
no VBA functions (dates: System.Convert.ToDateTime(""2014-05-16"")); arrays next to other values as {""a"", ""b""},
Array(...) only as the only value of a row.
- Iz.EqualTo distinguishes vbNullString and """".
- The specification is the method name plus the declaration and comment returned by accunit_generate_test_class;
do not read the body of the method under test on your own. If the expected behavior cannot be derived, ask the
developer once how to proceed (assume values, look at the code, developer specifies, leave out).
- Expected error: Assert.Throws with the VBA error number as seen in Err.Number (e.g. Assert.Throws 457).
- Save the test class as <TestClassName>.cls in the testFolder returned by accunit_generate_test_class and import it
with accunit_import_test_classes.
- If the module already has a test class, the draft name gets a number (e.g. modCalcTests1): create, import and run it,
then ask the developer whether to merge it into the existing class (accunit_export_test_classes,
accunit_remove_test_classes), replace the existing class or keep both.";
}
}
3 changes: 3 additions & 0 deletions mcp-server/AccUnit.McpServer/TestClassDraft.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ public class TestClassDraft
public string TestClassName { get; set; }
public string ModuleUnderTest { get; set; }
public string SourceCode { get; set; }

/// <summary>AccUnit test folder of the database: default folder of accunit_import_test_classes.</summary>
public string TestFolder { get; set; }
public List<MethodUnderTest> MethodsUnderTest { get; set; } = new List<MethodUnderTest>();
}

Expand Down
10 changes: 10 additions & 0 deletions mcp-server/AccUnit.McpServer/TestClassDraftService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using AccessCodeLib.AccUnit.Configuration;
using AccessCodeLib.AccUnit.Tools;
using AccessCodeLib.Common.VBIDETools;
using Microsoft.Vbe.Interop;
Expand Down Expand Up @@ -53,6 +54,7 @@ private static TestClassDraft CreateDraft(VBProject vbProject, CodeModuleReader
TestClassName = new TestClassNameGenerator(vbProject).GetTestClassName(moduleName),
ModuleUnderTest = moduleName,
SourceCode = generator.GenerateSourceCode(),
TestFolder = GetTestFolder(vbProject),
MethodsUnderTest = members.Select(member => new MethodUnderTest
{
Name = member.Name,
Expand All @@ -63,6 +65,14 @@ private static TestClassDraft CreateDraft(VBProject vbProject, CodeModuleReader
};
}

private static string GetTestFolder(VBProject vbProject)
{
using (var testClassManager = new TestClassManager(new VBProjectOnlyApplicatonHelper(vbProject)))
{
return testClassManager.ImportDirectory;
}
}

private static List<CodeModuleMember> SelectMembers(List<CodeModuleMember> publicMembers, IList<string> methodNames)
{
if (methodNames == null || methodNames.Count == 0)
Expand Down
Loading