package p.studio.app.mcp; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import p.studio.core.project.ProjectAccessRegistry; import p.studio.core.session.DefaultAutomationSession; import p.studio.app.operation.ExecutorOperationExecutor; import p.studio.api.automation.*; import java.nio.file.Path; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.*; class McpConnectionGuideTest { @TempDir Path root; @Test void preparationIsStableAndSeparateFromAuthority() throws Exception { var mapper = new ObjectMapper(); var projects = new ProjectAccessRegistry(); try (var workers = Executors.newSingleThreadExecutor(); var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of()))) { var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(workers)); var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority); var prepared = new AtomicInteger(); var canonical = root.toRealPath(); var guide = new McpConnectionGuide(server, projects, mapper, project -> { assertEquals(canonical, project); prepared.incrementAndGet(); return new AgentIntegrationPreparation.Result(true, "Prepared; trust/reload once."); }); assertEquals(AgentConnectionGuide.State.UNAVAILABLE, guide.state(root)); var stable = guide.configuration(root); assertTrue(guide.prepare(root).ready()); assertEquals(1, prepared.get()); assertEquals(ControlState.MANUAL, authority.snapshot().state()); assertNull(authority.snapshot().task()); server.start(); assertEquals(AgentConnectionGuide.State.WAITING_FOR_ACCESS, guide.state(root)); assertFalse(stable.contains("Bearer")); for (var instruction : List.of("studio_project_context", "studio_reference_read", "studio_control_acquire", "studio_control_release", "studio_language_query", "studio_build_start", "clientRequestId", "read-only", "restart", "native file writes")) assertTrue(stable.contains(instruction)); server.close(); server.start(); assertEquals(stable, guide.configuration(root)); assertThrows(AutomationException.class, () -> guide.configuration(root.resolve("unopened"))); authority.closeAsync().toCompletableFuture().join(); assertThrows(AutomationException.class, () -> guide.configuration(root)); registration.close(); } } }