feat(studio): integrate project MCP setup and lifecycle
This commit is contained in:
@@ -4,6 +4,7 @@ plugins {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.tomlj)
|
||||
implementation(project(":prometeu-infra"))
|
||||
implementation(project(":prometeu-lsp:prometeu-lsp-api"))
|
||||
implementation(project(":prometeu-lsp:prometeu-lsp-v1"))
|
||||
@@ -26,6 +27,36 @@ application {
|
||||
mainClass = "p.studio.app.StudioLauncher"
|
||||
}
|
||||
|
||||
val studioJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(21) }
|
||||
val studioRuntime = layout.buildDirectory.dir("studio-runtime")
|
||||
val assembleStudioRuntime by tasks.registering(Exec::class) {
|
||||
val jdk = studioJava.get().metadata.installationPath.asFile
|
||||
inputs.property("jdk", jdk.absolutePath)
|
||||
outputs.dir(studioRuntime)
|
||||
doFirst { delete(studioRuntime) }
|
||||
// jlink license files can be read-only; Gradle Sync must be able to refresh the installed image.
|
||||
doLast {
|
||||
studioRuntime.get().asFile.walkTopDown().filter { it.isFile }.forEach {
|
||||
check(it.setWritable(true, true)) { "Cannot normalize staged runtime permissions" }
|
||||
}
|
||||
}
|
||||
commandLine(jdk.resolve("bin/jlink"), "--add-modules", "ALL-MODULE-PATH", "--strip-debug", "--no-header-files",
|
||||
"--no-man-pages", "--output", studioRuntime.get().asFile)
|
||||
}
|
||||
distributions {
|
||||
main { contents { from(assembleStudioRuntime) { into("runtime") } } }
|
||||
}
|
||||
tasks.register<JavaExec>("stageStudioInstallation") {
|
||||
group = "application"
|
||||
description = "Stages and validates the bundled Studio/Java installation; no project launcher is created."
|
||||
dependsOn(tasks.named("installDist"))
|
||||
classpath = sourceSets["main"].runtimeClasspath
|
||||
mainClass = "p.studio.app.install.ManagedStudioInstallation"
|
||||
args(layout.buildDirectory.dir("install/prometeu-app").get().asFile.absolutePath,
|
||||
providers.gradleProperty("studioInstallationRoot").getOrElse(
|
||||
"${System.getProperty("user.home")}/Library/Application Support/Prometeu/Studio"))
|
||||
}
|
||||
|
||||
javafx {
|
||||
version = libs.versions.javafx.get()
|
||||
modules("javafx.controls", "javafx.fxml")
|
||||
@@ -77,3 +108,20 @@ tasks.register<Test>("headlessMcpDesktopTest") {
|
||||
systemProperty("java.awt.headless", "false")
|
||||
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
|
||||
}
|
||||
|
||||
// Subprocess tests exercise the actual Studio main and OS ownership boundaries.
|
||||
tasks.withType<Test>().configureEach {
|
||||
systemProperty("studio.test.classpath", sourceSets["test"].runtimeClasspath.asPath)
|
||||
}
|
||||
|
||||
tasks.named<Test>("test") { exclude("**/InstalledConnectorTest.class") }
|
||||
tasks.register<Test>("installedConnectorTest") {
|
||||
group = "verification"
|
||||
description = "Validates installed Java, stable updates, project preparation and JavaFX startup (requires a display)."
|
||||
dependsOn(tasks.named("installDist"))
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/InstalledConnectorTest.class")
|
||||
systemProperty("studio.test.distribution", layout.buildDirectory.dir("install/prometeu-app").get().asFile.absolutePath)
|
||||
}
|
||||
|
||||
@@ -230,13 +230,16 @@ public class StudioApplicationConfiguration {
|
||||
@Bean(destroyMethod = "close")
|
||||
DefaultProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore,
|
||||
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp,
|
||||
p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations) {
|
||||
return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations);
|
||||
p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations,
|
||||
p.studio.api.automation.AutomationConnectionLifecycle connections,
|
||||
p.studio.api.automation.AgentIntegrationPreparation preparation) {
|
||||
return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations, connections, preparation);
|
||||
}
|
||||
|
||||
@Bean
|
||||
ProjectCatalog projectCatalog(ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore) {
|
||||
return new ProjectCatalogService(resolveDefaultProjectsRoot(), mapper, setupStore);
|
||||
ProjectCatalog projectCatalog(ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore,
|
||||
p.studio.api.automation.AgentIntegrationPreparation preparation) {
|
||||
return new ProjectCatalogService(resolveDefaultProjectsRoot(), mapper, setupStore, preparation);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -340,10 +343,19 @@ public class StudioApplicationConfiguration {
|
||||
return new p.studio.app.mcp.LocalMcpServer(mapper, tools);
|
||||
}
|
||||
|
||||
@Bean
|
||||
p.studio.api.automation.AutomationConnectionLifecycle connectionLifecycle(p.studio.app.mcp.LocalMcpServer server, ObjectMapper mapper) {
|
||||
return new p.studio.app.mcp.ProjectConnectionPublisher(server, mapper);
|
||||
}
|
||||
@Bean
|
||||
p.studio.api.automation.AgentIntegrationPreparation agentPreparation(ObjectMapper mapper) {
|
||||
return new p.studio.app.mcp.StudioAgentPreparation(p.studio.app.install.ManagedStudioInstallation.defaultRoot(), mapper);
|
||||
}
|
||||
@Bean
|
||||
p.studio.api.automation.AgentConnectionGuide connectionGuide(p.studio.app.mcp.LocalMcpServer server,
|
||||
p.studio.core.project.ProjectAccessRegistry projects, ObjectMapper mapper) {
|
||||
return new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper);
|
||||
p.studio.core.project.ProjectAccessRegistry projects, ObjectMapper mapper,
|
||||
p.studio.api.automation.AgentIntegrationPreparation preparation) {
|
||||
return new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper, preparation);
|
||||
}
|
||||
|
||||
private static Path resolveDefaultProjectsRoot() {
|
||||
|
||||
@@ -7,6 +7,11 @@ public final class StudioLauncher {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length > 0 && "mcp".equals(args[0])) {
|
||||
try { p.studio.app.mcp.stdio.StudioMcpStdio.main(args); }
|
||||
catch (Exception failure) { System.err.println("Studio MCP could not start. Check --project, the manifest and installation."); System.exit(1); }
|
||||
return;
|
||||
}
|
||||
Application.launch(App.class, args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package p.studio.app.install;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** One versioned application installation; client entries always refer to current. */
|
||||
public final class ManagedStudioInstallation {
|
||||
public static final class MissingInstallation extends IOException {
|
||||
public MissingInstallation() {
|
||||
super("Studio installation is missing. In the Studio checkout, run ./gradlew :prometeu-app:stageStudioInstallation, then prepare the assistant again. If using an isolated installation, set -Dstudio.installationRoot to that installation in the desktop VM options.");
|
||||
}
|
||||
}
|
||||
private ManagedStudioInstallation() { }
|
||||
public static Path defaultRoot() {
|
||||
return Path.of(System.getProperty("studio.installationRoot", Path.of(System.getProperty("user.home"),
|
||||
"Library", "Application Support", "Prometeu", "Studio").toString())).toAbsolutePath();
|
||||
}
|
||||
public static void ensureAvailable(Path base) throws Exception {
|
||||
if (Files.isExecutable(base.resolve("current/runtime/bin/java")) && Files.isDirectory(base.resolve("current/lib"))) return;
|
||||
Path location = Path.of(ManagedStudioInstallation.class.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
if (!Files.isRegularFile(location) || !Files.isDirectory(location.getParent().getParent().resolve("runtime")))
|
||||
throw new MissingInstallation();
|
||||
install(location.getParent().getParent(), base);
|
||||
}
|
||||
public static synchronized Path install(Path source, Path base) throws Exception {
|
||||
source = source.toRealPath(); Files.createDirectories(base.resolve("versions"));
|
||||
Path version = base.resolve("versions").resolve(UUID.randomUUID().toString());
|
||||
Files.createDirectory(version);
|
||||
for (String part : List.of("lib", "runtime")) {
|
||||
if (!Files.isDirectory(source.resolve(part))) throw new IOException("Incomplete Studio distribution");
|
||||
try (var paths = Files.walk(source.resolve(part))) {
|
||||
for (Path from : paths.toList()) {
|
||||
Path to = version.resolve(source.relativize(from));
|
||||
if (Files.isDirectory(from)) Files.createDirectories(to);
|
||||
else Files.copy(from, to, StandardCopyOption.COPY_ATTRIBUTES);
|
||||
}
|
||||
}
|
||||
}
|
||||
var process = new ProcessBuilder(version.resolve("runtime/bin/java").toString(), "-cp", version.resolve("lib/*").toString(),
|
||||
"p.studio.app.install.StudioInstallationProbe").redirectError(ProcessBuilder.Redirect.DISCARD).redirectOutput(ProcessBuilder.Redirect.DISCARD).start();
|
||||
if (!process.waitFor(30, TimeUnit.SECONDS)) { process.destroyForcibly(); throw new IOException("Installation validation timed out"); }
|
||||
if (process.exitValue() != 0) throw new IOException("Installation validation failed");
|
||||
Path link = base.resolve(".current-" + UUID.randomUUID());
|
||||
try { Files.createSymbolicLink(link, base.toAbsolutePath().relativize(version.toAbsolutePath()));
|
||||
Files.move(link, base.resolve("current"), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally { Files.deleteIfExists(link); }
|
||||
return version;
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length != 2) throw new IllegalArgumentException("distribution and installation root required");
|
||||
install(Path.of(args[0]), Path.of(args[1]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package p.studio.app.install;
|
||||
|
||||
/** Packaging health check; it never starts the GUI or opens projects. */
|
||||
public final class StudioInstallationProbe {
|
||||
public static void main(String[] args) throws Exception {
|
||||
var catalog = new p.studio.app.mcp.McpToolCatalog(new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
if (catalog.names().isEmpty()) throw new IllegalStateException("Missing catalog");
|
||||
for (String type : java.util.List.of("javafx.application.Application", "javafx.fxml.FXMLLoader",
|
||||
"p.studio.app.App", "java.net.http.HttpClient", "com.sun.net.httpserver.HttpServer", "org.tomlj.Toml"))
|
||||
Class.forName(type, false, StudioInstallationProbe.class.getClassLoader());
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,22 @@ public final class LocalMcpServer implements AutoCloseable {
|
||||
private static final int MAX_CONNECTION_SESSIONS = 128;
|
||||
private final ObjectMapper mapper;
|
||||
private final McpToolRegistry tools;
|
||||
private final Map<String, AtomicBoolean> sessions = new ConcurrentHashMap<>();
|
||||
private record Session(ProjectCredentials.Credential credential, AtomicBoolean initialized, java.util.concurrent.atomic.AtomicLong lastSeen) { }
|
||||
private final Map<String, Session> sessions = new ConcurrentHashMap<>();
|
||||
private final ProjectCredentials credentials = new ProjectCredentials();
|
||||
private volatile String instanceId;
|
||||
public ProjectCredentials credentials() { return credentials; }
|
||||
public String instanceId() { return instanceId; }
|
||||
public synchronized void activateCredential(String instance, ProjectCredentials.Credential credential) {
|
||||
if (server == null || !Objects.equals(instanceId, instance)) throw new IllegalStateException("Studio instance changed");
|
||||
credential.activate();
|
||||
}
|
||||
public String catalogFingerprint() { return tools.catalogFingerprint(); }
|
||||
public boolean connected(java.nio.file.Path root) {
|
||||
long now = System.nanoTime();
|
||||
return sessions.values().stream().anyMatch(s -> s.initialized.get() && s.credential.active() && s.credential.root().equals(root)
|
||||
&& now - s.lastSeen.get() < TimeUnit.SECONDS.toNanos(10));
|
||||
}
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private HttpServer server;
|
||||
private ExecutorService executor;
|
||||
@@ -42,7 +57,8 @@ public final class LocalMcpServer implements AutoCloseable {
|
||||
this.tools = Objects.requireNonNull(tools);
|
||||
}
|
||||
|
||||
public synchronized void start() throws IOException {
|
||||
public void start() throws IOException {
|
||||
synchronized (this) {
|
||||
if (server != null) return;
|
||||
// No configurable bind address: remote and wildcard exposure cannot be enabled accidentally.
|
||||
var next = HttpServer.create(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), 32);
|
||||
@@ -50,17 +66,20 @@ public final class LocalMcpServer implements AutoCloseable {
|
||||
Thread.ofPlatform().daemon().name("studio-mcp-", 1).factory(), new ThreadPoolExecutor.AbortPolicy());
|
||||
var timers = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().name("studio-mcp-deadlines").factory());
|
||||
try {
|
||||
connection = new Connection(URI.create("http://127.0.0.1:" + next.getAddress().getPort() + "/mcp"), secret());
|
||||
instanceId = UUID.randomUUID().toString();
|
||||
connection = new Connection(URI.create("http://127.0.0.1:" + next.getAddress().getPort() + "/mcp"));
|
||||
deadlines = timers;
|
||||
next.createContext("/mcp", this::handle);
|
||||
next.setExecutor(workers);
|
||||
next.start();
|
||||
timers.scheduleWithFixedDelay(() -> connectionListeners.forEach(LocalMcpServer::notifyConnectionListener), 2, 2, TimeUnit.SECONDS);
|
||||
executor = workers; server = next;
|
||||
connectionListeners.forEach(LocalMcpServer::notifyConnectionListener);
|
||||
} catch (RuntimeException failure) {
|
||||
next.stop(0); workers.shutdownNow(); timers.shutdownNow(); connection = null;
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
connectionListeners.forEach(LocalMcpServer::notifyConnectionListener);
|
||||
}
|
||||
public Connection connection() {
|
||||
var current = connection;
|
||||
@@ -68,20 +87,20 @@ public final class LocalMcpServer implements AutoCloseable {
|
||||
return current;
|
||||
}
|
||||
public synchronized boolean isRunning() { return server != null; }
|
||||
@Override public synchronized void close() {
|
||||
@Override public void close() {
|
||||
synchronized (this) {
|
||||
if (server == null) return;
|
||||
connection = null; server.stop(0); server = null;
|
||||
sessions.clear(); executor.shutdownNow(); deadlines.shutdownNow();
|
||||
sessions.clear(); credentials.clear(); executor.shutdownNow(); deadlines.shutdownNow();
|
||||
}
|
||||
connectionListeners.forEach(LocalMcpServer::notifyConnectionListener);
|
||||
}
|
||||
|
||||
/** Only explicit connection/configuration consumers may obtain the bearer token; never log it. */
|
||||
/** Public endpoint metadata contains no credential. */
|
||||
public static final class Connection {
|
||||
private final URI endpoint;
|
||||
private final String token;
|
||||
private Connection(URI endpoint, String token) { this.endpoint = endpoint; this.token = token; }
|
||||
private Connection(URI endpoint) { this.endpoint = endpoint; }
|
||||
public URI endpoint() { return endpoint; }
|
||||
public String authorizationHeader() { return "Bearer " + token; }
|
||||
@Override public String toString() { return "LocalMcpConnection[endpoint=" + endpoint + ", credentials=REDACTED]"; }
|
||||
}
|
||||
|
||||
@@ -101,13 +120,17 @@ public final class LocalMcpServer implements AutoCloseable {
|
||||
|| !authority.equals(single(headers, "Host"))
|
||||
|| origin != null && !("http://" + authority).equals(origin)) { empty(exchange, 403); return; }
|
||||
String authorization = single(headers, "Authorization");
|
||||
if (authorization == null || !MessageDigest.isEqual(current.authorizationHeader().getBytes(StandardCharsets.UTF_8), authorization.getBytes(StandardCharsets.UTF_8))) {
|
||||
var credential = credentials.authenticate(authorization);
|
||||
if (credential == null) {
|
||||
empty(exchange, 401); return;
|
||||
}
|
||||
String version = single(headers, "MCP-Protocol-Version");
|
||||
if (version != null && !PROTOCOL_VERSION.equals(version)) { empty(exchange, 400); return; }
|
||||
String sessionId = single(headers, "Mcp-Session-Id");
|
||||
AtomicBoolean initialized = sessionId == null ? null : sessions.get(sessionId);
|
||||
var session = sessionId == null ? null : sessions.get(sessionId);
|
||||
if (session != null && session.credential != credential) { empty(exchange, 403); return; }
|
||||
AtomicBoolean initialized = session == null ? null : session.initialized;
|
||||
if (session != null) session.lastSeen.set(System.nanoTime());
|
||||
if (sessionId != null && initialized == null) { empty(exchange, 404); return; }
|
||||
String method = exchange.getRequestMethod();
|
||||
if (method.equals("GET")) { exchange.getResponseHeaders().set("Allow", "POST, DELETE"); empty(exchange, 405); return; }
|
||||
@@ -148,14 +171,16 @@ public final class LocalMcpServer implements AutoCloseable {
|
||||
send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32602, "Invalid initialization")); return;
|
||||
}
|
||||
synchronized (sessions) {
|
||||
sessions.values().removeIf(s -> !s.credential.active());
|
||||
if (sessions.size() >= MAX_CONNECTION_SESSIONS) { empty(exchange, 503); return; }
|
||||
sessionId = secret(); sessions.put(sessionId, new AtomicBoolean());
|
||||
sessionId = secret(); sessions.put(sessionId, new Session(credential, new AtomicBoolean(), new java.util.concurrent.atomic.AtomicLong(System.nanoTime())));
|
||||
}
|
||||
exchange.getResponseHeaders().set("Mcp-Session-Id", sessionId);
|
||||
var result = mapper.createObjectNode().put("protocolVersion", PROTOCOL_VERSION);
|
||||
result.putObject("capabilities").putObject("tools").put("listChanged", false);
|
||||
result.putObject("serverInfo").put("name", "prometeu-studio-mcp").put("version", "1.0");
|
||||
result.put("instructions", McpConnectionGuide.INSTRUCTIONS);
|
||||
result.putObject("_meta").put("instanceId", instanceId).put("projectRoot", credential.root().toString()).put("catalogFingerprint", tools.catalogFingerprint());
|
||||
send(exchange, 200, response(id, result)); return;
|
||||
}
|
||||
if (initialized == null) { empty(exchange, 400); return; }
|
||||
@@ -174,7 +199,18 @@ public final class LocalMcpServer implements AutoCloseable {
|
||||
}
|
||||
case "tools/call" -> {
|
||||
if (!params.path("name").isTextual()) throw new IllegalArgumentException("Missing tool name");
|
||||
yield tools.call(params.get("name").asText(), params.get("arguments")).wire();
|
||||
var arguments = params.get("arguments");
|
||||
if (arguments == null || !arguments.path("projectRoot").isTextual()) throw new IllegalArgumentException("Missing root");
|
||||
java.nio.file.Path requested;
|
||||
try { requested = java.nio.file.Path.of(arguments.path("projectRoot").asText());
|
||||
if (!requested.isAbsolute()) throw new IllegalArgumentException("Relative root");
|
||||
requested = requested.toRealPath();
|
||||
} catch (java.io.IOException | RuntimeException invalid) { throw new IllegalArgumentException("Invalid root"); }
|
||||
if (!credential.active() || !credential.root().equals(requested)) {
|
||||
yield McpToolResult.failure(mapper, new p.studio.api.automation.AutomationFailure(
|
||||
p.studio.api.automation.AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "Connection is bound to another project or no longer authorized")).wire();
|
||||
}
|
||||
yield tools.call(params.get("name").asText(), arguments).wire();
|
||||
}
|
||||
default -> null;
|
||||
};
|
||||
|
||||
@@ -7,12 +7,11 @@ import p.studio.core.project.ProjectAccessRegistry;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Builds a provider-neutral connection descriptor from the live server, only on explicit export. */
|
||||
/** Projects connection liveness and permanent setup independently of task authority. */
|
||||
public final class McpConnectionGuide implements AgentConnectionGuide {
|
||||
public static final String INSTRUCTIONS = """
|
||||
Configure your external coding client's MCP connection using the url and Authorization header below.
|
||||
This is a provider-neutral descriptor, not a provider-specific configuration file.
|
||||
Keep the token private; do not commit this descriptor, write it into project files or include it in logs.
|
||||
Use the Studio tools for this project. Wait for the developer to grant access in DEV, then acquire control.
|
||||
The installed Studio connector discovers the connection automatically; do not write transport scripts or copy tokens.
|
||||
Connect and list available tools. Read studio_project_context for the explicit projectRoot and consult
|
||||
studio_reference_read for the declared languages, SDK and libraries before editing as needed.
|
||||
Do not assume PBS or another language when support/documentation is missing; report the limitation.
|
||||
@@ -26,25 +25,42 @@ public final class McpConnectionGuide implements AgentConnectionGuide {
|
||||
Observe headless images/state when those tools are available, and explicitly studio_control_release
|
||||
when finished. On revocation stop external edits too: Studio cannot stop your native file writes.
|
||||
Existing edits are preserved. Git/review/recovery remain the developer's responsibility.
|
||||
Recopy and update your client's connection after Studio restart: endpoint and token are ephemeral.
|
||||
After Studio restart, wait for a fresh human grant. The connector reconnects automatically; old task identities are invalid.
|
||||
""";
|
||||
private final LocalMcpServer server;
|
||||
private final ProjectAccessRegistry projects;
|
||||
private final ObjectMapper mapper;
|
||||
private final p.studio.api.automation.AgentIntegrationPreparation preparation;
|
||||
public McpConnectionGuide(LocalMcpServer server, ProjectAccessRegistry projects, ObjectMapper mapper) {
|
||||
this.server = server; this.projects = projects; this.mapper = mapper;
|
||||
this(server, projects, mapper, new StudioAgentPreparation(p.studio.app.install.ManagedStudioInstallation.defaultRoot(), mapper));
|
||||
}
|
||||
public McpConnectionGuide(LocalMcpServer server, ProjectAccessRegistry projects, ObjectMapper mapper,
|
||||
p.studio.api.automation.AgentIntegrationPreparation preparation) {
|
||||
this.server = server; this.projects = projects; this.mapper = mapper; this.preparation = preparation;
|
||||
}
|
||||
@Override public boolean supportsPreparation() { return true; }
|
||||
@Override public Optional<String> endpoint() {
|
||||
try { return Optional.of(server.connection().endpoint().toString()); }
|
||||
catch (IllegalStateException unavailable) { return Optional.empty(); }
|
||||
}
|
||||
@Override public String configuration(Path root) {
|
||||
Path canonical = projects.requireOpenRoot(root);
|
||||
var live = server.connection();
|
||||
var value = mapper.createObjectNode().put("transport", "streamable-http").put("url", live.endpoint().toString());
|
||||
value.putObject("headers").put("Authorization", live.authorizationHeader());
|
||||
value.put("projectRoot", canonical.toString()).put("instructions", INSTRUCTIONS);
|
||||
return value.toPrettyString();
|
||||
return "Run the installed Studio in mcp --project mode for " + canonical + "\n" + INSTRUCTIONS;
|
||||
}
|
||||
@Override public p.studio.api.automation.AgentIntegrationPreparation.Result prepare(Path root) {
|
||||
return preparation.prepare(projects.requireOpenRoot(root));
|
||||
}
|
||||
@Override public p.studio.api.automation.AgentIntegrationPreparation.Result preparationStatus(Path root) {
|
||||
return preparation.status(projects.requireOpenRoot(root));
|
||||
}
|
||||
@Override public State state(Path root) {
|
||||
try {
|
||||
Path canonical = projects.requireOpenRoot(root);
|
||||
if (!server.isRunning()) return State.UNAVAILABLE;
|
||||
if (server.connected(canonical)) return State.CONNECTED;
|
||||
var control = projects.requireAutomation(canonical).snapshot().state();
|
||||
return control == p.studio.api.automation.ControlState.AGENT_WORKING ? State.RECONNECTING : State.WAITING_FOR_ACCESS;
|
||||
} catch (RuntimeException unavailable) { return State.UNAVAILABLE; }
|
||||
}
|
||||
@Override public OperationSubscription subscribe(Runnable changed) { return server.onConnectionChanged(changed); }
|
||||
}
|
||||
|
||||
@@ -21,6 +21,14 @@ public final class McpToolCatalog {
|
||||
} catch (IOException failure) { throw new IllegalStateException("Cannot read packaged MCP contract", failure); }
|
||||
}
|
||||
public Set<String> names() { return definitions.keySet(); }
|
||||
public String fingerprint() {
|
||||
try {
|
||||
var digest = java.security.MessageDigest.getInstance("SHA-256");
|
||||
digest.update(LocalMcpServer.PROTOCOL_VERSION.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
definitions.keySet().stream().sorted().forEach(name -> digest.update(descriptor(name).toString().getBytes(java.nio.charset.StandardCharsets.UTF_8)));
|
||||
return java.util.HexFormat.of().formatHex(digest.digest());
|
||||
} catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
|
||||
}
|
||||
public JsonNode definition(String name) {
|
||||
var definition = definitions.get(name);
|
||||
if (definition == null) throw new IllegalArgumentException("Unknown tool");
|
||||
|
||||
@@ -22,6 +22,7 @@ public final class McpToolRegistry {
|
||||
catalog.names().stream().filter(handlers::containsKey).forEach(name -> descriptors.add(catalog.descriptor(name)));
|
||||
return descriptors;
|
||||
}
|
||||
public String catalogFingerprint() { return catalog.fingerprint(); }
|
||||
public McpToolResult call(String name, JsonNode arguments) {
|
||||
var handler = handlers.get(name);
|
||||
if (handler == null) throw new IllegalArgumentException("Unknown or unavailable tool");
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
|
||||
|
||||
/** Local discovery data is untrusted until paths, permissions and live identity are verified. */
|
||||
public final class ProjectConnectionFiles {
|
||||
public static final String RELATIVE = ".studio/mcp/connection.json";
|
||||
private static final Set<java.nio.file.attribute.PosixFilePermission> FILE_MODE = PosixFilePermissions.fromString("rw-------");
|
||||
private ProjectConnectionFiles() { }
|
||||
public static Path directory(Path root) throws IOException {
|
||||
Path studio = root.resolve(".studio"), directory = studio.resolve("mcp");
|
||||
safeDirectory(studio, false); safeDirectory(directory, true); return directory;
|
||||
}
|
||||
private static void safeDirectory(Path path, boolean privateDirectory) throws IOException {
|
||||
if (!Files.exists(path, NOFOLLOW_LINKS)) Files.createDirectory(path, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")));
|
||||
if (Files.isSymbolicLink(path) || !Files.isDirectory(path, NOFOLLOW_LINKS)) throw new IOException("Unsafe connection directory");
|
||||
if (privateDirectory) requirePrivate(path, true);
|
||||
}
|
||||
public static void requirePrivate(Path path, boolean directory) throws IOException {
|
||||
if (Files.isSymbolicLink(path) || !(directory ? Files.isDirectory(path, NOFOLLOW_LINKS) : Files.isRegularFile(path, NOFOLLOW_LINKS)))
|
||||
throw new IOException("Unsafe connection file");
|
||||
var expected = directory ? PosixFilePermissions.fromString("rwx------") : FILE_MODE;
|
||||
if (!Files.getPosixFilePermissions(path, NOFOLLOW_LINKS).equals(expected)
|
||||
|| !Files.getOwner(path, NOFOLLOW_LINKS).equals(Files.getOwner(Path.of(System.getProperty("user.home")))))
|
||||
throw new IOException("Connection permissions must be restricted to the current user");
|
||||
}
|
||||
public static void atomicPrivateWrite(Path target, byte[] bytes) throws IOException {
|
||||
if (Files.exists(target, NOFOLLOW_LINKS)) requirePrivate(target, false);
|
||||
var temp = Files.createTempFile(target.getParent(), ".connection-", ".tmp", PosixFilePermissions.asFileAttribute(FILE_MODE));
|
||||
try { Files.write(temp, bytes); Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
finally { Files.deleteIfExists(temp); }
|
||||
}
|
||||
public static boolean tracked(Path root, String relative) throws IOException {
|
||||
try {
|
||||
var process = new ProcessBuilder("git", "-C", root.toString(), "ls-files", "-z", "--", relative).redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
if (!process.waitFor(5, TimeUnit.SECONDS)) { process.destroyForcibly(); throw new IOException("Git check timed out"); }
|
||||
if (process.exitValue() != 0 && process.exitValue() != 128) throw new IOException("Cannot verify file tracking");
|
||||
return process.getInputStream().read() != -1;
|
||||
} catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException("Git check interrupted"); }
|
||||
}
|
||||
public static void ignore(Path root, String relative) throws IOException {
|
||||
Path path = root.resolve(".gitignore");
|
||||
if (Files.isSymbolicLink(path)) throw new IOException("Unsafe ignore file");
|
||||
String old = Files.exists(path) ? Files.readString(path) : "";
|
||||
String rule = "/" + relative;
|
||||
if (old.lines().anyMatch(rule::equals)) return;
|
||||
Files.writeString(path, old + (old.isEmpty() || old.endsWith("\n") ? "" : "\n") + rule + "\n");
|
||||
}
|
||||
public static Descriptor read(Path root, ObjectMapper mapper) throws IOException {
|
||||
Path path = root.resolve(RELATIVE);
|
||||
if (Files.isSymbolicLink(root.resolve(".studio"))) throw new IOException("Unsafe discovery path");
|
||||
requirePrivate(path.getParent(), true); requirePrivate(path, false);
|
||||
byte[] bytes;
|
||||
try (var input = Files.newInputStream(path, NOFOLLOW_LINKS)) { bytes = input.readNBytes(16 * 1024 + 1); }
|
||||
if (bytes.length > 16 * 1024) throw new IOException("Connection descriptor too large");
|
||||
var json = mapper.readTree(bytes);
|
||||
if (json == null || !json.path("schemaVersion").isIntegralNumber() || !json.path("schemaVersion").canConvertToInt() || json.path("schemaVersion").asInt(-1) != 1) throw new IOException("Unsupported connection schema");
|
||||
for (String field : Set.of("instanceId", "projectRoot", "endpoint", "credential", "catalogFingerprint"))
|
||||
if (!json.path(field).isTextual() || json.path(field).asText().isBlank()) throw new IOException("Invalid connection descriptor");
|
||||
try {
|
||||
if (!Path.of(json.path("projectRoot").asText()).equals(root)) throw new IOException("Connection project mismatch");
|
||||
URI endpoint = URI.create(json.path("endpoint").asText());
|
||||
if (!"http".equals(endpoint.getScheme()) || !"127.0.0.1".equals(endpoint.getHost()) || endpoint.getPort() < 1
|
||||
|| endpoint.getPort() > 65535 || !"/mcp".equals(endpoint.getRawPath()) || endpoint.getRawQuery() != null
|
||||
|| endpoint.getRawFragment() != null || endpoint.getUserInfo() != null) throw new IOException("Invalid loopback endpoint");
|
||||
return new Descriptor(endpoint, json.path("instanceId").asText(), json.path("credential").asText(), json.path("catalogFingerprint").asText());
|
||||
} catch (IllegalArgumentException invalid) { throw new IOException("Invalid connection descriptor"); }
|
||||
}
|
||||
public record Descriptor(URI endpoint, String instanceId, String credential, String catalogFingerprint) {
|
||||
@Override public String toString() { return "ProjectConnectionDescriptor[REDACTED]"; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.automation.AutomationConnectionLifecycle;
|
||||
import java.nio.channels.*;
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Set;
|
||||
|
||||
/** The lock inode outlives a publication. Its OS lock, not a stale PID/file, establishes ownership. */
|
||||
public final class ProjectConnectionPublisher implements AutomationConnectionLifecycle {
|
||||
private final LocalMcpServer server;
|
||||
private final ObjectMapper mapper;
|
||||
public ProjectConnectionPublisher(LocalMcpServer server, ObjectMapper mapper) { this.server = server; this.mapper = mapper; }
|
||||
@Override public Publication prepare(Path projectRoot) throws Exception {
|
||||
Path root = projectRoot.toRealPath();
|
||||
final String instance = server.instanceId();
|
||||
final var endpoint = server.connection().endpoint();
|
||||
if (ProjectConnectionFiles.tracked(root, ProjectConnectionFiles.RELATIVE)) throw new IllegalStateException("Connection file is tracked");
|
||||
ProjectConnectionFiles.ignore(root, ".studio/mcp/");
|
||||
Path directory = ProjectConnectionFiles.directory(root), lockPath = directory.resolve("publication.lock");
|
||||
if (Files.exists(lockPath, LinkOption.NOFOLLOW_LINKS)) ProjectConnectionFiles.requirePrivate(lockPath, false);
|
||||
var channel = FileChannel.open(lockPath, Set.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS),
|
||||
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
|
||||
FileLock lock;
|
||||
try { lock = channel.tryLock(); if (lock == null) throw new AutomationConnectionLifecycle.OwnershipConflict(); }
|
||||
catch (OverlappingFileLockException conflict) { channel.close(); throw new AutomationConnectionLifecycle.OwnershipConflict(); }
|
||||
catch (Exception conflict) { channel.close(); throw conflict; }
|
||||
var credential = server.credentials().prepare(root);
|
||||
return new Publication() {
|
||||
private boolean published, closed;
|
||||
public void publish() throws Exception {
|
||||
var value = mapper.createObjectNode().put("schemaVersion", 1).put("instanceId", instance)
|
||||
.put("projectRoot", root.toString()).put("endpoint", endpoint.toString())
|
||||
.put("credential", credential.secret()).put("catalogFingerprint", server.catalogFingerprint());
|
||||
ProjectConnectionFiles.atomicPrivateWrite(directory.resolve("connection.json"), mapper.writeValueAsBytes(value)); published = true;
|
||||
}
|
||||
public void activate() { server.activateCredential(instance, credential); }
|
||||
public void invalidate() { credential.invalidate(); }
|
||||
public synchronized void close() throws Exception {
|
||||
if (closed) return; closed = true; invalidate();
|
||||
try {
|
||||
if (published && Files.exists(directory.resolve("connection.json"), LinkOption.NOFOLLOW_LINKS)) {
|
||||
var current = ProjectConnectionFiles.read(root, mapper);
|
||||
if (instance.equals(current.instanceId()) && credential.secret().equals(current.credential()))
|
||||
Files.delete(directory.resolve("connection.json"));
|
||||
}
|
||||
} finally { try { lock.release(); } finally { channel.close(); } }
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/** Memory-only authentication; never a substitute for the Core grant/task checks. */
|
||||
public final class ProjectCredentials {
|
||||
private final Map<String, Credential> credentials = new ConcurrentHashMap<>();
|
||||
public Credential prepare(Path root) {
|
||||
byte[] bytes = new byte[32]; new SecureRandom().nextBytes(bytes);
|
||||
var credential = new Credential(root, Base64.getUrlEncoder().withoutPadding().encodeToString(bytes));
|
||||
credentials.put(credential.secret, credential); return credential;
|
||||
}
|
||||
public Credential authenticate(String header) {
|
||||
if (header == null || !header.startsWith("Bearer ")) return null;
|
||||
String token = header.substring(7);
|
||||
var found = credentials.get(token);
|
||||
return found != null && found.active && MessageDigest.isEqual(token.getBytes(StandardCharsets.UTF_8),
|
||||
found.secret.getBytes(StandardCharsets.UTF_8)) ? found : null;
|
||||
}
|
||||
public void clear() { credentials.values().forEach(Credential::invalidate); credentials.clear(); }
|
||||
public final class Credential {
|
||||
private final Path root;
|
||||
private final String secret;
|
||||
private volatile boolean active;
|
||||
private boolean invalidated;
|
||||
private Credential(Path root, String secret) { this.root = root; this.secret = secret; }
|
||||
public Path root() { return root; }
|
||||
public String secret() { return secret; }
|
||||
public synchronized void activate() {
|
||||
if (invalidated) throw new IllegalStateException("Credential invalidated");
|
||||
active = true;
|
||||
}
|
||||
public synchronized void invalidate() { active = false; invalidated = true; credentials.remove(secret, this); }
|
||||
public boolean active() { return active; }
|
||||
@Override public String toString() { return "ProjectCredential[REDACTED]"; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.automation.AgentIntegrationPreparation;
|
||||
import p.studio.app.install.ManagedStudioInstallation;
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import org.tomlj.Toml;
|
||||
|
||||
/** Only the managed entry is edited; unrelated client configuration remains byte-for-byte intact. */
|
||||
public final class StudioAgentPreparation implements AgentIntegrationPreparation {
|
||||
private final Path installation;
|
||||
private final ObjectMapper mapper;
|
||||
private final Map<Path, Result> preparationFailures = new java.util.concurrent.ConcurrentHashMap<>();
|
||||
private static final String BEGIN = "# Studio managed MCP entry ";
|
||||
private static final String END = "# End Studio managed MCP entry\n";
|
||||
public StudioAgentPreparation(Path installation, ObjectMapper mapper) { this.installation = installation; this.mapper = mapper; }
|
||||
@Override public synchronized Result prepare(Path projectRoot) {
|
||||
var result = prepareLocal(projectRoot);
|
||||
Path key = preparationKey(projectRoot);
|
||||
if (result.ready()) preparationFailures.remove(key); else preparationFailures.put(key, result);
|
||||
return result;
|
||||
}
|
||||
private Result prepareLocal(Path projectRoot) {
|
||||
try {
|
||||
Path root = projectRoot.toRealPath();
|
||||
if (!Files.isRegularFile(root.resolve("prometeu.json"))) return new Result(false, "Project manifest not found.");
|
||||
if (ProjectConnectionFiles.tracked(root, ".codex/config.toml"))
|
||||
return new Result(false, "Client configuration is tracked. Keep machine-specific registration local before preparing this project.");
|
||||
Path directory = root.resolve(".codex"), config = directory.resolve("config.toml");
|
||||
if (Files.isSymbolicLink(directory) || Files.isSymbolicLink(config)) return new Result(false, "Client configuration path is unsafe.");
|
||||
String old = Files.exists(config) ? Files.readString(config) : "";
|
||||
String next = merge(old, entry(root));
|
||||
ManagedStudioInstallation.ensureAvailable(installation);
|
||||
Files.createDirectories(directory);
|
||||
ProjectConnectionFiles.ignore(root, ".codex/config.toml");
|
||||
ProjectConnectionFiles.ignore(root, ".studio/mcp/");
|
||||
if (!old.equals(next)) {
|
||||
int previous = old.indexOf(BEGIN);
|
||||
if (previous >= 0) {
|
||||
ProjectConnectionFiles.ignore(root, ".codex/.studio-mcp.previous.toml");
|
||||
String owned = old.substring(previous, old.indexOf(END, previous) + END.length());
|
||||
ProjectConnectionFiles.atomicPrivateWrite(directory.resolve(".studio-mcp.previous.toml"), owned.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
Path temporary = Files.createTempFile(directory, ".studio-config-", ".tmp", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
|
||||
try { Files.writeString(temporary, next); Files.move(temporary, config, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
Path studio = root.resolve(".studio");
|
||||
if (Files.isSymbolicLink(studio)) throw new IllegalStateException("Unsafe setup directory");
|
||||
Files.createDirectories(studio);
|
||||
Path setup = studio.resolve("setup.json");
|
||||
if (Files.isSymbolicLink(setup)) throw new IllegalStateException("Unsafe setup file");
|
||||
var value = Files.exists(setup) ? mapper.readTree(Files.readAllBytes(setup)) : mapper.createObjectNode();
|
||||
if (!(value instanceof com.fasterxml.jackson.databind.node.ObjectNode object)) throw new IllegalStateException("Invalid setup");
|
||||
object.putObject("agentIntegration").put("schemaVersion", 1).put("enabled", true).put("clientProfile", "codex");
|
||||
String setupText = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
|
||||
if (!Files.exists(setup) || !Files.readString(setup).equals(setupText)) {
|
||||
Path temporary = Files.createTempFile(studio, ".setup-", ".tmp");
|
||||
try { Files.writeString(temporary, setupText); Files.move(temporary, setup, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
return new Result(true, "Assistant prepared. Trust this project in your client and reload MCP once if requested. Then grant access in DEV; no token copying or restart reconfiguration is needed.");
|
||||
} catch (ManagedStudioInstallation.MissingInstallation missing) { return new Result(false, missing.getMessage()); }
|
||||
catch (Conflict conflict) { return new Result(false, conflict.getMessage()); }
|
||||
catch (Exception failure) { return new Result(false, "Preparation incomplete. Check the Studio installation and project/configuration permissions; existing client settings were not deliberately replaced."); }
|
||||
}
|
||||
@Override public Result status(Path projectRoot) {
|
||||
var failure = preparationFailures.get(preparationKey(projectRoot));
|
||||
if (failure != null) return failure;
|
||||
try {
|
||||
Path root = projectRoot.toRealPath(), config = root.resolve(".codex/config.toml");
|
||||
if (Files.isSymbolicLink(config.getParent()) || Files.isSymbolicLink(config))
|
||||
return new Result(false, "Unsafe client configuration path. Prepare the assistant after resolving it.");
|
||||
if (!Files.isRegularFile(config)) return new Result(false, "Assistant setup is incomplete. Prepare the assistant for this project.");
|
||||
String old = Files.readString(config);
|
||||
if (!old.equals(merge(old, entry(root))) || !Files.isExecutable(installation.resolve("current/runtime/bin/java")))
|
||||
return new Result(false, "Assistant setup is incomplete. Prepare the assistant from an installed Studio.");
|
||||
return new Result(true, "Assistant prepared. Trust this project in your client and reload MCP once if requested.");
|
||||
} catch (Conflict conflict) { return new Result(false, conflict.getMessage()); }
|
||||
catch (Exception unavailable) { return new Result(false, "Assistant setup could not be verified. Prepare the assistant again."); }
|
||||
}
|
||||
private static Path preparationKey(Path root) {
|
||||
try { return root.toRealPath(); }
|
||||
catch (java.io.IOException missing) { return root.toAbsolutePath().normalize(); }
|
||||
}
|
||||
public String entry(Path root) throws Exception {
|
||||
Path current = installation.resolve("current").toAbsolutePath();
|
||||
return "[mcp_servers.prometeu_studio]\ncommand = " + quote(current.resolve("runtime/bin/java").toString())
|
||||
+ "\nargs = " + mapper.writeValueAsString(List.of("-cp", current.resolve("lib/*").toString(), "p.studio.app.StudioLauncher", "mcp", "--project", root.toString()))
|
||||
+ "\ncwd = " + quote(root.toString()) + "\nstartup_timeout_sec = 20\ntool_timeout_sec = 90\n";
|
||||
}
|
||||
private String quote(String text) throws Exception { return mapper.writeValueAsString(text); }
|
||||
static String merge(String old, String entry) throws Exception {
|
||||
if (Toml.parse(old).hasErrors()) throw new Conflict("Existing client TOML is invalid; repair it before preparation.");
|
||||
String block = BEGIN + hash(entry) + "\n" + entry + END;
|
||||
int start = old.indexOf(BEGIN), end = old.indexOf(END);
|
||||
String next;
|
||||
if (start >= 0) {
|
||||
int body = old.indexOf('\n', start) + 1;
|
||||
if (start > 0 && old.charAt(start - 1) != '\n' || body == 0 || end < body || old.indexOf(BEGIN, body) >= 0 || !old.substring(start + BEGIN.length(), body - 1).equals(hash(old.substring(body, end))))
|
||||
throw new Conflict("The Studio MCP entry was edited. Resolve the managed-entry conflict explicitly.");
|
||||
next = old.substring(0, start) + block + old.substring(end + END.length());
|
||||
} else {
|
||||
if (end >= 0 || Toml.parse(old).contains("mcp_servers.prometeu_studio")) throw new Conflict("A user-owned Studio MCP entry already exists; resolve it explicitly.");
|
||||
next = old + (old.isEmpty() || old.endsWith("\n") ? "" : "\n") + block;
|
||||
}
|
||||
if (Toml.parse(next).hasErrors()) throw new Conflict("Client configuration conflicts with the Studio entry; nothing was overwritten.");
|
||||
var actual = Toml.parse(next).getTable("mcp_servers.prometeu_studio");
|
||||
var expected = Toml.parse(entry).getTable("mcp_servers.prometeu_studio");
|
||||
if (actual == null || expected == null || !actual.keySet().equals(expected.keySet())
|
||||
|| !Objects.equals(actual.getString("command"), expected.getString("command"))
|
||||
|| !Objects.equals(actual.getString("cwd"), expected.getString("cwd"))
|
||||
|| !Objects.equals(actual.getLong("startup_timeout_sec"), expected.getLong("startup_timeout_sec"))
|
||||
|| !Objects.equals(actual.getLong("tool_timeout_sec"), expected.getLong("tool_timeout_sec"))
|
||||
|| actual.getArray("args") == null || !actual.getArray("args").toList().equals(expected.getArray("args").toList()))
|
||||
throw new Conflict("The managed Studio table conflicts with other client settings; resolve it explicitly.");
|
||||
return next;
|
||||
}
|
||||
private static String hash(String text) throws Exception { return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); }
|
||||
private static final class Conflict extends Exception { Conflict(String text) { super(text); } }
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package p.studio.app.mcp.stdio;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import p.studio.app.mcp.*;
|
||||
import java.io.*;
|
||||
import java.net.http.*;
|
||||
import java.nio.file.*;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
/** Owns only HTTP transport. Never retries a tools/call or creates task authority. */
|
||||
final class StudioMcpConnection implements AutoCloseable {
|
||||
private final Path root;
|
||||
private final ObjectMapper mapper;
|
||||
private final McpToolCatalog catalog;
|
||||
private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).followRedirects(HttpClient.Redirect.NEVER).build();
|
||||
private ProjectConnectionFiles.Descriptor descriptor;
|
||||
private String session;
|
||||
private Set<String> available = Set.of();
|
||||
// Diagnostic correlation only: Core remains the sole validator of task authority.
|
||||
private final LinkedHashMap<String, String> observedTaskInstances = new LinkedHashMap<>();
|
||||
private long sequence;
|
||||
private volatile String status = "WAITING_FOR_ACCESS";
|
||||
StudioMcpConnection(Path root, ObjectMapper mapper, McpToolCatalog catalog) { this.root = root; this.mapper = mapper; this.catalog = catalog; }
|
||||
String status() { return status; }
|
||||
synchronized void probe() {
|
||||
try { connect(); exchange("ping", mapper.createObjectNode(), true, 3); status = "CONNECTED"; }
|
||||
catch (Exception failure) { disconnect(); }
|
||||
}
|
||||
synchronized JsonNode call(String tool, JsonNode arguments) {
|
||||
boolean dispatched = false;
|
||||
try {
|
||||
catalog.validateArguments(tool, arguments);
|
||||
try {
|
||||
if (!Path.of(arguments.path("projectRoot").asText()).toRealPath().equals(root))
|
||||
return failure("OUTSIDE_PROJECT_SCOPE", "The connector is bound to another project.");
|
||||
} catch (IOException inaccessible) { return failure("INVALID_REQUEST", "Project root cannot be resolved."); }
|
||||
connect();
|
||||
String taskInstance = observedTaskInstances.get(arguments.path("taskId").asText());
|
||||
if (tool.equals("studio_operation_get") && taskInstance != null && !taskInstance.equals(descriptor.instanceId()))
|
||||
return failure("OUTCOME_UNKNOWN", "Studio restarted; this task's in-memory receipts are unavailable. Obtain a fresh grant/task and decide the next intent explicitly; do not replay the old operation.");
|
||||
if (!available.contains(tool)) return failure("UNSUPPORTED_CAPABILITY", "The live Studio does not provide this tool.");
|
||||
var params = mapper.createObjectNode().put("name", tool).set("arguments", arguments);
|
||||
dispatched = true;
|
||||
var response = exchange("tools/call", params, true, 70);
|
||||
if (response.has("error")) throw new ProtocolFailure(response.get("error"));
|
||||
status = "CONNECTED";
|
||||
var result = response.required("result");
|
||||
if (tool.equals("studio_control_acquire") && !result.path("isError").asBoolean()) {
|
||||
String task = result.path("structuredContent").path("value").path("taskId").asText();
|
||||
if (!task.isBlank()) {
|
||||
observedTaskInstances.put(task, descriptor.instanceId());
|
||||
if (observedTaskInstances.size() > 64) observedTaskInstances.remove(observedTaskInstances.keySet().iterator().next());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} catch (ProtocolFailure protocol) { throw protocol;
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
return failure("INVALID_REQUEST", "Invalid tool arguments or project root.");
|
||||
} catch (Exception unavailable) {
|
||||
disconnect();
|
||||
var result = failure(dispatched ? "OUTCOME_UNKNOWN" : status,
|
||||
dispatched ? "Response unavailable; do not replay. For the same authorized task, look up operationId/clientRequestId. After Studio restart, obtain a new grant; old receipts may be unavailable."
|
||||
: guidance());
|
||||
if (dispatched && arguments != null && arguments.path("clientRequestId").isTextual())
|
||||
((ObjectNode) result.path("structuredContent").path("error")).put("clientRequestId", arguments.path("clientRequestId").asText());
|
||||
((ObjectNode) result.path("content").get(0)).put("text", result.path("structuredContent").toString());
|
||||
return result;
|
||||
}
|
||||
}
|
||||
private String guidance() {
|
||||
return switch (status) {
|
||||
case "VERSION_INCOMPATIBLE" -> "Studio and its installed connector are incompatible; update the installation.";
|
||||
case "STALE_CONNECTION" -> "Connection credentials are stale or invalid; grant access again in DEV.";
|
||||
case "INVALID_DESCRIPTOR" -> "Project connection data or permissions are invalid; prepare the project again.";
|
||||
default -> "Open Studio and this project, then grant access in DEV. The connection will be discovered without restarting this client.";
|
||||
};
|
||||
}
|
||||
private void connect() throws Exception {
|
||||
ProjectConnectionFiles.Descriptor next;
|
||||
try { next = ProjectConnectionFiles.read(root, mapper); }
|
||||
catch (NoSuchFileException absent) { status = "WAITING_FOR_ACCESS"; throw absent; }
|
||||
catch (IOException invalid) {
|
||||
status = Files.exists(root.resolve(ProjectConnectionFiles.RELATIVE)) ? "INVALID_DESCRIPTOR" : "WAITING_FOR_ACCESS";
|
||||
throw invalid;
|
||||
}
|
||||
if (!catalog.fingerprint().equals(next.catalogFingerprint())) { status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible catalog"); }
|
||||
if (session != null && next.equals(descriptor)) return;
|
||||
descriptor = next; session = null; status = "RECONNECTING";
|
||||
var params = mapper.createObjectNode().put("protocolVersion", LocalMcpServer.PROTOCOL_VERSION);
|
||||
params.putObject("capabilities"); params.putObject("clientInfo").put("name", "studio-project-connector").put("version", "1");
|
||||
var result = exchange("initialize", params, true, 5).required("result");
|
||||
if (!LocalMcpServer.PROTOCOL_VERSION.equals(result.path("protocolVersion").asText())
|
||||
|| !catalog.fingerprint().equals(result.path("_meta").path("catalogFingerprint").asText())) {
|
||||
status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible protocol");
|
||||
}
|
||||
if (!next.instanceId().equals(result.path("_meta").path("instanceId").asText())
|
||||
|| !root.toString().equals(result.path("_meta").path("projectRoot").asText())) {
|
||||
status = "STALE_CONNECTION"; throw new IOException("Wrong instance");
|
||||
}
|
||||
exchange("notifications/initialized", mapper.createObjectNode(), false, 5);
|
||||
var descriptors = exchange("tools/list", mapper.createObjectNode(), true, 5).path("result").path("tools");
|
||||
if (!descriptors.isArray()) throw new IOException("Invalid catalog");
|
||||
var names = new HashSet<String>();
|
||||
for (var tool : descriptors) {
|
||||
String name = tool.path("name").asText();
|
||||
if (!catalog.names().contains(name) || !catalog.descriptor(name).equals(tool) || !names.add(name)) {
|
||||
status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible tools");
|
||||
}
|
||||
}
|
||||
available = Set.copyOf(names); status = "CONNECTED";
|
||||
}
|
||||
private JsonNode exchange(String method, JsonNode params, boolean responseExpected, int seconds) throws Exception {
|
||||
var message = mapper.createObjectNode().put("jsonrpc", "2.0").put("method", method);
|
||||
if (responseExpected) message.put("id", ++sequence);
|
||||
message.set("params", params);
|
||||
var request = HttpRequest.newBuilder(descriptor.endpoint()).timeout(Duration.ofSeconds(seconds))
|
||||
.header("Authorization", "Bearer " + descriptor.credential()).header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", LocalMcpServer.PROTOCOL_VERSION);
|
||||
if (session != null) request.header("Mcp-Session-Id", session);
|
||||
var pending = client.sendAsync(request.POST(HttpRequest.BodyPublishers.ofString(message.toString())).build(),
|
||||
info -> boundedBody());
|
||||
HttpResponse<byte[]> response;
|
||||
try { response = pending.get(seconds, java.util.concurrent.TimeUnit.SECONDS); }
|
||||
catch (Exception failure) { pending.cancel(true); throw failure; }
|
||||
if (response.statusCode() != 200 && response.statusCode() != 202) {
|
||||
if (response.statusCode() == 401 || response.statusCode() == 403 || response.statusCode() == 404) status = "STALE_CONNECTION";
|
||||
throw new IOException("Connection rejected");
|
||||
}
|
||||
response.headers().firstValue("Mcp-Session-Id").ifPresent(value -> session = value);
|
||||
if (method.equals("initialize") && session == null) throw new IOException("Missing session identity");
|
||||
if (!responseExpected) return mapper.nullNode();
|
||||
var json = mapper.readTree(response.body());
|
||||
if (json == null || !"2.0".equals(json.path("jsonrpc").asText()) || !json.path("id").isIntegralNumber() || !message.get("id").bigIntegerValue().equals(json.path("id").bigIntegerValue())
|
||||
|| json.has("result") == json.has("error")) throw new IOException("Invalid response");
|
||||
return json;
|
||||
}
|
||||
private static HttpResponse.BodySubscriber<byte[]> boundedBody() {
|
||||
return new HttpResponse.BodySubscriber<>() {
|
||||
final HttpResponse.BodySubscriber<byte[]> delegate = HttpResponse.BodySubscribers.ofByteArray();
|
||||
java.util.concurrent.Flow.Subscription subscription;
|
||||
long bytes;
|
||||
public java.util.concurrent.CompletionStage<byte[]> getBody() { return delegate.getBody(); }
|
||||
public void onSubscribe(java.util.concurrent.Flow.Subscription value) { subscription = value; delegate.onSubscribe(value); }
|
||||
public void onNext(List<java.nio.ByteBuffer> buffers) {
|
||||
for (var buffer : buffers) bytes += buffer.remaining();
|
||||
if (bytes > 32L * 1024 * 1024) { subscription.cancel(); delegate.onError(new IOException("Response too large")); }
|
||||
else delegate.onNext(buffers);
|
||||
}
|
||||
public void onError(Throwable failure) { delegate.onError(failure); }
|
||||
public void onComplete() { delegate.onComplete(); }
|
||||
};
|
||||
}
|
||||
|
||||
private ObjectNode failure(String code, String message) {
|
||||
var value = mapper.createObjectNode().put("isError", true);
|
||||
var data = value.putObject("structuredContent").put("status", "error");
|
||||
data.putObject("error").put("code", code).put("message", message);
|
||||
value.putArray("content").addObject().put("type", "text").put("text", data.toString());
|
||||
return value;
|
||||
}
|
||||
static final class ProtocolFailure extends RuntimeException {
|
||||
final JsonNode error;
|
||||
ProtocolFailure(JsonNode error) { super("Studio protocol error"); this.error = error.deepCopy(); }
|
||||
}
|
||||
|
||||
private void disconnect() { if (status.equals("CONNECTED")) status = "RECONNECTING"; session = null; available = Set.of(); }
|
||||
@Override public void close() { client.shutdownNow(); }
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package p.studio.app.mcp.stdio;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import p.studio.app.mcp.*;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/** A mode of Studio itself; no JavaFX, Spring, HTTP listener or agent runtime is started here. */
|
||||
public final class StudioMcpStdio {
|
||||
private StudioMcpStdio() { }
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length != 3 || !"mcp".equals(args[0]) || !"--project".equals(args[1]) || !Path.of(args[2]).isAbsolute())
|
||||
throw new IllegalArgumentException("Usage: mcp --project <absolute-project-root>");
|
||||
Path root = Path.of(args[2]).toRealPath();
|
||||
if (!Files.isRegularFile(root.resolve("prometeu.json"))) throw new IllegalArgumentException("Project manifest not found");
|
||||
run(root, System.in, System.out);
|
||||
}
|
||||
public static void run(Path root, InputStream input, OutputStream output) throws Exception {
|
||||
var mapper = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||
mapper.getFactory().setStreamReadConstraints(com.fasterxml.jackson.core.StreamReadConstraints.builder().maxStringLength(32 * 1024 * 1024).build());
|
||||
var catalog = new McpToolCatalog(mapper);
|
||||
var timer = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().name("studio-mcp-discovery").factory());
|
||||
try (var connection = new StudioMcpConnection(root, mapper, catalog)) {
|
||||
timer.scheduleWithFixedDelay(connection::probe, 0, 2, TimeUnit.SECONDS);
|
||||
boolean initialized = false, negotiated = false;
|
||||
var line = new ByteArrayOutputStream(); int next;
|
||||
while ((next = input.read()) != -1) {
|
||||
if (next != '\n') {
|
||||
if (line.size() >= 1024 * 1024) throw new IOException("MCP request exceeds limit");
|
||||
line.write(next); continue;
|
||||
}
|
||||
JsonNode message;
|
||||
try { message = mapper.readTree(StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(line.toByteArray())).toString()); }
|
||||
catch (Exception malformed) { line.reset(); write(output, error(mapper, mapper.nullNode(), -32700, "Invalid JSON")); continue; }
|
||||
line.reset();
|
||||
if (message == null || !message.isObject() || !message.path("jsonrpc").isTextual() || !"2.0".equals(message.path("jsonrpc").asText())
|
||||
|| !message.path("method").isTextual() || message.has("id") && !(message.path("id").isTextual() || message.path("id").isIntegralNumber())) {
|
||||
write(output, error(mapper, mapper.nullNode(), -32600, "Invalid request")); continue;
|
||||
}
|
||||
String method = message.path("method").asText();
|
||||
if (!message.has("id")) { if (negotiated && "notifications/initialized".equals(method)) initialized = true; continue; }
|
||||
var id = message.get("id"); JsonNode result;
|
||||
if (method.equals("initialize") && !negotiated) {
|
||||
var params = message.path("params");
|
||||
if (!params.path("protocolVersion").isTextual() || !params.path("capabilities").isObject() || !params.path("clientInfo").isObject()) {
|
||||
write(output, error(mapper, id, -32602, "Invalid initialization")); continue;
|
||||
}
|
||||
var value = mapper.createObjectNode().put("protocolVersion", LocalMcpServer.PROTOCOL_VERSION);
|
||||
value.putObject("capabilities").putObject("tools").put("listChanged", false);
|
||||
value.putObject("serverInfo").put("name", "prometeu-studio").put("version", "1");
|
||||
value.put("instructions", McpConnectionGuide.INSTRUCTIONS + "\nProject root: " + root);
|
||||
result = value; negotiated = true;
|
||||
} else if (!initialized) { write(output, error(mapper, id, -32600, "Initialization required")); continue; }
|
||||
else if (method.equals("ping")) result = mapper.createObjectNode();
|
||||
else if (method.equals("tools/list")) {
|
||||
var value = mapper.createObjectNode(); var tools = value.putArray("tools");
|
||||
catalog.names().forEach(name -> tools.add(catalog.descriptor(name))); result = value;
|
||||
} else if (method.equals("tools/call")) {
|
||||
String tool = message.path("params").path("name").asText();
|
||||
var arguments = message.path("params").path("arguments");
|
||||
try { catalog.validateArguments(tool, arguments); }
|
||||
catch (IllegalArgumentException invalid) { write(output, error(mapper, id, -32602, "Invalid tool arguments")); continue; }
|
||||
try { result = connection.call(tool, arguments); }
|
||||
catch (StudioMcpConnection.ProtocolFailure protocol) {
|
||||
var reply = mapper.createObjectNode().put("jsonrpc", "2.0"); reply.set("id", id); reply.set("error", protocol.error);
|
||||
write(output, reply); continue;
|
||||
}
|
||||
} else { write(output, error(mapper, id, -32601, "Method not found")); continue; }
|
||||
var reply = mapper.createObjectNode().put("jsonrpc", "2.0"); reply.set("id", id); reply.set("result", result); write(output, reply);
|
||||
}
|
||||
} finally { timer.shutdownNow(); }
|
||||
}
|
||||
private static JsonNode error(ObjectMapper mapper, JsonNode id, int code, String text) {
|
||||
var reply = mapper.createObjectNode().put("jsonrpc", "2.0"); reply.set("id", id);
|
||||
reply.putObject("error").put("code", code).put("message", text); return reply;
|
||||
}
|
||||
private static void write(OutputStream output, JsonNode value) throws IOException {
|
||||
output.write(value.toString().getBytes(StandardCharsets.UTF_8)); output.write('\n'); output.flush();
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,12 @@ class DevDesktopTest {
|
||||
completed.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
static void awaitWaiting(AutomationSession authority) throws Exception {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (authority.snapshot().state() != ControlState.WAITING_FOR_AGENT && System.nanoTime() < deadline) Thread.sleep(5);
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
}
|
||||
|
||||
@Test void devDebugNavigationBackgroundProjectionAndDisposal() throws Exception {
|
||||
var pool = Executors.newSingleThreadExecutor();
|
||||
var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool));
|
||||
@@ -70,6 +76,9 @@ class DevDesktopTest {
|
||||
assertEquals(1, subscriptions.get());
|
||||
assertTrue(((Button) dev[0].rootNode().lookup("#dev-mcp-config")).isDisabled());
|
||||
((Button) dev[0].rootNode().lookup("#dev-grant")).fire();
|
||||
});
|
||||
awaitWaiting(authority);
|
||||
fx(() -> {
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
host[0].change(WorkspaceId.DEBUG); assertEquals(0, subscriptions.get());
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
@@ -96,8 +105,8 @@ class DevDesktopTest {
|
||||
locale.setLocale(java.util.Locale.forLanguageTag("pt-BR"));
|
||||
host[0].deactivateCurrentWorkspace(); assertEquals(0, subscriptions.get());
|
||||
authority.grant(false); locale.setLocale(java.util.Locale.ENGLISH);
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
});
|
||||
awaitWaiting(authority);
|
||||
} finally {
|
||||
fx(() -> { if (host[0] != null) host[0].deactivateCurrentWorkspace(); if (stage[0] != null) stage[0].close(); });
|
||||
authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); pool.shutdownNow();
|
||||
@@ -120,56 +129,39 @@ class DevDesktopTest {
|
||||
});
|
||||
}
|
||||
|
||||
@Test void copiesLiveConnectionWithoutGrantOrCredentialDisplayAndRefreshesAvailability() throws Exception {
|
||||
@Test void preparesConnectionWithoutGrantAndRemainsAvailableWhenTransportStops() throws Exception {
|
||||
var mapper = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
var projects = new p.studio.core.project.ProjectAccessRegistry();
|
||||
var savedClipboard = new java.util.HashMap<javafx.scene.input.DataFormat, Object>();
|
||||
var copied = new java.util.concurrent.atomic.AtomicReference<String>();
|
||||
var prepared = new CompletableFuture<Void>();
|
||||
var view = new DevWorkspace[1]; var stage = new Stage[1];
|
||||
try (var pool = Executors.newSingleThreadExecutor();
|
||||
var server = new p.studio.app.mcp.LocalMcpServer(mapper, new p.studio.app.mcp.McpToolRegistry(
|
||||
new p.studio.app.mcp.McpToolCatalog(mapper), mapper, java.util.Map.of()))) {
|
||||
var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool));
|
||||
var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority);
|
||||
var guide = new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper);
|
||||
var guide = new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper, project -> {
|
||||
prepared.complete(null);
|
||||
return new p.studio.api.automation.AgentIntegrationPreparation.Result(true, "Prepared; trust/reload once.");
|
||||
});
|
||||
server.start();
|
||||
try {
|
||||
fx(() -> {
|
||||
var clipboard = javafx.scene.input.Clipboard.getSystemClipboard();
|
||||
clipboard.getContentTypes().forEach(type -> savedClipboard.put(type, clipboard.getContent(type)));
|
||||
var project = new ProjectReference("Connection smoke", "1", "pbs", 1, ProjectTarget.Game, root);
|
||||
view[0] = new DevWorkspace(project, authority, new I18nService(), new StudioEventBus(), guide);
|
||||
stage[0] = new Stage(); stage[0].setScene(new Scene(new VBox(view[0].rootNode()), 1050, 800)); stage[0].show();
|
||||
view[0].load();
|
||||
var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled());
|
||||
button.fire(); copied.set(clipboard.getString());
|
||||
assertEquals(ControlState.MANUAL, authority.snapshot().state());
|
||||
assertEquals(server.connection().endpoint().toString(), ((Label) view[0].rootNode().lookup("#dev-mcp-endpoint")).getText());
|
||||
assertTrue(view[0].rootNode().lookupAll(".label").stream().filter(n -> n instanceof Label)
|
||||
.noneMatch(n -> ((Label) n).getText().contains(server.connection().authorizationHeader())));
|
||||
var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled()); button.fire();
|
||||
});
|
||||
var first = mapper.readTree(copied.get());
|
||||
assertTrue(server.connection().authorizationHeader().equals(first.path("headers").path("Authorization").asText()));
|
||||
assertEquals(root.toRealPath().toString(), first.path("projectRoot").asText());
|
||||
prepared.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(ControlState.MANUAL, authority.snapshot().state());
|
||||
server.close();
|
||||
fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled()));
|
||||
fx(() -> assertFalse(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled()));
|
||||
server.start(); authority.grant(false).toCompletableFuture().join();
|
||||
fx(() -> {
|
||||
var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled());
|
||||
button.fire(); copied.set(javafx.scene.input.Clipboard.getSystemClipboard().getString());
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
});
|
||||
var next = mapper.readTree(copied.get());
|
||||
assertFalse(first.path("headers").equals(next.path("headers")));
|
||||
assertTrue(server.connection().authorizationHeader().equals(next.path("headers").path("Authorization").asText()));
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled()));
|
||||
} finally {
|
||||
fx(() -> {
|
||||
if (view[0] != null) view[0].unLoad();
|
||||
if (stage[0] != null) stage[0].close();
|
||||
javafx.scene.input.Clipboard.getSystemClipboard().setContent(savedClipboard);
|
||||
});
|
||||
fx(() -> { if (view[0] != null) view[0].unLoad(); if (stage[0] != null) stage[0].close(); });
|
||||
authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); registration.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package p.studio.app.install;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.app.mcp.StudioAgentPreparation;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.api.project.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class InstalledConnectorTest {
|
||||
@TempDir Path temporary;
|
||||
@Test void bundledJavaAndStableUpdateWorkWithSpacesMinimalEnvironmentAndBothPreparationPaths() throws Exception {
|
||||
Path base = temporary.resolve("Application Support/Studio");
|
||||
Path source = Path.of(System.getProperty("studio.test.distribution"));
|
||||
Path first = ManagedStudioInstallation.install(source, base);
|
||||
var mapper = new ObjectMapper();
|
||||
var preparation = new StudioAgentPreparation(base, mapper);
|
||||
var catalog = new ProjectCatalogService(temporary, mapper, new ProjectLocalStudioSetupStore(mapper), preparation);
|
||||
var scaffold = catalog.createProject(new ProjectCreationRequest("Scaffold Game", temporary, "pbs", 1, ProjectTarget.Game, "src", 8, "/my/runtime"));
|
||||
assertTrue(preparation.status(scaffold.rootPath()).ready());
|
||||
Path existing = Files.createDirectory(temporary.resolve("Existing Project"));
|
||||
Files.copy(scaffold.rootPath().resolve("prometeu.json"), existing.resolve("prometeu.json"));
|
||||
Files.createDirectory(existing.resolve(".studio"));
|
||||
Files.writeString(existing.resolve(".studio/setup.json"), "{\"runtimePath\":\"/preserved/runtime\",\"custom\":42}");
|
||||
Files.createDirectory(existing.resolve(".codex"));
|
||||
String custom = "# preserve\napproval_policy = \"on-request\"\n[mcp_servers.other]\ncommand = \"other\"\n";
|
||||
Files.writeString(existing.resolve(".codex/config.toml"), custom);
|
||||
assertTrue(preparation.prepare(existing).ready());
|
||||
var config = existing.resolve(".codex/config.toml");
|
||||
String stable = Files.readString(config); var modified = Files.getLastModifiedTime(config);
|
||||
assertTrue(stable.startsWith(custom)); assertTrue(preparation.prepare(existing).ready());
|
||||
assertEquals(stable, Files.readString(config)); assertEquals(modified, Files.getLastModifiedTime(config));
|
||||
var setup = mapper.readTree(Files.readString(existing.resolve(".studio/setup.json")));
|
||||
assertEquals(42, setup.path("custom").asInt()); assertEquals("/preserved/runtime", setup.path("runtimePath").asText());
|
||||
assertFalse(Files.exists(existing.resolve(".studio/mcp/connection.json")));
|
||||
runConnector(base, existing);
|
||||
Path second = ManagedStudioInstallation.install(source, base);
|
||||
assertNotEquals(first, second); assertTrue(Files.isDirectory(first));
|
||||
assertEquals(second.toRealPath(), base.resolve("current").toRealPath());
|
||||
assertEquals(stable, Files.readString(config)); runConnector(base, existing);
|
||||
assertThrows(Exception.class, () -> ManagedStudioInstallation.install(existing, base));
|
||||
assertEquals(second.toRealPath(), base.resolve("current").toRealPath()); runConnector(base, existing);
|
||||
// Test fixture only: installed runtime/lib must load and start JavaFX, without checkout application classes.
|
||||
String fixtures = Path.of(DesktopProbe.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString();
|
||||
var desktop = minimal(base.resolve("current/runtime/bin/java").toString(), "-cp", base.resolve("current/lib/*") + java.io.File.pathSeparator + fixtures,
|
||||
DesktopProbe.class.getName()).redirectError(temporary.resolve("desktop.stderr").toFile()).start();
|
||||
try { assertTrue(desktop.waitFor(20, TimeUnit.SECONDS)); assertEquals(0, desktop.exitValue(), Files.readString(temporary.resolve("desktop.stderr"))); }
|
||||
finally { desktop.destroyForcibly(); }
|
||||
}
|
||||
void runConnector(Path base, Path root) throws Exception {
|
||||
var process = minimal(base.resolve("current/runtime/bin/java").toString(), "-cp", base.resolve("current/lib/*").toString(),
|
||||
"p.studio.app.StudioLauncher", "mcp", "--project", root.toRealPath().toString()).start();
|
||||
try {
|
||||
String input = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"installed-test\",\"version\":\"1\"}}}\n";
|
||||
process.getOutputStream().write(input.getBytes(java.nio.charset.StandardCharsets.UTF_8)); process.getOutputStream().close();
|
||||
assertTrue(process.waitFor(15, TimeUnit.SECONDS)); assertEquals(0, process.exitValue());
|
||||
assertEquals("prometeu-studio", new ObjectMapper().readTree(process.getInputStream()).path("result").path("serverInfo").path("name").asText());
|
||||
} finally { process.destroyForcibly(); }
|
||||
}
|
||||
ProcessBuilder minimal(String... args) {
|
||||
var builder = new ProcessBuilder(args).directory(temporary.toFile());
|
||||
builder.environment().clear(); builder.environment().put("PATH", "/usr/bin:/bin"); builder.environment().put("HOME", System.getProperty("user.home"));
|
||||
return builder;
|
||||
}
|
||||
public static class DesktopProbe {
|
||||
public static void main(String[] args) {
|
||||
javafx.application.Platform.startup(() -> {
|
||||
try {
|
||||
var stage = new javafx.stage.Stage(); stage.setScene(new javafx.scene.Scene(new javafx.scene.control.Label("Installed Studio JavaFX")));
|
||||
stage.show(); stage.close(); System.exit(0);
|
||||
} catch (Throwable failure) { System.exit(2); }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AutomationLspQueriesTest {
|
||||
String httpAuthorization;
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final ExecutorService workers = Executors.newCachedThreadPool();
|
||||
@@ -134,6 +135,8 @@ class AutomationLspQueriesTest {
|
||||
try (var server = new p.studio.app.mcp.LocalMcpServer(mapper, tools);
|
||||
var client = java.net.http.HttpClient.newHttpClient()) {
|
||||
server.start();
|
||||
var credential = server.credentials().prepare(root.toRealPath());
|
||||
credential.activate(); httpAuthorization = "Bearer " + credential.secret();
|
||||
var initialize = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize");
|
||||
var setup = initialize.putObject("params").put("protocolVersion", "2025-06-18");
|
||||
setup.putObject("capabilities"); setup.putObject("clientInfo").put("name", "language-test").put("version", "1");
|
||||
@@ -155,7 +158,7 @@ class AutomationLspQueriesTest {
|
||||
private java.net.http.HttpResponse<String> post(java.net.http.HttpClient client, p.studio.app.mcp.LocalMcpServer server,
|
||||
String connection, JsonNode body) throws Exception {
|
||||
var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).timeout(java.time.Duration.ofSeconds(15))
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json")
|
||||
.header("Authorization", httpAuthorization).header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18");
|
||||
if (connection != null) request.header("Mcp-Session-Id", connection);
|
||||
return client.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), java.net.http.HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
@@ -15,6 +15,12 @@ class LocalMcpServerTest {
|
||||
final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
|
||||
LocalMcpServer server;
|
||||
String session;
|
||||
@org.junit.jupiter.api.io.TempDir java.nio.file.Path root;
|
||||
String authorization;
|
||||
void authorize(java.nio.file.Path project) throws Exception {
|
||||
var credential = server.credentials().prepare(project.toRealPath());
|
||||
credential.activate(); authorization = "Bearer " + credential.secret();
|
||||
}
|
||||
AtomicInteger calls;
|
||||
|
||||
@BeforeEach void start() throws Exception {
|
||||
@@ -22,7 +28,7 @@ class LocalMcpServerTest {
|
||||
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of(
|
||||
"studio_project_context", args -> { calls.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("projectRoot", args.get("projectRoot").asText())); },
|
||||
"studio_control_acquire", args -> McpToolResult.failure(mapper, new AutomationFailure(AutomationFailure.Code.NOT_GRANTED, "Human grant required")))));
|
||||
server.start();
|
||||
server.start(); authorize(root);
|
||||
}
|
||||
@AfterEach void close() { server.close(); client.close(); }
|
||||
HttpResponse<String> request(String method, URI uri, String body, String token, String origin, String protocol, String sessionId) throws Exception {
|
||||
@@ -35,7 +41,7 @@ class LocalMcpServerTest {
|
||||
return client.send(request.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
HttpResponse<String> post(String body) throws Exception {
|
||||
return request("POST", server.connection().endpoint(), body, server.connection().authorizationHeader(), null, LocalMcpServer.PROTOCOL_VERSION, session);
|
||||
return request("POST", server.connection().endpoint(), body.replace("/project", root.toRealPath().toString()), authorization, null, LocalMcpServer.PROTOCOL_VERSION, session);
|
||||
}
|
||||
static String init() { return "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"clientInfo\":{\"name\":\"test-client\",\"version\":\"1\"},\"capabilities\":{}}}"; }
|
||||
void initialize() throws Exception {
|
||||
@@ -51,11 +57,11 @@ class LocalMcpServerTest {
|
||||
var response = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"/project\"}}}");
|
||||
assertEquals(200, response.statusCode()); assertEquals(1, calls.get());
|
||||
assertEquals("ok", mapper.readTree(response.body()).path("result").path("structuredContent").path("status").asText());
|
||||
assertEquals(200, request("DELETE", server.connection().endpoint(), null, server.connection().authorizationHeader(), null, null, session).statusCode());
|
||||
assertEquals(200, request("DELETE", server.connection().endpoint(), null, authorization, null, null, session).statusCode());
|
||||
assertEquals(404, post("{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"ping\"}").statusCode());
|
||||
}
|
||||
@Test void authAndOriginAreCheckedBeforeProtocolOrTools() throws Exception {
|
||||
var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader();
|
||||
var endpoint = server.connection().endpoint(); var token = authorization;
|
||||
assertEquals("127.0.0.1", endpoint.getHost()); assertTrue(endpoint.getPort() > 0);
|
||||
assertEquals(401, request("POST", endpoint, init(), null, null, null, null).statusCode());
|
||||
assertEquals(401, request("POST", endpoint, init(), "Bearer wrong", null, null, null).statusCode());
|
||||
@@ -66,10 +72,10 @@ class LocalMcpServerTest {
|
||||
assertFalse(server.connection().toString().contains(token.substring(7)));
|
||||
}
|
||||
@Test void restartChangesCredentialsInvalidatesConnectionsAndDoesNotPersistThem() throws Exception {
|
||||
initialize(); var old = server.connection(); server.close();
|
||||
initialize(); var old = authorization; server.close();
|
||||
assertFalse(server.isRunning()); assertThrows(IllegalStateException.class, server::connection);
|
||||
server.start(); assertFalse(old.authorizationHeader().equals(server.connection().authorizationHeader()));
|
||||
assertEquals(401, request("POST", server.connection().endpoint(), init(), old.authorizationHeader(), null, null, null).statusCode());
|
||||
server.start(); authorize(root); assertFalse(old.equals(authorization));
|
||||
assertEquals(401, request("POST", server.connection().endpoint(), init(), old, null, null, null).statusCode());
|
||||
assertEquals(404, post(init()).statusCode());
|
||||
session = null; initialize();
|
||||
}
|
||||
@@ -81,13 +87,13 @@ class LocalMcpServerTest {
|
||||
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"method\":123}").statusCode());
|
||||
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"id\":2,\"method\":\"ping\"}").statusCode());
|
||||
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"} {}").statusCode());
|
||||
assertEquals(400, request("POST", server.connection().endpoint(), init(), server.connection().authorizationHeader(), null, "unknown", session).statusCode());
|
||||
assertEquals(400, request("POST", server.connection().endpoint(), init(), authorization, null, "unknown", session).statusCode());
|
||||
var bad = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"relative\"}}}");
|
||||
assertEquals(-32602, mapper.readTree(bad.body()).path("error").path("code").intValue()); assertEquals(0, calls.get());
|
||||
assertEquals(413, post(" ".repeat(1024 * 1024 + 1)).statusCode());
|
||||
}
|
||||
@Test void exactEndpointNoSseAndInitializationAreEnforced() throws Exception {
|
||||
var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader();
|
||||
var endpoint = server.connection().endpoint(); var token = authorization;
|
||||
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").statusCode());
|
||||
var initialized = post(init()); session = initialized.headers().firstValue("Mcp-Session-Id").orElseThrow();
|
||||
assertEquals(-32600, mapper.readTree(post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").body()).path("error").path("code").asInt());
|
||||
@@ -117,7 +123,7 @@ class LocalMcpServerTest {
|
||||
server.close();
|
||||
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper,
|
||||
McpProjectKnowledgeTools.handlers(knowledge, mapper)));
|
||||
server.start();
|
||||
server.start(); authorize(root);
|
||||
initialize();
|
||||
var call = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 2).put("method", "tools/call");
|
||||
call.putObject("params").put("name", "studio_project_context").putObject("arguments").put("projectRoot", root.toString());
|
||||
@@ -153,13 +159,13 @@ class LocalMcpServerTest {
|
||||
var connection = server.connection();
|
||||
try (var socket = new java.net.Socket("127.0.0.1", connection.endpoint().getPort())) {
|
||||
socket.setSoTimeout(3000);
|
||||
String request = "POST /mcp HTTP/1.1\r\nHost: evil.example\r\nAuthorization: " + connection.authorizationHeader()
|
||||
String request = "POST /mcp HTTP/1.1\r\nHost: evil.example\r\nAuthorization: " + authorization
|
||||
+ "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
|
||||
socket.getOutputStream().write(request.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
var status = new java.io.BufferedReader(new java.io.InputStreamReader(socket.getInputStream())).readLine();
|
||||
assertTrue(status.contains("403"));
|
||||
}
|
||||
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
|
||||
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", authorization)
|
||||
.header("Origin", "http://" + connection.endpoint().getRawAuthority()).header("Origin", "https://evil.example")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(init())).build();
|
||||
assertEquals(403, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
@@ -167,13 +173,29 @@ class LocalMcpServerTest {
|
||||
|
||||
@Test void contentNegotiationAcceptsWeightedTypesAndRejectsInvalidUtf8() throws Exception {
|
||||
var connection = server.connection();
|
||||
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
|
||||
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", authorization)
|
||||
.header("Accept", "application/json;q=1, text/event-stream;q=0.5").header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(init())).build();
|
||||
assertEquals(200, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
var invalid = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
|
||||
var invalid = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", authorization)
|
||||
.header("Accept", "application/json, text/event-stream").header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(new byte[]{(byte) 0xc3, (byte) 0x28})).build();
|
||||
assertEquals(400, client.send(invalid, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
}
|
||||
@Test void projectCredentialsCannotCrossRootsOrReuseAnotherSession() throws Exception {
|
||||
initialize();
|
||||
var other = java.nio.file.Files.createDirectory(root.resolve("other")).toRealPath();
|
||||
var credential = server.credentials().prepare(other); credential.activate();
|
||||
var wire = "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/list\"}";
|
||||
assertEquals(403, request("POST", server.connection().endpoint(), wire, "Bearer " + credential.secret(), null,
|
||||
LocalMcpServer.PROTOCOL_VERSION, session).statusCode());
|
||||
var call = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 5).put("method", "tools/call");
|
||||
call.putObject("params").put("name", "studio_project_context").putObject("arguments").put("projectRoot", other.toString());
|
||||
var reply = mapper.readTree(post(call.toString()).body());
|
||||
assertEquals("OUTSIDE_PROJECT_SCOPE", reply.path("result").path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(0, calls.get());
|
||||
server.credentials().authenticate(authorization).invalidate();
|
||||
assertEquals(401, post(wire).statusCode());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,38 +15,34 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class McpConnectionGuideTest {
|
||||
@TempDir Path root;
|
||||
@Test void exportsLiveProjectDescriptorWithoutGrantAndTracksRestartWithoutRetainingSecrets() throws Exception {
|
||||
@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 guide = new McpConnectionGuide(server, projects, mapper);
|
||||
assertTrue(guide.endpoint().isEmpty());
|
||||
assertThrows(IllegalStateException.class, () -> guide.configuration(root));
|
||||
var notifications = new AtomicInteger();
|
||||
var subscription = guide.subscribe(notifications::incrementAndGet);
|
||||
server.start(); assertEquals(2, notifications.get());
|
||||
var descriptor = mapper.readTree(guide.configuration(root));
|
||||
assertEquals(server.connection().endpoint().toString(), descriptor.path("url").asText());
|
||||
assertEquals(root.toRealPath().toString(), descriptor.path("projectRoot").asText());
|
||||
// Do not put bearer credentials into assertion diagnostics.
|
||||
assertTrue(server.connection().authorizationHeader().equals(descriptor.path("headers").path("Authorization").asText()));
|
||||
assertFalse(guide.toString().contains(descriptor.path("headers").path("Authorization").asText()));
|
||||
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(descriptor.path("instructions").asText().contains(instruction));
|
||||
var old = server.connection(); server.close(); assertEquals(3, notifications.get()); assertTrue(guide.endpoint().isEmpty());
|
||||
server.start(); assertEquals(4, notifications.get());
|
||||
var fresh = mapper.readTree(guide.configuration(root));
|
||||
assertTrue(fresh.path("headers").path("Authorization").asText().equals(server.connection().authorizationHeader()));
|
||||
assertFalse(fresh.path("headers").path("Authorization").asText().equals(old.authorizationHeader()));
|
||||
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(); subscription.close(); server.close(); assertEquals(4, notifications.get());
|
||||
registration.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import java.util.function.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class McpTaskToolsTest {
|
||||
String httpAuthorization;
|
||||
@TempDir Path root;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final ExecutorService workers = Executors.newCachedThreadPool();
|
||||
@@ -243,6 +244,8 @@ class McpTaskToolsTest {
|
||||
compose(shipper);
|
||||
try (var server = new LocalMcpServer(mapper, tools); var client = java.net.http.HttpClient.newHttpClient()) {
|
||||
server.start();
|
||||
var credential = server.credentials().prepare(root.toRealPath());
|
||||
credential.activate(); httpAuthorization = "Bearer " + credential.secret();
|
||||
var initialize = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize");
|
||||
var params = initialize.putObject("params").put("protocolVersion", "2025-06-18");
|
||||
params.putObject("capabilities"); params.putObject("clientInfo").put("name", "task-test").put("version", "1");
|
||||
@@ -281,6 +284,8 @@ class McpTaskToolsTest {
|
||||
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers));
|
||||
var client = java.net.http.HttpClient.newHttpClient()) {
|
||||
server.start();
|
||||
var credential = server.credentials().prepare(root.toRealPath());
|
||||
credential.activate(); httpAuthorization = "Bearer " + credential.secret();
|
||||
var unauthorized = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).POST(java.net.http.HttpRequest.BodyPublishers.ofString("{}"))
|
||||
.timeout(java.time.Duration.ofSeconds(5)).build();
|
||||
assertEquals(401, client.send(unauthorized, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
@@ -315,7 +320,7 @@ class McpTaskToolsTest {
|
||||
var captured = httpCall(client, server, first, "studio_headless_capture", args()); value(captured);
|
||||
assertArrayEquals(session.snapshot().capture().png(), Base64.getDecoder().decode(captured.path("content").get(1).path("data").asText()));
|
||||
var deleted = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).DELETE()
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", first).build();
|
||||
.header("Authorization", httpAuthorization).header("Mcp-Session-Id", first).build();
|
||||
assertEquals(200, client.send(deleted, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
|
||||
String reconnected = connect(client, server);
|
||||
@@ -367,7 +372,7 @@ class McpTaskToolsTest {
|
||||
}
|
||||
java.net.http.HttpResponse<String> post(java.net.http.HttpClient client, LocalMcpServer server, String connection, JsonNode body) throws Exception {
|
||||
var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).timeout(java.time.Duration.ofSeconds(10))
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json")
|
||||
.header("Authorization", httpAuthorization).header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18");
|
||||
if (connection != null) request.header("Mcp-Session-Id", connection);
|
||||
return client.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), java.net.http.HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ProjectConnectionPublisherTest {
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
LocalMcpServer server;
|
||||
Path root;
|
||||
@BeforeEach void start() throws Exception {
|
||||
root = temporary.toRealPath();
|
||||
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of())); server.start();
|
||||
}
|
||||
@AfterEach void stop() { server.close(); }
|
||||
@Test void publishesPrivatelyOnlyActivatesExplicitlyAndCleansUpOwnedGeneration() throws Exception {
|
||||
Files.writeString(root.resolve(".gitignore"), "# existing\n/build/\n");
|
||||
var publisher = new ProjectConnectionPublisher(server, mapper);
|
||||
var publication = publisher.prepare(root);
|
||||
publication.publish();
|
||||
var descriptor = ProjectConnectionFiles.read(root, mapper);
|
||||
assertNull(server.credentials().authenticate("Bearer " + descriptor.credential()));
|
||||
publication.activate();
|
||||
assertEquals(root, server.credentials().authenticate("Bearer " + descriptor.credential()).root());
|
||||
var file = root.resolve(ProjectConnectionFiles.RELATIVE);
|
||||
assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(file));
|
||||
assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(file.getParent()));
|
||||
assertFalse(descriptor.toString().contains(descriptor.credential()));
|
||||
assertThrows(Exception.class, () -> publisher.prepare(root));
|
||||
publication.invalidate(); assertNull(server.credentials().authenticate("Bearer " + descriptor.credential()));
|
||||
publication.close(); assertFalse(Files.exists(file)); assertTrue(Files.exists(file.resolveSibling("publication.lock")));
|
||||
try (var next = publisher.prepare(root)) {
|
||||
next.publish(); next.activate(); publication.close();
|
||||
assertTrue(Files.exists(file));
|
||||
assertNotEquals(descriptor.credential(), ProjectConnectionFiles.read(root, mapper).credential());
|
||||
}
|
||||
assertEquals("# existing\n/build/\n/.studio/mcp/\n", Files.readString(root.resolve(".gitignore")));
|
||||
}
|
||||
@Test void unsafePathsAndPermissionsNeverPublishSecrets() throws Exception {
|
||||
Path destination = Files.createDirectory(root.resolve("outside"));
|
||||
Files.createSymbolicLink(root.resolve(".studio"), destination);
|
||||
assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root));
|
||||
assertFalse(Files.exists(destination.resolve("mcp")));
|
||||
Files.delete(root.resolve(".studio"));
|
||||
Path directory = ProjectConnectionFiles.directory(root);
|
||||
Files.setPosixFilePermissions(directory, PosixFilePermissions.fromString("rwxr-xr-x"));
|
||||
assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root));
|
||||
}
|
||||
@Test void malformedDescriptorsNeverSupplyAnArbitraryEndpoint() throws Exception {
|
||||
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root)) {
|
||||
publication.publish();
|
||||
Path path = root.resolve(ProjectConnectionFiles.RELATIVE);
|
||||
var valid = mapper.readTree(Files.readString(path));
|
||||
for (String endpoint : java.util.List.of("https://example.com/mcp", "http://127.0.0.1:123/mcp?x=1", "http://localhost:123/mcp")) {
|
||||
var bad = valid.deepCopy(); ((com.fasterxml.jackson.databind.node.ObjectNode) bad).put("endpoint", endpoint);
|
||||
Files.writeString(path, bad.toString()); assertThrows(Exception.class, () -> ProjectConnectionFiles.read(root, mapper));
|
||||
}
|
||||
Files.writeString(path, valid.toString());
|
||||
}
|
||||
}
|
||||
@Test void osLockRejectsAnotherJvmAndCrashAllowsRecoveryWithoutUnlinkingLock() throws Exception {
|
||||
Process owner = ownerProcess();
|
||||
try {
|
||||
assertEquals("READY", java.util.concurrent.CompletableFuture.supplyAsync(() -> {
|
||||
try { return owner.inputReader().readLine(); } catch (java.io.IOException failure) { throw new java.io.UncheckedIOException(failure); }
|
||||
}).get(10, java.util.concurrent.TimeUnit.SECONDS));
|
||||
var lock = root.resolve(".studio/mcp/publication.lock");
|
||||
var inode = Files.readAttributes(lock, java.nio.file.attribute.BasicFileAttributes.class).fileKey();
|
||||
Process conflict = ownerProcess();
|
||||
try { assertTrue(conflict.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)); assertEquals(2, conflict.exitValue()); }
|
||||
finally { conflict.destroyForcibly(); }
|
||||
owner.destroyForcibly(); assertTrue(owner.waitFor(10, java.util.concurrent.TimeUnit.SECONDS));
|
||||
assertTrue(Files.exists(root.resolve(ProjectConnectionFiles.RELATIVE)));
|
||||
try (var recovered = new ProjectConnectionPublisher(server, mapper).prepare(root)) {
|
||||
recovered.publish(); recovered.activate();
|
||||
assertEquals(server.instanceId(), ProjectConnectionFiles.read(root, mapper).instanceId());
|
||||
assertEquals(inode, Files.readAttributes(lock, java.nio.file.attribute.BasicFileAttributes.class).fileKey());
|
||||
}
|
||||
} finally { owner.destroyForcibly(); }
|
||||
}
|
||||
@Test void trackedDiscoveryTargetIsRejectedWithoutWritingCredentials() throws Exception {
|
||||
var directory = ProjectConnectionFiles.directory(root);
|
||||
var target = directory.resolve("connection.json"); Files.writeString(target, "tracked placeholder");
|
||||
for (var command : java.util.List.of(java.util.List.of("git", "init", "-q"), java.util.List.of("git", "add", "-f", ProjectConnectionFiles.RELATIVE))) {
|
||||
var process = new ProcessBuilder(command).directory(root.toFile()).redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
assertTrue(process.waitFor(5, java.util.concurrent.TimeUnit.SECONDS)); assertEquals(0, process.exitValue());
|
||||
}
|
||||
assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root));
|
||||
assertEquals("tracked placeholder", Files.readString(target));
|
||||
assertFalse(Files.exists(directory.resolve("publication.lock")));
|
||||
}
|
||||
|
||||
private Process ownerProcess() throws Exception {
|
||||
return new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin/java").toString(), "-cp",
|
||||
System.getProperty("studio.test.classpath"), Owner.class.getName(), root.toString())
|
||||
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
}
|
||||
public static class Owner {
|
||||
public static void main(String[] args) throws Exception {
|
||||
var mapper = new ObjectMapper();
|
||||
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of()))) {
|
||||
server.start();
|
||||
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(Path.of(args[0]))) {
|
||||
publication.publish(); publication.activate(); System.out.println("READY"); System.out.flush(); System.in.read();
|
||||
} catch (Exception conflict) { System.exit(2); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
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 java.nio.file.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class StudioAgentPreparationTest {
|
||||
@TempDir Path temporary;
|
||||
@Test void preservesUnrelatedTomlAndRejectsUserOwnedOrEditedEntry() throws Exception {
|
||||
var preparation = new StudioAgentPreparation(temporary.resolve("Application Support/Studio"), new ObjectMapper());
|
||||
String entry = preparation.entry(temporary.toRealPath());
|
||||
String custom = "# keep exactly\napproval_policy = \"on-request\"\n[mcp_servers.custom]\ncommand = \"custom\"\n";
|
||||
String merged = StudioAgentPreparation.merge(custom, entry);
|
||||
assertTrue(merged.startsWith(custom)); assertEquals(merged, StudioAgentPreparation.merge(merged, entry));
|
||||
assertFalse(merged.contains("credential")); assertFalse(merged.contains("connection.json"));
|
||||
assertThrows(Exception.class, () -> StudioAgentPreparation.merge("[mcp_servers.prometeu_studio]\ncommand=\"mine\"\n", entry));
|
||||
assertThrows(Exception.class, () -> StudioAgentPreparation.merge(merged.replace("startup_timeout_sec = 20", "startup_timeout_sec = 30"), entry));
|
||||
String updated = StudioAgentPreparation.merge(merged, preparation.entry(temporary.resolve("another project")));
|
||||
assertTrue(updated.startsWith(custom)); assertTrue(updated.contains("another project"));
|
||||
}
|
||||
@Test void absentInstallationReportsIncompleteAndDoesNotModifyClientConfig() throws Exception {
|
||||
Files.writeString(temporary.resolve("prometeu.json"), "{}");
|
||||
Files.createDirectory(temporary.resolve(".codex"));
|
||||
Path config = temporary.resolve(".codex/config.toml"); Files.writeString(config, "# preserve\n");
|
||||
var preparation = new StudioAgentPreparation(temporary.resolve("missing"), new ObjectMapper());
|
||||
var result = preparation.prepare(temporary);
|
||||
assertFalse(result.ready()); assertEquals("# preserve\n", Files.readString(config));
|
||||
assertTrue(result.message().contains("Studio installation is missing"));
|
||||
assertTrue(result.message().contains(":prometeu-app:stageStudioInstallation"));
|
||||
assertTrue(result.message().contains("-Dstudio.installationRoot"));
|
||||
assertFalse(Files.exists(temporary.resolve(".studio/mcp")));
|
||||
assertEquals(result, preparation.status(temporary.toRealPath()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package p.studio.app.mcp.stdio;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.app.mcp.*;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class StudioMcpStdioTest {
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
Path root;
|
||||
@BeforeEach void project() throws Exception { root = temporary.toRealPath(); Files.writeString(root.resolve("prometeu.json"), "{}"); }
|
||||
LocalMcpServer server(AtomicInteger calls, String image) {
|
||||
return new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of("studio_project_context", args -> {
|
||||
calls.incrementAndGet();
|
||||
return McpToolResult.successWithCapture(mapper, mapper.createObjectNode().put("projectRoot", args.path("projectRoot").asText()),
|
||||
new p.studio.api.automation.CanonicalCapture("session", "build", 1, 1, 1, 1, 1, Base64.getDecoder().decode(image)), false);
|
||||
})));
|
||||
}
|
||||
@Test void coldProcessDiscoversLaterGrantPreservesLargeImagesAndSurvivesRestart() throws Exception {
|
||||
var count = new AtomicInteger(); String pixels = "A".repeat(1024 * 1024 + 100);
|
||||
try (var process = new Connector(root); var server = server(count, pixels)) {
|
||||
process.initialize();
|
||||
assertEquals(17, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size());
|
||||
var waiting = process.call("studio_project_context", root);
|
||||
assertEquals("WAITING_FOR_ACCESS", waiting.path("structuredContent").path("error").path("code").asText());
|
||||
assertFalse(Files.exists(root.resolve(".studio")));
|
||||
server.start();
|
||||
var publisher = new ProjectConnectionPublisher(server, mapper);
|
||||
try (var publication = publisher.prepare(root)) {
|
||||
publication.publish(); publication.activate();
|
||||
var result = process.call("studio_project_context", root);
|
||||
assertFalse(result.path("isError").asBoolean(), result.path("structuredContent").toString());
|
||||
assertEquals(pixels, result.path("content").get(1).path("data").asText());
|
||||
assertEquals(root.toString(), result.path("structuredContent").path("value").path("projectRoot").asText());
|
||||
Path other = Files.createDirectory(root.resolve("other"));
|
||||
assertEquals("OUTSIDE_PROJECT_SCOPE", process.call("studio_project_context", other).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(1, count.get());
|
||||
}
|
||||
server.close(); server.start();
|
||||
assertEquals("WAITING_FOR_ACCESS", process.call("studio_project_context", root).path("structuredContent").path("error").path("code").asText());
|
||||
try (var fresh = publisher.prepare(root)) {
|
||||
fresh.publish(); fresh.activate();
|
||||
assertFalse(process.call("studio_project_context", root).path("isError").asBoolean());
|
||||
assertEquals(2, count.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test void invalidArgumentsAndMalformedLinesDoNotLaunchDesktopOrBreakCorrelation() throws Exception {
|
||||
try (var connector = new Connector(root)) {
|
||||
connector.send("{bad json}");
|
||||
assertEquals(-32700, connector.read().path("error").path("code").asInt());
|
||||
connector.initialize();
|
||||
assertEquals(-32601, connector.request("no-method", mapper.createObjectNode()).path("error").path("code").asInt());
|
||||
assertTrue(connector.request("ping", mapper.createObjectNode()).has("result"));
|
||||
}
|
||||
var process = new ProcessBuilder(java(), "-cp", classpath(), "p.studio.app.StudioLauncher", "mcp", "--project", "relative")
|
||||
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
assertTrue(process.waitFor(10, TimeUnit.SECONDS)); assertNotEquals(0, process.exitValue());
|
||||
assertEquals(0, process.getInputStream().readAllBytes().length);
|
||||
}
|
||||
@Test void lostBuildResponseIsNotReplayedAndReceiptCanBeLookedUpAfterReconnect() throws Exception {
|
||||
var builds = new AtomicInteger(); var mapper = this.mapper;
|
||||
var handlers = Map.<String, java.util.function.Function<JsonNode, McpToolResult>>of(
|
||||
"studio_build_start", args -> { builds.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1")); },
|
||||
"studio_operation_get", args -> McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1")));
|
||||
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers));
|
||||
var transport = java.net.http.HttpClient.newHttpClient()) {
|
||||
server.start();
|
||||
var proxy = com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
|
||||
var dropped = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
proxy.createContext("/mcp", exchange -> {
|
||||
try (exchange) {
|
||||
var bytes = exchange.getRequestBody().readAllBytes();
|
||||
var incoming = mapper.readTree(bytes);
|
||||
var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint());
|
||||
for (String header : List.of("Authorization", "Content-Type", "Accept", "Mcp-Session-Id", "MCP-Protocol-Version")) {
|
||||
String value = exchange.getRequestHeaders().getFirst(header); if (value != null) request.header(header, value);
|
||||
}
|
||||
var response = transport.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofByteArray(bytes)).build(), java.net.http.HttpResponse.BodyHandlers.ofByteArray());
|
||||
if (incoming.path("params").path("name").asText().equals("studio_build_start") && dropped.compareAndSet(false, true)) {
|
||||
exchange.sendResponseHeaders(200, 100); return; // Committed tool, intentionally incomplete transport response.
|
||||
}
|
||||
response.headers().firstValue("Mcp-Session-Id").ifPresent(value -> exchange.getResponseHeaders().set("Mcp-Session-Id", value));
|
||||
exchange.sendResponseHeaders(response.statusCode(), response.body().length == 0 ? -1 : response.body().length);
|
||||
exchange.getResponseBody().write(response.body());
|
||||
} catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); }
|
||||
});
|
||||
proxy.start();
|
||||
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root);
|
||||
var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
|
||||
publication.publish(); publication.activate();
|
||||
var path = root.resolve(ProjectConnectionFiles.RELATIVE);
|
||||
var descriptor = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(Files.readString(path));
|
||||
descriptor.put("endpoint", "http://127.0.0.1:" + proxy.getAddress().getPort() + "/mcp"); Files.writeString(path, descriptor.toString());
|
||||
var args = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", "task").put("clientRequestId", "intent-1");
|
||||
var unknown = connection.call("studio_build_start", args);
|
||||
assertEquals("OUTCOME_UNKNOWN", unknown.path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals("intent-1", unknown.path("structuredContent").path("error").path("clientRequestId").asText());
|
||||
connection.probe(); assertEquals(1, builds.get());
|
||||
var recovered = connection.call("studio_operation_get", args);
|
||||
assertEquals("op-1", recovered.path("structuredContent").path("value").path("operationId").asText());
|
||||
assertEquals(1, builds.get());
|
||||
} finally { proxy.stop(0); }
|
||||
}
|
||||
}
|
||||
|
||||
@Test void restartedInstanceCannotClaimRecoveryOfOldTaskReceipts() throws Exception {
|
||||
var calls = new AtomicInteger();
|
||||
var handlers = Map.<String, java.util.function.Function<JsonNode, McpToolResult>>of(
|
||||
"studio_control_acquire", args -> McpToolResult.success(mapper, mapper.createObjectNode().put("taskId", UUID.randomUUID().toString())),
|
||||
"studio_operation_get", args -> { calls.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "fresh")); });
|
||||
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers));
|
||||
var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
|
||||
server.start(); var publisher = new ProjectConnectionPublisher(server, mapper);
|
||||
String task;
|
||||
try (var publication = publisher.prepare(root)) {
|
||||
publication.publish(); publication.activate();
|
||||
task = connection.call("studio_control_acquire", mapper.createObjectNode().put("projectRoot", root.toString()))
|
||||
.path("structuredContent").path("value").path("taskId").asText();
|
||||
}
|
||||
server.close(); server.start();
|
||||
try (var publication = publisher.prepare(root)) {
|
||||
publication.publish(); publication.activate();
|
||||
var old = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", task).put("clientRequestId", "old");
|
||||
assertEquals("OUTCOME_UNKNOWN", connection.call("studio_operation_get", old).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(0, calls.get());
|
||||
String fresh = connection.call("studio_control_acquire", mapper.createObjectNode().put("projectRoot", root.toString()))
|
||||
.path("structuredContent").path("value").path("taskId").asText();
|
||||
old.put("taskId", fresh);
|
||||
assertFalse(connection.call("studio_operation_get", old).path("isError").asBoolean()); assertEquals(1, calls.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void staleIdentityAndCatalogMismatchAreRejectedBeforeToolDispatch() throws Exception {
|
||||
var calls = new AtomicInteger();
|
||||
try (var server = server(calls, "AAAA")) {
|
||||
server.start();
|
||||
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root)) {
|
||||
publication.publish(); publication.activate();
|
||||
Path path = root.resolve(ProjectConnectionFiles.RELATIVE);
|
||||
String valid = Files.readString(path);
|
||||
try {
|
||||
for (String field : List.of("instanceId", "catalogFingerprint")) {
|
||||
var invalid = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(valid); invalid.put(field, "outdated");
|
||||
Files.writeString(path, invalid.toString());
|
||||
try (var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
|
||||
var result = connection.call("studio_project_context", mapper.createObjectNode().put("projectRoot", root.toString()));
|
||||
assertEquals(field.equals("instanceId") ? "STALE_CONNECTION" : "VERSION_INCOMPATIBLE",
|
||||
result.path("structuredContent").path("error").path("code").asText());
|
||||
}
|
||||
}
|
||||
assertEquals(0, calls.get());
|
||||
} finally { Files.writeString(path, valid); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String java() { return Path.of(System.getProperty("java.home"), "bin/java").toString(); }
|
||||
static String classpath() { return System.getProperty("studio.test.classpath"); }
|
||||
final class Connector implements AutoCloseable {
|
||||
final Process process;
|
||||
final BufferedReader reader;
|
||||
final BufferedWriter writer;
|
||||
final ExecutorService reads = Executors.newSingleThreadExecutor();
|
||||
final Path errors;
|
||||
int sequence;
|
||||
Connector(Path project) throws Exception {
|
||||
errors = Files.createTempFile(temporary, "stdio-", ".stderr");
|
||||
process = new ProcessBuilder(java(), "-cp", classpath(), "p.studio.app.StudioLauncher", "mcp", "--project", project.toString())
|
||||
.directory(temporary.toFile()).redirectError(errors.toFile()).start();
|
||||
reader = process.inputReader(); writer = process.outputWriter();
|
||||
}
|
||||
void send(String value) throws Exception { writer.write(value); writer.newLine(); writer.flush(); }
|
||||
JsonNode read() throws Exception {
|
||||
String line = reads.submit(reader::readLine).get(15, TimeUnit.SECONDS);
|
||||
assertNotNull(line, Files.readString(errors)); return mapper.readTree(line);
|
||||
}
|
||||
JsonNode request(String method, JsonNode params) throws Exception {
|
||||
var value = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", ++sequence).put("method", method); value.set("params", params);
|
||||
send(value.toString()); var response = read(); assertEquals(sequence, response.path("id").asInt()); return response;
|
||||
}
|
||||
void initialize() throws Exception {
|
||||
var params = mapper.createObjectNode().put("protocolVersion", "2025-06-18"); params.putObject("capabilities"); params.putObject("clientInfo").put("name", "process-test").put("version", "1");
|
||||
assertEquals("2025-06-18", request("initialize", params).path("result").path("protocolVersion").asText());
|
||||
send("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}");
|
||||
}
|
||||
JsonNode call(String name, Path root) throws Exception {
|
||||
var params = mapper.createObjectNode().put("name", name); params.putObject("arguments").put("projectRoot", root.toString());
|
||||
return request("tools/call", params).path("result");
|
||||
}
|
||||
public void close() throws Exception {
|
||||
try { writer.close(); assertTrue(process.waitFor(10, TimeUnit.SECONDS), "EOF must terminate the connector"); assertEquals(0, process.exitValue(), Files.readString(errors)); }
|
||||
finally { process.destroyForcibly(); reads.shutdownNow(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ class HeadlessMcpDesktopTest {
|
||||
LocalMcpServer server;
|
||||
HttpClient client;
|
||||
String connection, task, build, session;
|
||||
String authorization = "Bearer unavailable";
|
||||
Path installation, source;
|
||||
DevWorkspace dev;
|
||||
Stage stage;
|
||||
@@ -76,9 +77,9 @@ class HeadlessMcpDesktopTest {
|
||||
stage = new Stage(); stage.setTitle("Real MCP / headless / DEV conformance");
|
||||
stage.setScene(new Scene((javafx.scene.Parent) dev.rootNode(), 1000, 800)); stage.show(); dev.load();
|
||||
});
|
||||
connect();
|
||||
}
|
||||
void connect() throws Exception {
|
||||
authorization = "Bearer " + p.studio.app.mcp.ProjectConnectionFiles.read(root, mapper).credential();
|
||||
connection = null;
|
||||
var initialize = request("initialize");
|
||||
var params = initialize.putObject("params").put("protocolVersion", "2025-06-18");
|
||||
@@ -96,8 +97,15 @@ class HeadlessMcpDesktopTest {
|
||||
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive), "No managed runtime may survive the test");
|
||||
}
|
||||
|
||||
void acquire() throws Exception {
|
||||
void grant() throws Exception {
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
while (project.automation().snapshot().state() != ControlState.WAITING_FOR_AGENT && System.nanoTime() < deadline) Thread.sleep(10);
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, project.automation().snapshot().state());
|
||||
connect();
|
||||
}
|
||||
void acquire() throws Exception {
|
||||
grant();
|
||||
task = value(call("studio_control_acquire", args())).path("taskId").asText();
|
||||
}
|
||||
void prepareLongRun() throws Exception {
|
||||
@@ -121,7 +129,7 @@ class HeadlessMcpDesktopTest {
|
||||
prepareLongRun();
|
||||
var receipt = startRunning("cancel-me");
|
||||
var delete = HttpRequest.newBuilder(server.connection().endpoint()).DELETE()
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", connection).build();
|
||||
.header("Authorization", authorization).header("Mcp-Session-Id", connection).build();
|
||||
assertEquals(200, client.send(delete, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
client.close(); client = HttpClient.newHttpClient(); connect();
|
||||
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state());
|
||||
@@ -159,7 +167,7 @@ class HeadlessMcpDesktopTest {
|
||||
refreshEntered.get(10, TimeUnit.SECONDS);
|
||||
assertEquals(ControlState.RETURNING_CONTROL, project.automation().snapshot().state());
|
||||
assertFalse(project.automation().snapshot().manualAllowed());
|
||||
assertEquals("INVALID_TASK", call("studio_operation_get", args().put("clientRequestId", "revoked")).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
assertSame(lastCapture, project.automation().snapshot().capture(), "Revoked work must not publish a late frame");
|
||||
refreshGate.complete(null);
|
||||
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
|
||||
@@ -169,19 +177,19 @@ class HeadlessMcpDesktopTest {
|
||||
}
|
||||
|
||||
@Test void waitingRevokeProjectCloseAndReopenNeverRestoreAuthority() throws Exception {
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
|
||||
grant();
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-reclaim")).fire());
|
||||
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
|
||||
assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
prepareLongRun(); startRunning("close-project");
|
||||
fx(dev::unLoad);
|
||||
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state(), "DEV does not own task lifetime");
|
||||
project.close();
|
||||
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive));
|
||||
assertEquals("PROJECT_NOT_OPEN", call("studio_operation_get", args().put("clientRequestId", "close-project")).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
project = app.getBean(ProjectSessionFactory.class).open(project.projectReference());
|
||||
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
|
||||
assertEquals("INVALID_TASK", call("studio_build_start", args().put("clientRequestId", "late")).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
}
|
||||
|
||||
@Test void applicationContextShutdownClosesActiveProjectAndRuntime() throws Exception {
|
||||
@@ -270,13 +278,13 @@ class HeadlessMcpDesktopTest {
|
||||
}
|
||||
|
||||
@Test void fullHttpLoopMatchesRawRuntimePixelsAndDisplayedDevAcrossResetAndRebuild() throws Exception {
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
grant();
|
||||
assertEquals(17, mapper.readTree(post(request("tools/list")).body()).path("result").path("tools").size());
|
||||
assertTrue(value(call("studio_project_context", args())).path("languages").toString().contains("pbs"));
|
||||
value(call("studio_reference_read", args().put("referenceId", "pbs:quickstart").put("limit", 100)));
|
||||
var sdk = value(call("studio_reference_read", args().put("referenceId", "pbs:sdk:game:1:sdk/input/main.pbs").put("limit", 1000)));
|
||||
assertTrue(sdk.toString().contains("InputPad"), "Consult installed SDK source through the indexed read-only reference");
|
||||
assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText());
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, project.automation().snapshot().state());
|
||||
task = value(call("studio_control_acquire", args())).path("taskId").asText();
|
||||
assertFalse(task.isBlank());
|
||||
@@ -442,7 +450,7 @@ class HeadlessMcpDesktopTest {
|
||||
}
|
||||
HttpResponse<String> post(JsonNode body) throws Exception {
|
||||
var request = HttpRequest.newBuilder(server.connection().endpoint()).timeout(Duration.ofSeconds(15))
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json")
|
||||
.header("Authorization", authorization).header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18");
|
||||
if (connection != null) request.header("Mcp-Session-Id", connection);
|
||||
return client.send(request.POST(HttpRequest.BodyPublishers.ofString(body.toString())).build(), HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
Reference in New Issue
Block a user