feat(studio): integrate project MCP setup and lifecycle
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user