From 734c6cb753260e0e27b5c277accef978de4715f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Tue, 17 Nov 2026 13:50:17 +0100 Subject: [PATCH] Guard MCP server against foreign or unopened Access instances Refuse an Access instance that was already running before the server requested one and release it without quitting. Quit the own instance and report an error when OpenCurrentDatabase returns without opening the database, which was seen while another Access automation was running. --- .../AccessInstanceOwnership.cs | 23 +++++++ mcp-server/AccUnit.McpServer/AccessSession.cs | 60 ++++++++++++++++++- mcp-server/README.md | 4 +- .../AccessInstanceOwnershipTests.cs | 25 ++++++++ 4 files changed, 109 insertions(+), 3 deletions(-) create mode 100644 mcp-server/AccUnit.McpServer/AccessInstanceOwnership.cs create mode 100644 mcp-server/Tests/AccUnit.McpServer.Tests/AccessInstanceOwnershipTests.cs diff --git a/mcp-server/AccUnit.McpServer/AccessInstanceOwnership.cs b/mcp-server/AccUnit.McpServer/AccessInstanceOwnership.cs new file mode 100644 index 0000000..52f4d61 --- /dev/null +++ b/mcp-server/AccUnit.McpServer/AccessInstanceOwnership.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; + +namespace AccessCodeLib.AccUnit.McpServer +{ + /// + /// Decides whether the Access instance returned by COM was started by this server. + /// While another automation (e.g. another MCP server) uses Access, COM may hand out that running instance + /// instead of starting a new one; the server must neither use nor quit it. + /// + public static class AccessInstanceOwnership + { + public const string ExistingInstanceMessage = + "Access returned an instance that was already running (probably used by another automation), " + + "so the database was not opened. Try again when the other Access automation has finished."; + + /// Process of the instance returned by COM. + /// Access processes that were running before the instance was requested. + public static bool IsStartedByServer(int processId, ICollection processIdsBeforeStart) + { + return !processIdsBeforeStart.Contains(processId); + } + } +} diff --git a/mcp-server/AccUnit.McpServer/AccessSession.cs b/mcp-server/AccUnit.McpServer/AccessSession.cs index c81657f..8535a8c 100644 --- a/mcp-server/AccUnit.McpServer/AccessSession.cs +++ b/mcp-server/AccUnit.McpServer/AccessSession.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Access = Microsoft.Office.Interop.Access; @@ -17,6 +18,10 @@ public sealed class AccessSession : IDisposable private const bool OpenExclusive = true; private const string AllowBypassKeyPropertyName = "AllowBypassKey"; private const int DaoPropertyNotFoundHResult = unchecked((int)0x800A0CC6); // DAO error 3270 + private const string AccessProcessName = "MSACCESS"; + private const string DatabaseNotOpenedMessage = + "Access did not open the database, although it reported no error. This can happen while another Access automation " + + "is running; the Access instance of this server was closed. Try again."; private readonly StaComDispatcher _dispatcher; private Access.Application _application; @@ -90,6 +95,14 @@ private SessionStatus OpenOnStaThread(string fullPath, bool bypassStartup) QuitAccess(); throw new DatabaseSessionException("Access could not open the database: " + ex.Message, ex); } + + // Seen while another Access automation was running: OpenCurrentDatabase returned without error, + // but no database was open (CurrentProject "closed or doesn't exist"). + if (!HasOpenDatabase()) + { + QuitAccess(); + throw new DatabaseSessionException(DatabaseNotOpenedMessage); + } _databasePath = fullPath; _bypassStartup = bypassStartup; @@ -99,6 +112,24 @@ private SessionStatus OpenOnStaThread(string fullPath, bool bypassStartup) return status; } + private bool HasOpenDatabase() + { + Access._CurrentProject currentProject = null; + try + { + currentProject = _application.CurrentProject; + return !string.IsNullOrEmpty(currentProject.FullName); + } + catch (COMException) + { + return false; + } + finally + { + ReleaseComObject(currentProject); + } + } + private void OpenCurrentDatabase(string fullPath, bool pressShiftKey) { using (pressShiftKey ? new ShiftKeyScope() : null) @@ -152,10 +183,35 @@ private static void ReleaseComObject(object comObject) private void StartAccess() { - _application = new Access.Application(); + var processIdsBeforeStart = GetAccessProcessIds(); + var application = new Access.Application(); + var process = GetProcess(application); + + if (!AccessInstanceOwnership.IsStartedByServer(process.Id, processIdsBeforeStart)) + { + // COM handed out a running instance (e.g. of another automation): release it, never quit or kill it. + process.Dispose(); + Marshal.FinalReleaseComObject(application); + throw new DatabaseSessionException(AccessInstanceOwnership.ExistingInstanceMessage); + } + + _application = application; + _accessProcess = process; // Visible, so the user can see what happens and dialogs do not block unnoticed. _application.Visible = true; - _accessProcess = GetProcess(_application); + } + + private static HashSet GetAccessProcessIds() + { + var processIds = new HashSet(); + foreach (var process in Process.GetProcessesByName(AccessProcessName)) + { + using (process) + { + processIds.Add(process.Id); + } + } + return processIds; } private CloseResult CloseOnStaThread() diff --git a/mcp-server/README.md b/mcp-server/README.md index 9edebbe..6af079f 100644 --- a/mcp-server/README.md +++ b/mcp-server/README.md @@ -71,7 +71,9 @@ The finished test class is added through the source files (e.g. msaccess-vcs imp ## Behavior and changes to the database - **One database at a time**, opened exclusively in an Access instance started by the server; the server never uses - an Access instance it did not start. The instance is visible. + an Access instance it did not start. The instance is visible. If COM hands out an Access instance that was already + running (e.g. while another Access automation runs), `accunit_open` fails and leaves that instance untouched. + If Access reports no error but has no database open afterwards, the server quits its own instance and reports it. - **Startup code** (AutoExec, startup form) is skipped by default like opening with the Shift key held down. This does not work if the database sets `AllowBypassKey = False`; the result then contains a warning. - **`accunit_run_tests`** inserts the module `AccUnit_Factory` if it is missing (test classes use `Assert`/`Iz` from it) diff --git a/mcp-server/Tests/AccUnit.McpServer.Tests/AccessInstanceOwnershipTests.cs b/mcp-server/Tests/AccUnit.McpServer.Tests/AccessInstanceOwnershipTests.cs new file mode 100644 index 0000000..8c03847 --- /dev/null +++ b/mcp-server/Tests/AccUnit.McpServer.Tests/AccessInstanceOwnershipTests.cs @@ -0,0 +1,25 @@ +using NUnit.Framework; + +namespace AccessCodeLib.AccUnit.McpServer.Tests +{ + public class AccessInstanceOwnershipTests + { + [Test] + public void IsStartedByServer_NewProcess_IsTrue() + { + Assert.That(AccessInstanceOwnership.IsStartedByServer(300, new[] { 100, 200 }), Is.True); + } + + [Test] + public void IsStartedByServer_NoAccessRunningBefore_IsTrue() + { + Assert.That(AccessInstanceOwnership.IsStartedByServer(300, new int[0]), Is.True); + } + + [Test] + public void IsStartedByServer_ProcessRunningBefore_IsFalse() + { + Assert.That(AccessInstanceOwnership.IsStartedByServer(200, new[] { 100, 200 }), Is.False); + } + } +}