From 4b64c3edd0d4db259e536d0d80ad2fb1c9819e98 Mon Sep 17 00:00:00 2001 From: VotingPlugin Control Automation Date: Thu, 19 Nov 2026 00:19:18 +0000 Subject: [PATCH] Add browser-approved MCP setup to VotingPlugin Control --- README.md | 1 + docs/agent-setup.md | 48 +++ docs/control-management.md | 8 + .../control/ControlApplication.java | 5 +- .../control/domain/AgentOperations.java | 219 +++++++++++++ .../control/domain/AgentSetup.java | 86 +++++ .../domain/ConfigurationOperations.java | 169 +++++++++- .../control/http/ControlHttpServer.java | 122 ++++++- .../control/mcp/StdioAdapter.java | 307 ++++++++++++++++++ src/main/resources/web/app.js | 135 ++++++++ src/main/resources/web/index.html | 24 ++ .../control/domain/AgentOperationsTest.java | 65 ++++ .../control/http/AgentMcpHttpTest.java | 206 ++++++++++++ 13 files changed, 1378 insertions(+), 17 deletions(-) create mode 100644 docs/agent-setup.md create mode 100644 src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java create mode 100644 src/main/java/com/bencodez/votingplugin/control/domain/AgentSetup.java create mode 100644 src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java create mode 100644 src/test/java/com/bencodez/votingplugin/control/domain/AgentOperationsTest.java create mode 100644 src/test/java/com/bencodez/votingplugin/control/http/AgentMcpHttpTest.java diff --git a/README.md b/README.md index 4d3bfff..b7ee3ff 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ VotingPlugin Control is designed to manage and troubleshoot a VotingPlugin netwo - Run guided setup for standalone and proxy/backend networks. - Configure common settings through searchable presets. +- Let Codex CLI or Claude Code read and preview a named backend vote site through local MCP, then review and apply it in Control. See [agent setup](docs/agent-setup.md). - Set up or synchronize Vote Sites while preserving existing rewards and sensitive values. - Configure automatic Vote Site creation. - Configure VoteLogging and retention. diff --git a/docs/agent-setup.md b/docs/agent-setup.md new file mode 100644 index 0000000..2816481 --- /dev/null +++ b/docs/agent-setup.md @@ -0,0 +1,48 @@ +# Configure a vote site with an MCP agent + +VotingPlugin Control can provide a local stdio MCP connection to Codex CLI and Claude Code. The agent can discover authorized enrolled nodes, read one named vote site on a Bukkit backend, preview a change and track the result. The owner reviews and applies the preview in Control. The backend uses existing managed-file and quick-setup capabilities over the current task protocol. + +## Connect a client + +1. Install VotingPlugin and enroll the backend as an administrator. Check that Control reports the backend online with both accepted capabilities, `config.files.v1` and `config.quick-setup.v1`. +2. Open **Access → Agent access** in Control. Enter the exact node IDs and choose the actions and lifetime. Issue the credential and copy it when displayed. Control keeps only its verifier in memory. Grants expire after the chosen lifetime (up to 24 hours), can be revoked immediately, and are invalidated when Control restarts. Revocation prevents new requests and prevents approval of pending previews. A write the owner already approved can still complete. +3. Supply `VP_CONTROL_MCP_ORIGIN` and `VP_CONTROL_MCP_TOKEN` in the local client environment. Use a verified HTTPS origin or literal loopback HTTP such as `http://127.0.0.1:8080`. Use the actual Control port. Keep the token out of tool arguments, command-line arguments, agent prompts and checked-in files. +4. Configure the client to launch the Control all-in-one JAR with its `mcp` subcommand. Use an absolute path to the JAR. + +### Codex CLI + +Add the following to your local Codex configuration: + +```toml +[mcp_servers.votingplugin-control] +command = "java" +args = ["-jar", "/absolute/path/votingplugin-control-all.jar", "mcp"] +env_vars = ["VP_CONTROL_MCP_ORIGIN", "VP_CONTROL_MCP_TOKEN"] +``` + +Verify that the server is configured with `codex mcp list`. [Codex MCP configuration](https://learn.chatgpt.com/docs/extend/mcp?surface=cli) + +### Claude Code + +Launch Claude Code with the two environment variables available to the process. Register the stdio command in local scope: + +```sh +claude mcp add --transport stdio --scope local votingplugin-control -- java -jar /absolute/path/votingplugin-control-all.jar mcp +``` + +Use `/mcp` to check the connection. [Claude Code MCP configuration](https://code.claude.com/docs/en/mcp) + +## Review and apply + +Ask the agent to choose an authorized node, read the exact site name and prepare a preview. The agent returns a review path on the configured Control origin. You can also open **Activity → Review agent preview**. The review lists the agent grant, target, changed configuration paths and effective proposed values. Control reads the redacted main `VoteSites.yml` through its managed-file service and extracts only the named site's typed values. It discards the full document after extraction. The review shows the preset's proposed display item amount of one and the prior value when present. Control blocks approval if the file has an ambiguous structure or the node's changed paths do not match the revision-bound typed diff. Split VoteSites files are outside this setup flow. The URL must use HTTP(S) and omit userinfo, query and fragment. Only put public vote-site information in the guided fields. + +Approve in the browser to queue the exact preview. The agent can poll the preview operation for the resulting apply ID and then track the apply. A changed file revision, changed session, lost capability, expired grant or incomplete diff requires a new eligible preview. The MCP server exposes four tools: + +| Tool | Arguments | +|---|---| +| `list_nodes` | Empty object. Returns up to the 50 nodes on the grant. | +| `read_setup` | `nodeId`, `name`. | +| `preview_setup` | `nodeId`, `readOperationId`, `options`. Options require `name`, `serviceSite` and `voteUrl` and may include `enabled`, `displayName`, `priority`, `hidden`, `voteDelay` and `material`. | +| `get_operation` | `operationId`. Only operations from the current grant are visible. | + +The adapter can prepare work for a single enrolled backend per operation. Deployment, enrollment, restarts and raw file editing use their existing administrator workflows. diff --git a/docs/control-management.md b/docs/control-management.md index fdbbca2..cf147ee 100644 --- a/docs/control-management.md +++ b/docs/control-management.md @@ -60,6 +60,14 @@ Do not infer support from plugin version strings. Check `acceptedCapabilities` f Deploy the paired VotingPlugin connector change before enabling Control features that require a new capability. During a mixed-version rollout, older nodes remain connected but are excluded from v2 HTTP previews and applies. +## Local agent setup + +The packaged stdio MCP adapter calls Control's scoped agent API. The browser owner issues and revokes +short-lived grants. Each grant authorizes only exact node IDs and discovery, read, preview or status actions. +Agent previews bind a successful named-site projection from the redacted managed VoteSites.yml read to the same node session and file revision. Control's +browser-only approval route uses the normal configuration operation engine without returning its approval token. +Existing node capability negotiation and the node task protocol are unchanged. See [agent setup](agent-setup.md). + ## WebUI feature map The dependency-free WebUI is an API client, not a privileged implementation path. Every write below still uses the same diff --git a/src/main/java/com/bencodez/votingplugin/control/ControlApplication.java b/src/main/java/com/bencodez/votingplugin/control/ControlApplication.java index 0726aed..de0aca8 100644 --- a/src/main/java/com/bencodez/votingplugin/control/ControlApplication.java +++ b/src/main/java/com/bencodez/votingplugin/control/ControlApplication.java @@ -42,7 +42,10 @@ private ControlApplication() { } public static void main(String[] args) { try { - if (args.length > 0) { + if (args.length == 1 && "mcp".equals(args[0])) { + new com.bencodez.votingplugin.control.mcp.StdioAdapter(System.getenv("VP_CONTROL_MCP_ORIGIN"), + System.getenv("VP_CONTROL_MCP_TOKEN")).run(System.in, System.out); + } else if (args.length > 0) { runOwnerCommand(args); } else { runServer(System.getenv()); diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java b/src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java new file mode 100644 index 0000000..79c5152 --- /dev/null +++ b/src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java @@ -0,0 +1,219 @@ +package com.bencodez.votingplugin.control.domain; + +import com.bencodez.votingplugin.control.protocol.ManagedConfiguration; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Base64; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +public final class AgentOperations { + private static final Set ACTIONS = Set.of("discover", "read", "preview", "status"); + private final Map grants = new HashMap<>(); + private final NodeRegistry registry; + private final ConfigurationOperations operations; + private final Clock clock; + private final SecureRandom random = new SecureRandom(); + + public AgentOperations(NodeRegistry registry, ConfigurationOperations operations, Clock clock) { + this.registry = registry; + this.operations = operations; + this.clock = clock; + } + + public synchronized Issued issue(Issue request) { + grants.values().removeIf(grant -> !clock.instant().isBefore(grant.expiresAt())); + if (request == null || request.nodeIds() == null || request.nodeIds().isEmpty() + || request.nodeIds().size() > 50 || request.actions() == null || request.actions().isEmpty() + || request.actions().size() > ACTIONS.size() || request.actions().stream().anyMatch(action -> action == null || !ACTIONS.contains(action)) || request.minutes() == null || request.minutes() < 1 + || request.minutes() > 1440 || grants.size() >= 64) throw invalid("Invalid agent grant or grant limit reached"); + request.nodeIds().forEach(AgentOperations::validateNodeId); + UUID id = UUID.randomUUID(); + byte[] secret = new byte[32]; + random.nextBytes(secret); + String token = "vp-agent-" + id + "." + Base64.getUrlEncoder().withoutPadding().encodeToString(secret); + Instant expiry = clock.instant().plusSeconds(60L * request.minutes()); + operations.auditAgentGrant(id, "ISSUED"); + grants.put(id, new Grant(id, Set.copyOf(request.nodeIds()), Set.copyOf(request.actions()), expiry, digest(token))); + return new Issued(id, token, expiry); + } + + public synchronized List list() { + return grants.values().stream().filter(grant -> clock.instant().isBefore(grant.expiresAt())) + .map(grant -> new GrantView(grant.id(), grant.nodes(), grant.actions(), grant.expiresAt())).toList(); + } + + public synchronized void revoke(UUID id) { + operations.auditAgentGrant(id, "REVOKED"); + grants.remove(id); + } + + public synchronized void requireAccess(String token, String action) { + authorize(token, action); + } + + public synchronized Object discover(String token) { + Grant grant = authorize(token, "discover"); + return Map.of("items", grant.nodes().stream().sorted().map(registry::find) + .filter(java.util.Objects::nonNull) + .map(node -> Map.of("nodeId", node.nodeId(), "platform", node.platform(), "online", node.online(), + "acceptedCapabilities", node.acceptedCapabilities())).toList()); + } + + public synchronized Object read(String token, Read request) { + Grant grant = authorize(token, "read"); + requireNode(grant, request.nodeId()); + siteName(request.name()); + return project(operations.createAgentVoteSite(grant.id(), request.nodeId(), + configuration(Map.of("name", request.name())), null)); + } + + public synchronized Object preview(String token, Preview request) { + Grant grant = authorize(token, "preview"); + requireNode(grant, request.nodeId()); + if (request.readOperationId() == null || request.options() == null) throw invalid("Read and options are required"); + Site site = request.options(); + siteName(site.name()); + Map values = new LinkedHashMap<>(); + values.put("name", site.name()); + values.put("serviceSite", bounded(site.serviceSite(), 200)); + if (!AgentSetup.safeUrl(site.voteUrl())) throw invalid("Invalid vote URL"); + values.put("voteUrl", site.voteUrl()); + put(values, "displayName", site.displayName()); + put(values, "voteDelay", site.voteDelay()); + put(values, "material", site.material()); + if (site.enabled() != null) values.put("enabled", site.enabled().toString()); + if (site.hidden() != null) values.put("hidden", site.hidden().toString()); + if (site.priority() != null) { + if (site.priority() < 0 || site.priority() > 100) throw invalid("Invalid priority"); + values.put("priority", site.priority().toString()); + } + return project(operations.createAgentVoteSite(grant.id(), request.nodeId(), configuration(values), + parseId(request.readOperationId()))); + } + + public synchronized Object status(String token, UUID id) { + Grant grant = authorize(token, "status"); + var operation = operations.getAgentOperation(grant.id(), id); + var projected = project(operation); + if ("READ".equals(operation.type()) && "SUCCEEDED".equals(operation.state())) { + projected.put("values", operations.agentReadValues(grant.id(), id)); + } + if ("PREVIEW".equals(operation.type())) { + UUID applyId = operations.agentApplyId(grant.id(), id); + if (applyId != null) projected.put("applyOperationId", applyId); + } + return projected; + } + + public synchronized ConfigurationOperations.OperationView approve(UUID id) { + var preview = operations.get(id); + Grant grant = grants.get(preview.agentId()); + if (grant == null || !clock.instant().isBefore(grant.expiresAt())) throw invalid("Agent grant is unavailable"); + return operations.approveAgentPreview(id); + } + + private static Map project(ConfigurationOperations.OperationView operation) { + Map result = new LinkedHashMap<>(); + result.put("operationId", operation.operationId()); + result.put("type", operation.type()); + result.put("state", operation.state()); + result.put("nodes", operation.nodeStates()); + result.put("browserReviewReady", operation.browserReviewReady()); + if ("PREVIEW".equals(operation.type())) result.put("reviewPath", "/#agent-review/" + operation.operationId()); + Map results = new LinkedHashMap<>(); + operation.results().forEach((node, value) -> { + Map item = new LinkedHashMap<>(); + item.put("code", value.code()); + item.put("success", value.success()); + item.put("rolledBack", value.rolledBack()); + item.put("reloaded", value.reloaded()); + results.put(node, item); + }); + result.put("results", results); + return result; + } + + private Grant authorize(String token, String action) { + if (token == null || !token.matches("vp-agent-[0-9a-f-]{36}\\.[A-Za-z0-9_-]{43}")) return denied(); + UUID id; + try { + id = UUID.fromString(token.substring(9, 45)); + } catch (IllegalArgumentException e) { + return denied(); + } + Grant grant = grants.get(id); + if (grant == null || !clock.instant().isBefore(grant.expiresAt()) + || !MessageDigest.isEqual(grant.verifier(), digest(token)) || !grant.actions().contains(action)) { + return denied(); + } + return grant; + } + + private static Grant denied() { + throw new SecurityException("Agent access denied"); + } + + private static void requireNode(Grant grant, String id) { + validateNodeId(id); + if (!grant.nodes().contains(id)) denied(); + } + + public static UUID parseId(String id) { + if (id == null || !id.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + throw invalid("Invalid operation ID"); + } + return UUID.fromString(id); + } + + private static void validateNodeId(String id) { + if (id == null || !id.matches("[A-Za-z0-9][A-Za-z0-9._-]{0,63}")) throw invalid("Invalid node ID"); + } + + private static void siteName(String name) { + if (name == null || !name.matches("[A-Za-z0-9_-]{1,64}")) throw invalid("Invalid site name"); + } + + private static String bounded(String value, int max) { + if (value == null || value.isBlank() || value.length() > max + || value.codePoints().anyMatch(Character::isISOControl)) throw invalid("Invalid site option"); + return value; + } + + private static void put(Map values, String field, String value) { + if (value != null) values.put(field, bounded(value, 200)); + } + + private static ManagedConfiguration configuration(Map options) { + return new ManagedConfiguration("quick-setup", null, List.of(), null, null, "vote-site", options); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static byte[] digest(String token) { + try { + return MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.US_ASCII)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + public record Issue(List nodeIds, List actions, Integer minutes) { } + public record Issued(UUID id, String token, Instant expiresAt) { } + public record GrantView(UUID id, Set nodeIds, Set actions, Instant expiresAt) { } + public record Read(String nodeId, String name) { } + public record Preview(String nodeId, String readOperationId, Site options) { } + public record Site(String name, String serviceSite, String voteUrl, Boolean enabled, String displayName, + Integer priority, Boolean hidden, String voteDelay, String material) { } + private record Grant(UUID id, Set nodes, Set actions, Instant expiresAt, byte[] verifier) { } +} diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/AgentSetup.java b/src/main/java/com/bencodez/votingplugin/control/domain/AgentSetup.java new file mode 100644 index 0000000..d948ff3 --- /dev/null +++ b/src/main/java/com/bencodez/votingplugin/control/domain/AgentSetup.java @@ -0,0 +1,86 @@ +package com.bencodez.votingplugin.control.domain; + +import com.bencodez.votingplugin.control.protocol.ManagedConfiguration; +import java.net.URI; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.HashSet; + +final class AgentSetup { + private static final Map DEFAULTS = Map.of( + "enabled", "true", "priority", "5", "hidden", "false", "voteDelay", "24h", "material", "DIAMOND"); + private static final Map PATHS = Map.of( + "enabled", "Enabled", "displayName", "Name", "priority", "Priority", "hidden", "Hidden", + "serviceSite", "ServiceSite", "voteUrl", "VoteURL", "voteDelay", "VoteDelay", + "material", "DisplayItem.Material", "displayItem.amount", "DisplayItem.Amount"); + + private AgentSetup() { } + + static ManagedConfiguration proposal(Map current, ManagedConfiguration requested) { + Map values = new LinkedHashMap<>(DEFAULTS); + String name = requested.options().get("name"); + values.put("displayName", name); + if (current == null || !name.equals(current.get("name")) + || !List.of("true", "false").contains(current.getOrDefault("exists", ""))) { + throw new IllegalArgumentException("Read did not return the requested site"); + } + if ("true".equals(current.get("exists"))) { + for (String field : List.of("enabled", "priority", "hidden", "voteDelay", "material", "displayName")) { + String value = current.get(field); + if (value != null) values.put(field, value); + } + } + values.putAll(requested.options()); + if (!safeUrl(values.get("voteUrl"))) throw new IllegalArgumentException("Use a public-facing HTTP(S) vote URL without credentials, query or fragment"); + return new ManagedConfiguration("quick-setup", null, List.of(), null, null, "vote-site", values); + } + + static Map readSite(String name, ManagedConfiguration document) { + if (document == null || document.content() == null) throw new IllegalArgumentException("Missing VoteSites read"); + Map values = new LinkedHashMap<>(); + values.put("name", name); + var sites = VoteSitesDocument.inventory(document.content()).sites(); + var site = sites.stream().filter(item -> name.equalsIgnoreCase(item.key())).findFirst().orElse(null); + values.put("exists", Boolean.toString(site != null)); + if (site == null) return Map.copyOf(values); + if (!site.editable() || !name.equals(site.key())) throw new IllegalArgumentException("Ambiguous site name"); + PATHS.forEach((key, path) -> { + var field = site.fields().get(path); + if (field.status() == VoteSitesDocument.Status.UNSUPPORTED) { + throw new IllegalArgumentException("Site contains unsupported field"); + } + if (field.status() == VoteSitesDocument.Status.AVAILABLE) { + String value = field.value().toString(); + if ("voteUrl".equals(key) && !safeUrl(value)) { + throw new IllegalArgumentException("Existing site URL cannot be reviewed"); + } + values.put(key, value); + } + }); + return Map.copyOf(values); + } + + static boolean safeUrl(String value) { + if (value == null || value.length() > 500) return false; + try { + URI uri = URI.create(value); + return ("https".equalsIgnoreCase(uri.getScheme()) || "http".equalsIgnoreCase(uri.getScheme())) + && uri.getHost() != null && uri.getRawUserInfo() == null + && uri.getRawQuery() == null && uri.getRawFragment() == null; + } catch (IllegalArgumentException e) { + return false; + } + } + + static boolean reviewableChanges(ManagedConfiguration configuration, Map before, + List changes) { + String root = "changed VoteSites." + configuration.options().get("name") + "."; + var expected = new HashSet(); + PATHS.forEach((key, path) -> { + String next = "displayItem.amount".equals(key) ? "1" : configuration.options().get(key); + if (!next.equals(before.get(key))) expected.add(root + path); + }); + return changes.size() == expected.size() && expected.equals(new HashSet<>(changes)); + } +} diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java b/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java index 7d0af56..486f4bf 100644 --- a/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java +++ b/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java @@ -105,7 +105,98 @@ public synchronized OperationView createPreview(List nodeIds, ManagedCon Base64.getUrlEncoder().withoutPadding().encodeToString(token)); } + public synchronized void auditAgentGrant(UUID agent, String outcome) { + audit.append("AGENT_GRANT", agent, null, outcome); + } + + public synchronized OperationView createAgentVoteSite(UUID agent, String nodeId, + ManagedConfiguration configuration, UUID readId) { + prune(); + if (!"vote-site".equals(configuration.preset())) throw invalid("Unsupported agent preset"); + configuration.validateProposal(); + ValidatedTargets targets = validateTargets(List.of(nodeId), QUICK_SETUP_CAPABILITY); + if (!"BUKKIT".equalsIgnoreCase(targets.platforms().get(nodeId))) throw invalid("Agent setup requires a Bukkit node"); + validateConfigurationTargets(targets, configuration); + var retained = operations.values().stream().filter(op -> agent.equals(op.agent)).toList(); + if (retained.size() >= 48 || retained.stream().filter(op -> !op.complete()).count() >= 4) { + throw invalid("Agent operation limit reached"); + } + if (readId == null) { + var selector = ManagedConfiguration.file("VoteSites.yml", null); + ValidatedTargets readTargets = validateTargets(List.of(nodeId), FILE_CAPABILITY); + validateConfigurationTargets(readTargets, selector); + OperationView view = create("READ", readTargets, selector, null, Map.of(), agent); + operations.get(view.operationId()).agentSite = configuration.options().get("name"); + return view; + } + StoredOperation read = agentOperation(agent, readId); + ConfigurationTaskResult result = read.results.get(nodeId); + if (!"READ".equals(read.type) || result == null || !result.success() + || !Objects.equals(read.agentSite, configuration.options().get("name")) + || !Objects.equals(result.sessionId(), targets.sessions().get(nodeId))) { + throw invalid("A successful READ of this site in the current node session is required"); + } + ManagedConfiguration proposal = AgentSetup.proposal(read.agentBefore, configuration); + byte[] token = new byte[32]; + random.nextBytes(token); + OperationView preview = create("PREVIEW", targets, proposal, + Base64.getUrlEncoder().withoutPadding().encodeToString(token), + Map.of(nodeId, result.revision()), agent); + operations.get(preview.operationId()).agentBefore = read.agentBefore; + return preview; + } + + public synchronized AgentReview getAgentReview(UUID id) { + prune(); + StoredOperation operation = operations.get(id); + if (operation == null || operation.agent == null || !"PREVIEW".equals(operation.type)) { + throw new ValidationException("OPERATION_NOT_FOUND", "Agent preview was not found", List.of()); + } + return new AgentReview(view(operation), operation.agentBefore); + } + + public synchronized OperationView getAgentOperation(UUID agent, UUID id) { + prune(); + return view(agentOperation(agent, id)); + } + + synchronized Map agentReadValues(UUID agent, UUID id) { + StoredOperation operation = agentOperation(agent, id); + return "READ".equals(operation.type) ? operation.agentBefore : Map.of(); + } + + synchronized UUID agentApplyId(UUID agent, UUID previewId) { + return operations.values().stream().filter(op -> agent.equals(op.agent) && "APPLY".equals(op.type) + && previewId.equals(op.sourceOperationId)).map(op -> op.id).findFirst().orElse(null); + } + + private StoredOperation agentOperation(UUID agent, UUID id) { + StoredOperation operation = operations.get(id); + if (operation == null || !agent.equals(operation.agent)) { + throw new ValidationException("OPERATION_NOT_FOUND", "Operation was not found", List.of()); + } + return operation; + } + + public synchronized OperationView approveAgentPreview(UUID id) { + prune(); + StoredOperation preview = operations.get(id); + if (preview == null || !agentReviewReady(preview)) throw invalid("Preview is unavailable for browser approval"); + return createApply(id, preview.approvalToken, true); + } + + private boolean agentReviewReady(StoredOperation operation) { + return operation.agent != null && "PREVIEW".equals(operation.type) + && !operation.approvalUsed && operation.complete() + && operation.results.values().stream().allMatch(ConfigurationTaskResult::success) + && clock.instant().isBefore(operation.createdAt.plus(ACTIVE_RETENTION)); + } + public synchronized OperationView createApply(UUID previewId, String approvalToken) { + return createApply(previewId, approvalToken, false); + } + + private OperationView createApply(UUID previewId, String approvalToken, boolean browserAgentReview) { prune(); LinkedHashMap priorOperations = new LinkedHashMap<>(operations); long priorChanges = retainedChangeBytes; @@ -113,6 +204,7 @@ public synchronized OperationView createApply(UUID previewId, String approvalTok long priorFiles = retainedFileBytes; StoredOperation preview = operations.get(previewId); if (preview == null || !"PREVIEW".equals(preview.type)) throw invalid("preview operation was not found"); + if ((preview.agent != null) != browserAgentReview) throw invalid("Preview requires its original approval route"); if (!preview.complete() || preview.results.values().stream().anyMatch(result -> !result.success())) { throw new ValidationException("PREVIEW_INCOMPLETE", "Every node must pass preview before apply", List.of()); } @@ -133,9 +225,14 @@ public synchronized OperationView createApply(UUID previewId, String approvalTok boolean priorApprovalUsed = preview.approvalUsed; StoredOperation apply = store("APPLY", targets, preview.configuration, null, revisions, preview.id); + apply.agent = preview.agent; preview.approvalUsed = true; try { - audit.append("APPLY_APPROVED", apply.id, null, "QUEUED"); + if (browserAgentReview) { + audit.append("AGENT_APPLY_APPROVED", apply.id, targets.nodeIds().get(0), preview.id.toString()); + } else { + audit.append("APPLY_APPROVED", apply.id, null, "QUEUED"); + } persist(); } catch (RuntimeException e) { operations.clear(); @@ -343,7 +440,7 @@ public synchronized OperationView discardVoteSitesPreview(UUID id, String token) private OperationView discardVisualPreview(UUID id, String token, String source) { prune(); StoredOperation preview = operations.get(id); - if (preview == null || !"PREVIEW".equals(preview.type) || preview.expectedRevisions.isEmpty() + if (preview == null || preview.agent != null || !"PREVIEW".equals(preview.type) || preview.expectedRevisions.isEmpty() || token == null || token.length() > 128 || preview.approvalToken == null || !MessageDigest.isEqual(token.getBytes(java.nio.charset.StandardCharsets.UTF_8), preview.approvalToken.getBytes(java.nio.charset.StandardCharsets.UTF_8))) { @@ -382,7 +479,7 @@ public synchronized OperationView retry(UUID id) { prune(); StoredOperation original = operations.get(id); if (original == null) throw new ValidationException("OPERATION_NOT_FOUND", "Operation was not found", List.of()); - if (original.recovered) { + if (original.recovered || original.agent != null) { throw new ValidationException("RETRY_REQUIRES_INPUT", "Recovered operations are history only; start a fresh read or preview", List.of()); } @@ -451,7 +548,7 @@ private ConfigurationTask claimCurrentSession(String nodeId, NodeStatus node) { if ("QUEUED".equals(state) || ("IN_PROGRESS".equals(state) && leased != null && !now.isBefore(leased.plus(LEASE)))) { if (cancelChangedFileRole(operation, node)) continue; - if (cancelChangedBackendSetupRole(operation, node)) continue; + if (cancelChangedAgentTarget(operation, node) || cancelChangedBackendSetupRole(operation, node)) continue; if (cancelChangedProxyMethodRole(operation, node)) continue; if (deferProxyMethodApply(operation, node)) continue; if (cancelLostCapability(operation, node)) continue; @@ -589,6 +686,14 @@ private boolean cancelChangedFileRole(StoredOperation operation, NodeStatus node return true; } + private boolean cancelChangedAgentTarget(StoredOperation operation, NodeStatus node) { + if (operation.agent == null || ("BUKKIT".equalsIgnoreCase(node.platform()) + && Objects.equals(operation.targetSessions.get(node.nodeId()), node.sessionId()))) return false; + automaticCancellation(operation, node.nodeId(), node.sessionId(), "TARGET_CHANGED", + "Agent operation target reconnected or changed role", "TARGET_CHANGED"); + return true; + } + private boolean cancelChangedBackendSetupRole(StoredOperation operation, NodeStatus node) { if (!ManagedConfiguration.QUICK_SETUP.equals(operation.configuration.domain()) || !"proxy-backend".equals(operation.configuration.preset())) return false; @@ -778,7 +883,8 @@ private OperationView completeCurrentSession(UUID operationId, String nodeId, Co if (!Objects.equals(operation.claimSessions.get(nodeId), result.sessionId())) { throw new ValidationException("SESSION_MISMATCH", "Operation task belongs to another node session", List.of()); } - if (cancelChangedFileRole(operation, node) || cancelChangedBackendSetupRole(operation, node) + if (cancelChangedAgentTarget(operation, node) || cancelChangedFileRole(operation, node) + || cancelChangedBackendSetupRole(operation, node) || cancelChangedProxyMethodRole(operation, node) || cancelLostCapability(operation, node)) { return view(operation); @@ -791,6 +897,28 @@ private OperationView completeCurrentSession(UUID operationId, String nodeId, Co "Configuration changed since READ; read and preview again", null, (ManagedConfiguration) null, List.of(), false, false, result.attemptId()); } + if (operation.agent != null && "PREVIEW".equals(operation.type) && result.success() + && (result.changes().size() >= 20 || result.changes().contains("additional changes omitted") + || retainedChangeBytes + result.changes().stream().mapToLong( + change -> change.getBytes(StandardCharsets.UTF_8).length).sum() > MAX_RETAINED_CHANGE_BYTES + || !operation.configuration.equals(result.configuration()) + || !AgentSetup.reviewableChanges(operation.configuration, operation.agentBefore, result.changes()))) { + result = new ConfigurationTaskResult(result.sessionId(), false, "DIFF_UNAVAILABLE", + "Preview changes cannot be reviewed completely", null, (ManagedConfiguration) null, + List.of(), false, false, result.attemptId()); + } + Map agentRead = Map.of(); + if (operation.agent != null && "READ".equals(operation.type) && result.success()) { + try { + agentRead = AgentSetup.readSite(operation.agentSite, result.configuration()); + result = new ConfigurationTaskResult(result.sessionId(), true, "OK", "Named site read", + result.revision(), (ManagedConfiguration) null, List.of(), false, false, result.attemptId()); + } catch (IllegalArgumentException unreviewable) { + result = new ConfigurationTaskResult(result.sessionId(), false, "DIFF_UNAVAILABLE", + "VoteSites.yml or the named site cannot be represented safely", null, + (ManagedConfiguration) null, List.of(), false, false, result.attemptId()); + } + } String priorState = operation.states.get(nodeId); ConfigurationTaskResult priorResult = operation.results.get(nodeId); Instant priorLease = operation.leasedAt.get(nodeId); @@ -815,6 +943,7 @@ private OperationView completeCurrentSession(UUID operationId, String nodeId, Co operation.attemptIds.remove(nodeId); persist(); audit.append("TASK_COMPLETED", operation.id, nodeId, result.success() ? "SUCCESS" : result.code()); + if (!agentRead.isEmpty()) operation.agentBefore = agentRead; } catch (RuntimeException failure) { restoreTransition(operation, nodeId, priorState, priorResult, priorLease, priorAttempt, priorChanges, priorMessages, priorFiles, priorConfigurationGeneration, @@ -830,13 +959,20 @@ private OperationView create(String type, ValidatedTargets targets, ManagedConfi private OperationView create(String type, ValidatedTargets targets, ManagedConfiguration config, String token, Map revisions) { + return create(type, targets, config, token, revisions, null); + } + + private OperationView create(String type, ValidatedTargets targets, ManagedConfiguration config, String token, + Map revisions, UUID agent) { LinkedHashMap priorOperations = new LinkedHashMap<>(operations); long priorChanges = retainedChangeBytes; long priorMessages = retainedMessageBytes; long priorFiles = retainedFileBytes; StoredOperation operation = store(type, targets, config, token, revisions, null); try { - audit.append("OPERATION_CREATED", operation.id, null, type); + operation.agent = agent; + if (agent == null) audit.append("OPERATION_CREATED", operation.id, null, type); + else audit.append("AGENT_" + type + "_CREATED", operation.id, targets.nodeIds().get(0), agent.toString()); persist(); } catch (RuntimeException e) { operations.clear(); @@ -1062,7 +1198,7 @@ private OperationView view(StoredOperation operation, boolean includeRetainedCon ? "SUCCEEDED" : "COMPLETED_WITH_ERRORS") : "RUNNING"; String approval = "PREVIEW".equals(operation.type) && operation.complete() && operation.results.values().stream().allMatch(ConfigurationTaskResult::success) - && !operation.approvalUsed ? operation.approvalToken : null; + && !operation.approvalUsed && operation.agent == null ? operation.approvalToken : null; Map results = operation.results; if (!includeRetainedContent) { LinkedHashMap summaries = new LinkedHashMap<>(); @@ -1076,11 +1212,11 @@ private OperationView view(StoredOperation operation, boolean includeRetainedCon return new OperationView(operation.id, operation.type, state, operation.createdAt, operation.configuration == null ? null : operation.configuration.publicView(), Map.copyOf(operation.states), Map.copyOf(results), approval, operation.sourceOperationId, - operation.recovered, retryable(operation)); + operation.recovered, retryable(operation), operation.agent, agentReviewReady(operation)); } private static boolean retryable(StoredOperation operation) { - if (operation.recovered || !operation.complete() + if (operation.recovered || operation.agent != null || !operation.complete() || operation.results.values().stream().allMatch(ConfigurationTaskResult::success)) return false; if ("PREVIEW".equals(operation.type) && !operation.expectedRevisions.isEmpty()) return false; return !("APPLY".equals(operation.type) @@ -1206,7 +1342,17 @@ public void close() throws java.io.IOException { public record OperationView(UUID operationId, String type, String state, Instant createdAt, ManagedConfiguration configuration, Map nodeStates, Map results, String approvalToken, - UUID sourceOperationId, boolean recovered, boolean retryable) { } + UUID sourceOperationId, boolean recovered, boolean retryable, UUID agentId, boolean browserReviewReady) { + public OperationView(UUID operationId, String type, String state, Instant createdAt, + ManagedConfiguration configuration, Map nodeStates, + Map results, String approvalToken, + UUID sourceOperationId, boolean recovered, boolean retryable) { + this(operationId, type, state, createdAt, configuration, nodeStates, results, approvalToken, + sourceOperationId, recovered, retryable, null, false); + } + } + + public record AgentReview(OperationView operation, Map before) { } public record OperationListView(List items, Map voteLoggingRestartSessions, long configurationGeneration) { @@ -1235,6 +1381,9 @@ private static final class StoredOperation { private final UUID sourceOperationId; private final boolean recovered; private boolean approvalUsed; + private UUID agent; + private String agentSite; + private Map agentBefore = Map.of(); private StoredOperation(UUID id, String type, ManagedConfiguration configuration, String approvalToken, Instant createdAt, LinkedHashMap states, diff --git a/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java b/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java index e3b936f..286fdac 100644 --- a/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java +++ b/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java @@ -5,6 +5,7 @@ import com.bencodez.votingplugin.control.artifact.ArtifactStore; import com.bencodez.votingplugin.control.artifact.JenkinsVotingPluginSource; import com.bencodez.votingplugin.control.artifact.ArtifactStore.ArtifactException; +import com.bencodez.votingplugin.control.domain.AgentOperations; import com.bencodez.votingplugin.control.domain.NodeRegistry; import com.bencodez.votingplugin.control.domain.RegistrySnapshot; import com.bencodez.votingplugin.control.domain.ConfigurationOperations; @@ -112,6 +113,11 @@ public final class ControlHttpServer implements AutoCloseable { private static final int MAX_BACKENDS_PER_NODE_SUMMARY = 256; private static final long ARTIFACT_TRANSFER_TIMEOUT_SECONDS = 120; + private static final String AGENT_API = "/api/v1/agent/"; + private static final String AGENT_OWNER = "/api/v1/agent-admin/"; + private static final int AGENT_REQUEST_BYTES = 16 * 1024; + private final AgentOperations agentOperations; + private final ObjectMapper agentJson; private final HttpServer server; private final ObjectMapper json; private final NodeRegistry registry; @@ -254,6 +260,17 @@ public ControlHttpServer(InetSocketAddress address, NodeRegistry registry, Contr json.getFactory().setStreamReadConstraints(StreamReadConstraints.builder() .maxNestingDepth(20).maxStringLength(ManagedConfiguration.MAX_CONTENT + 4096) .maxNumberLength(64).build()); + agentOperations = new AgentOperations(registry, configurationOperations, clock); + agentJson = json.copy().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(com.fasterxml.jackson.databind.MapperFeature.ALLOW_COERCION_OF_SCALARS) + .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT); + agentJson.coercionConfigFor(com.fasterxml.jackson.databind.type.LogicalType.Textual) + .setCoercion(com.fasterxml.jackson.databind.cfg.CoercionInputShape.Integer, + com.fasterxml.jackson.databind.cfg.CoercionAction.Fail) + .setCoercion(com.fasterxml.jackson.databind.cfg.CoercionInputShape.Float, + com.fasterxml.jackson.databind.cfg.CoercionAction.Fail) + .setCoercion(com.fasterxml.jackson.databind.cfg.CoercionInputShape.Boolean, + com.fasterxml.jackson.databind.cfg.CoercionAction.Fail); authLimiter = new AuthFailureLimiter(nanoTime, MAX_AUTH_FAILURES_PER_MINUTE, TimeUnit.MINUTES.toNanos(1)); passwordFailureLimiter = new PasswordFailureLimiter(nanoTime, MAX_PASSWORD_FAILURES_PER_CLIENT, TimeUnit.MINUTES.toNanos(1), MAX_PASSWORD_FAILURE_CLIENTS); @@ -390,6 +407,10 @@ private void route(HttpExchange exchange) throws IOException { send(exchange, 200, health); return; } + if (path != null && (path.startsWith(AGENT_API) || path.startsWith(AGENT_OWNER))) { + routeAgent(exchange, path); + return; + } if (AUTH_SETUP.equals(path)) { if ("GET".equals(exchange.getRequestMethod())) { send(exchange, 200, Map.of("required", !credentials.hasWebPassword(), @@ -1027,9 +1048,93 @@ static BackendPage boundedNodePage(List nodes) { return new BackendPage(List.copyOf(items), returned, truncated, List.copyOf(truncatedNodeIds)); } + private void routeAgent(HttpExchange exchange, String path) throws IOException { + if (exchange.getRequestURI().getRawQuery() != null + || !path.equals(exchange.getRequestURI().getRawPath())) { + throw new IllegalArgumentException("Invalid agent route"); + } + if (path.startsWith(AGENT_OWNER)) { + switch (path.substring(AGENT_OWNER.length())) { + case "grants" -> { + requireMethod(exchange, "GET"); + authenticateWebSession(exchange, false); + send(exchange, 200, agentOperations.list()); + } + case "issue" -> { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + send(exchange, 201, agentOperations.issue(read(exchange, AgentOperations.Issue.class, true))); + } + case "revoke" -> { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + agentOperations.revoke(readAgentId(exchange)); + send(exchange, 200, Map.of("revoked", true)); + } + case "review" -> { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + send(exchange, 200, configurationOperations.getAgentReview(readAgentId(exchange))); + } + case "approve" -> { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + send(exchange, 202, agentOperations.approve(readAgentId(exchange))); + } + default -> error(exchange, 404, "NOT_FOUND", "Route not found", List.of()); + } + return; + } + requireMethod(exchange, "POST"); + String token = bearer(exchange); + String route = path.substring(AGENT_API.length()); + String action = switch (route) { + case "nodes" -> "discover"; + case "read", "preview", "status" -> route; + default -> null; + }; + if (action == null) { + error(exchange, 404, "NOT_FOUND", "Route not found", List.of()); + return; + } + try { + agentOperations.requireAccess(token, action); + Object result = switch (route) { + case "nodes" -> { + read(exchange, AgentEmpty.class, true); + yield agentOperations.discover(token); + } + case "read" -> agentOperations.read(token, read(exchange, AgentOperations.Read.class, true)); + case "preview" -> agentOperations.preview(token, read(exchange, AgentOperations.Preview.class, true)); + case "status" -> agentOperations.status(token, readAgentId(exchange)); + default -> throw new IllegalStateException("Unhandled agent route"); + }; + byte[] bytes = agentJson.writeValueAsBytes(result); + if (bytes.length > 32 * 1024) throw new IllegalArgumentException("Agent result exceeds limit"); + sendBytes(exchange, 200, "application/json; charset=utf-8", bytes); + } catch (SecurityException denied) { + authenticationFailed(); + } + } + + private UUID readAgentId(HttpExchange exchange) throws IOException { + AgentId request = read(exchange, AgentId.class, true); + return AgentOperations.parseId(request.operationId()); + } + + private record AgentEmpty() { } + private record AgentId(String operationId) { } + private T read(HttpExchange exchange, Class type) throws IOException { - String contentType = exchange.getRequestHeaders().getFirst("Content-Type"); - if (contentType == null || !contentType.toLowerCase(Locale.ROOT).startsWith("application/json")) { + return read(exchange, type, false); + } + + private T read(HttpExchange exchange, Class type, boolean agent) throws IOException { + int maximum = agent ? AGENT_REQUEST_BYTES : MAX_REQUEST_BYTES; + String contentType = agent ? singleHeader(exchange, "Content-Type") + : exchange.getRequestHeaders().getFirst("Content-Type"); + if (contentType == null || (agent ? !"application/json".equalsIgnoreCase(contentType.split(";", 2)[0].trim()) + : !contentType.toLowerCase(Locale.ROOT).startsWith("application/json"))) { throw new ValidationException("UNSUPPORTED_MEDIA_TYPE", "Content-Type must be application/json", List.of()); } List lengths = exchange.getRequestHeaders().get("Content-Length"); @@ -1046,8 +1151,8 @@ private T read(HttpExchange exchange, Class type) throws IOException { if (length < 0) { throw new IllegalArgumentException("Invalid Content-Length"); } - if (length > MAX_REQUEST_BYTES) { - throw new RequestTooLargeException(MAX_REQUEST_BYTES); + if (length > maximum) { + throw new RequestTooLargeException(maximum); } } byte[] bytes; @@ -1057,8 +1162,8 @@ private T read(HttpExchange exchange, Class type) throws IOException { int count; while ((count = input.read(buffer)) != -1) { total += count; - if (total > MAX_REQUEST_BYTES) { - throw new RequestTooLargeException(MAX_REQUEST_BYTES); + if (total > maximum) { + throw new RequestTooLargeException(maximum); } output.write(buffer, 0, count); } @@ -1067,6 +1172,11 @@ private T read(HttpExchange exchange, Class type) throws IOException { String text = StandardCharsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT) .decode(ByteBuffer.wrap(bytes)).toString(); + if (agent) { + T value = agentJson.readValue(text, type); + requireRequest(value); + return value; + } if (type == ConfigurationRequests.SettingsState.class || type == ConfigurationRequests.SettingsPreview.class || type == ConfigurationRequests.SettingsDiscard.class || type == ConfigurationRequests.VoteSitesState.class || type == ConfigurationRequests.VoteSitesPreview.class || type == ConfigurationRequests.VoteSitesDiscard.class diff --git a/src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java b/src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java new file mode 100644 index 0000000..6acec5f --- /dev/null +++ b/src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java @@ -0,0 +1,307 @@ +package com.bencodez.votingplugin.control.mcp; + +import com.fasterxml.jackson.core.StreamReadConstraints; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Flow; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public final class StdioAdapter { + private static final int MAX_REQUEST = 16 * 1024; + private static final int MAX_RESULT = 32 * 1024; + private static final List VERSIONS = List.of("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"); + private static final ObjectMapper JSON = JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).build(); + static { + JSON.getFactory().setStreamReadConstraints(StreamReadConstraints.builder() + .maxNestingDepth(16).maxStringLength(MAX_RESULT).maxNumberLength(64).build()); + } + private static final Map TOOLS = tools(); + + private final URI origin; + private final String token; + private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)) + .followRedirects(HttpClient.Redirect.NEVER).build(); + private String version; + private boolean ready; + + public StdioAdapter(String origin, String token) { + if (origin == null || token == null || !token.matches("vp-agent-[0-9a-f-]{36}\\.[A-Za-z0-9_-]{43}")) { + throw new IllegalArgumentException("Configure the Control origin and scoped credential"); + } + this.origin = URI.create(origin); + String host = this.origin.getHost(); + if (host == null || this.origin.getRawUserInfo() != null || this.origin.getRawQuery() != null + || this.origin.getRawFragment() != null || !Set.of("", "/").contains(this.origin.getRawPath()) + || !("https".equals(this.origin.getScheme()) || ("http".equals(this.origin.getScheme()) + && Set.of("127.0.0.1", "[::1]").contains(host)))) { + throw new IllegalArgumentException("Use an HTTPS Control origin or a literal loopback HTTP origin"); + } + this.token = token; + } + + public void run(InputStream source, OutputStream output) throws IOException, InterruptedException { + BufferedInputStream input = new BufferedInputStream(source); + byte[] line; + while ((line = readFrame(input)) != null) { + Object reply = dispatch(line); + if (reply == null) continue; + output.write(JSON.writeValueAsBytes(reply)); + output.write('\n'); + output.flush(); + } + } + + private Object dispatch(byte[] line) throws InterruptedException { + JsonNode request; + try { + request = JSON.readTree(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(line)).toString()); + } catch (IOException failure) { + return error(JSON.nullNode(), -32700, "Invalid JSON"); + } + JsonNode id = request == null ? JSON.nullNode() : request.path("id"); + if (request == null || !request.isObject() || !"2.0".equals(request.path("jsonrpc").asText()) + || !request.path("method").isTextual() + || !(id.isMissingNode() || id.isTextual() || id.isIntegralNumber())) { + return error(JSON.nullNode(), -32600, "Invalid request"); + } + String method = request.path("method").asText(); + if (id.isMissingNode()) { + if (version != null && "notifications/initialized".equals(method)) ready = true; + return null; + } + JsonNode params = request.path("params"); + return switch (method) { + case "initialize" -> initialize(id, params); + case "ping" -> reply(id, "result", Map.of()); + case "tools/list" -> ready ? reply(id, "result", Map.of("tools", + TOOLS.values().stream().map(Tool::descriptionJson).toList())) + : error(id, -32002, "Initialize MCP first"); + case "tools/call" -> ready ? call(id, params) : error(id, -32002, "Initialize MCP first"); + default -> error(id, -32601, "Method not found"); + }; + } + + private Object initialize(JsonNode id, JsonNode params) { + if (version != null || !params.path("protocolVersion").isTextual()) { + return error(id, -32602, "Invalid initialization"); + } + String requested = params.path("protocolVersion").asText(); + version = VERSIONS.contains(requested) ? requested : VERSIONS.get(0); + return reply(id, "result", Map.of( + "protocolVersion", version, + "capabilities", Map.of("tools", Map.of()), + "serverInfo", Map.of("name", "votingplugin-control", "version", "1.0.0"))); + } + + private Object call(JsonNode id, JsonNode params) throws InterruptedException { + Tool tool = TOOLS.get(params.path("name").asText()); + if (tool == null) return error(id, -32602, "Unknown tool"); + JsonNode arguments = params.has("arguments") ? params.get("arguments") : JSON.createObjectNode(); + if (!arguments.isObject()) return error(id, -32602, "Invalid arguments"); + try { + HttpRequest request = HttpRequest.newBuilder(origin.resolve("/api/v1/agent/" + tool.route())) + .timeout(Duration.ofSeconds(8)) + .header("Authorization", "Bearer " + token).header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofByteArray(JSON.writeValueAsBytes(arguments))).build(); + HttpResponse response = request(request); + if (response.statusCode() != 200) { + String code = JSON.readTree(response.body()).path("error").path("code").asText(""); + return toolError(id, "Control rejected the request (" + response.statusCode() + + (code.matches("[A-Z_]{1,48}") ? ", " + code : "") + ")."); + } + JsonNode result = JSON.readTree(response.body()); + if (!validResult(tool.route(), result)) return toolError(id, "Invalid Control response."); + Map body = new LinkedHashMap<>(); + body.put("content", List.of(Map.of("type", "text", "text", JSON.writeValueAsString(result)))); + if (version.compareTo("2025-06-18") >= 0) body.put("structuredContent", result); + return reply(id, "result", body); + } catch (IOException | RuntimeException failure) { + return toolError(id, "Control request failed. Check the configured origin and operation status."); + } + } + + private static boolean validResult(String route, JsonNode result) { + if ("nodes".equals(route)) { + JsonNode items = result.path("items"); + if (!fields(result, Set.of("items")) || !items.isArray() || items.size() > 50) return false; + for (JsonNode node : items) { + if (!fields(node, Set.of("nodeId", "platform", "online", "acceptedCapabilities")) + || !node.path("nodeId").asText().matches("[A-Za-z0-9][A-Za-z0-9._-]{0,63}") + || !node.path("nodeId").isTextual() || !node.path("platform").isTextual() + || !node.path("online").isBoolean() || !node.path("acceptedCapabilities").isArray()) { + return false; + } + for (JsonNode capability : node.path("acceptedCapabilities")) { + if (!capability.isTextual()) return false; + } + } + return true; + } + if (!fields(result, Set.of("operationId", "applyOperationId", "type", "state", "nodes", + "browserReviewReady", "reviewPath", "results", "values")) + || !canonicalId(result.path("operationId")) + || !Set.of("READ", "PREVIEW", "APPLY").contains(result.path("type").asText()) + || !Set.of("RUNNING", "SUCCEEDED", "COMPLETED_WITH_ERRORS").contains(result.path("state").asText()) + || !result.path("browserReviewReady").isBoolean() + || !result.path("nodes").isObject() || result.path("nodes").size() != 1 + || !result.path("results").isObject() || result.path("results").size() > 1) return false; + if (result.has("applyOperationId") && !canonicalId(result.path("applyOperationId"))) return false; + if (result.has("reviewPath") && !result.path("reviewPath").asText().equals( + "/#agent-review/" + result.path("operationId").asText())) return false; + var nodes = result.path("nodes").fields(); + var node = nodes.next(); + if (!node.getKey().matches("[A-Za-z0-9][A-Za-z0-9._-]{0,63}") + || !Set.of("QUEUED", "IN_PROGRESS", "COMPLETE").contains(node.getValue().asText())) return false; + if (result.has("values") && !validValues(result)) return false; + if (result.path("results").isEmpty()) return true; + JsonNode details = result.path("results").path(node.getKey()); + return fields(details, Set.of("code", "success", "rolledBack", "reloaded")) + && details.path("code").asText().matches("[A-Z][A-Z0-9_]{0,63}") + && details.path("success").isBoolean() && details.path("rolledBack").isBoolean() + && details.path("reloaded").isBoolean(); + } + + private static boolean validValues(JsonNode result) { + JsonNode values = result.path("values"); + if (!"READ".equals(result.path("type").asText()) || !fields(values, Set.of("name", "exists", + "serviceSite", "voteUrl", "enabled", "displayName", "priority", "hidden", "voteDelay", "material", + "displayItem.amount"))) { + return false; + } + for (JsonNode value : values) if (!value.isTextual()) return false; + return true; + } + + private static boolean fields(JsonNode object, Set permitted) { + if (!object.isObject()) return false; + var fields = object.fieldNames(); + while (fields.hasNext()) { + if (!permitted.contains(fields.next())) return false; + } + return true; + } + + private static boolean canonicalId(JsonNode id) { + return id.isTextual() && id.asText().matches( + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + } + + private HttpResponse request(HttpRequest request) throws IOException, InterruptedException { + var pending = client.sendAsync(request, ignored -> new BoundedBody()); + try { + return pending.get(8, TimeUnit.SECONDS); + } catch (ExecutionException | TimeoutException failure) { + throw new IOException("Control request failed", failure); + } finally { + if (!pending.isDone()) pending.cancel(true); + } + } + + private static byte[] readFrame(InputStream input) throws IOException { + ByteArrayOutputStream frame = new ByteArrayOutputStream(); + int next; + while ((next = input.read()) != -1 && next != '\n') { + if (frame.size() == MAX_REQUEST) throw new IOException("MCP frame exceeds the input limit"); + frame.write(next); + } + if (next == -1) return null; + return frame.toByteArray(); + } + + private static Object toolError(JsonNode id, String text) { + return reply(id, "result", Map.of("isError", true, "content", List.of(Map.of("type", "text", "text", text)))); + } + + private static Object error(JsonNode id, int code, String message) { + return reply(id, "error", Map.of("code", code, "message", message)); + } + + private static Object reply(JsonNode id, String field, Object body) { + return Map.of("jsonrpc", "2.0", "id", id, field, body); + } + + private static Map tools() { + Map tools = new LinkedHashMap<>(); + Map node = Map.of("type", "string", "pattern", "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"); + Map name = Map.of("type", "string", "pattern", "^[A-Za-z0-9_-]{1,64}$"); + Map id = Map.of("type", "string", "pattern", + "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); + Map flag = Map.of("type", "boolean"); + Map text = Map.of("type", "string", "minLength", 1, "maxLength", 200); + tools.put("list_nodes", new Tool("list_nodes", "nodes", "List authorized enrolled Control nodes.", + object(Map.of(), List.of()))); + tools.put("read_setup", new Tool("read_setup", "read", "Read one named backend vote site.", + object(Map.of("nodeId", node, "name", name), List.of("nodeId", "name")))); + tools.put("preview_setup", new Tool("preview_setup", "preview", + "Preview a named backend vote site. The operator reviews and applies in Control.", + object(Map.of("nodeId", node, "readOperationId", id, "options", object(Map.of( + "name", name, "serviceSite", text, "voteUrl", Map.of("type", "string", "maxLength", 500), + "enabled", flag, "displayName", text, "priority", Map.of("type", "integer", + "minimum", 0, "maximum", 100), "hidden", flag, "voteDelay", text, "material", text), + List.of("name", "serviceSite", "voteUrl"))), List.of("nodeId", "readOperationId", "options")))); + tools.put("get_operation", new Tool("get_operation", "status", "Track a scoped setup operation.", + object(Map.of("operationId", id), List.of("operationId")))); + return java.util.Collections.unmodifiableMap(tools); + } + + private static Map object(Map properties, List required) { + return Map.of("type", "object", "properties", properties, "required", required, "additionalProperties", false); + } + + private record Tool(String name, String route, String description, Map schema) { + Map descriptionJson() { + return Map.of("name", name, "description", description, "inputSchema", schema); + } + } + + private static final class BoundedBody implements HttpResponse.BodySubscriber { + private final HttpResponse.BodySubscriber delegate = HttpResponse.BodySubscribers.ofByteArray(); + private Flow.Subscription subscription; + private long size; + + public CompletionStage getBody() { return delegate.getBody(); } + + public void onSubscribe(Flow.Subscription subscription) { + this.subscription = subscription; + delegate.onSubscribe(subscription); + } + + public void onNext(List buffers) { + size += buffers.stream().mapToLong(ByteBuffer::remaining).sum(); + if (size > MAX_RESULT) { + subscription.cancel(); + delegate.onError(new IOException("Control response exceeds the result limit")); + return; + } + delegate.onNext(buffers); + } + + public void onError(Throwable failure) { delegate.onError(failure); } + + public void onComplete() { delegate.onComplete(); } + } +} diff --git a/src/main/resources/web/app.js b/src/main/resources/web/app.js index fd8b859..b737502 100644 --- a/src/main/resources/web/app.js +++ b/src/main/resources/web/app.js @@ -1062,6 +1062,122 @@ function rememberOperation(operation) { renderOperationHistory(); } +const agentGrantForm = document.querySelector('#agent-grant-form'); +const agentGrantStatus = document.querySelector('#agent-grant-status'); +const agentCredentialOutput = document.querySelector('#agent-credential-output'); +const agentGrants = document.querySelector('#agent-grants'); +const agentReview = document.querySelector('#agent-review'); +const agentReviewDetail = document.querySelector('#agent-review-detail'); +const agentReviewStatus = document.querySelector('#agent-review-status'); +const agentReviewApply = document.querySelector('#agent-review-apply'); +let agentReviewId = null; + +function agentAdmin(action, body) { + return authorized('/api/v1/agent-admin/' + action, body === undefined ? {} : { + method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body) + }); +} + +function clearAgentCredential() { + agentCredentialOutput.querySelector('input').value = ''; + agentCredentialOutput.hidden = true; +} + +async function loadAgentGrants() { + const grants = await agentAdmin('grants'); + agentGrants.replaceChildren(...grants.map(grant => { + const row = document.createElement('p'); + const label = document.createTextNode(`${grant.id} · ${grant.nodeIds.join(', ')} · ${grant.actions.join(', ')} · ${grant.expiresAt} `); + const revoke = text(document.createElement('button'), 'Revoke'); + revoke.type = 'button'; + revoke.addEventListener('click', async () => { + revoke.disabled = true; + clearAgentCredential(); + try { + await agentAdmin('revoke', {operationId: grant.id}); + await loadAgentGrants(); + } catch (error) { text(agentGrantStatus, error.message); } + finally { revoke.disabled = false; } + }); + row.append(label, revoke); + return row; + })); +} + +agentGrantForm.addEventListener('submit', async event => { + event.preventDefault(); + clearAgentCredential(); + const button = event.submitter; + button.disabled = true; + try { + const form = new FormData(agentGrantForm); + const grant = await agentAdmin('issue', { + nodeIds: form.get('nodes').split(',').map(id => id.trim()), + actions: form.getAll('actions'), + minutes: Number(form.get('minutes')) + }); + agentCredentialOutput.querySelector('input').value = grant.token; + agentCredentialOutput.hidden = false; + text(agentGrantStatus, `Grant expires at ${grant.expiresAt}.`); + await loadAgentGrants(); + } catch (error) { text(agentGrantStatus, error.message); } + finally { button.disabled = false; } +}); + +document.querySelector('#agent-grant-refresh').addEventListener('click', () => { + loadAgentGrants().catch(error => text(agentGrantStatus, error.message)); +}); + +async function reviewAgentPreview(operationId) { + agentReviewId = operationId; + agentReviewApply.disabled = true; + text(agentReviewDetail, ''); + text(agentReviewStatus, 'Loading preview…'); + if (!agentReview.open) agentReview.showModal(); + try { + const {operation, before} = await agentAdmin('review', {operationId}); + if (agentReviewId !== operationId || !agentReview.open) return; + const options = operation.configuration.options; + const details = [...Object.entries(options), ['displayItem.amount', '1']] + .map(([key, value]) => `${key}: ${before.exists === 'true' && Object.hasOwn(before, key) + ? JSON.stringify(before[key]) : '(absent)'} → ${JSON.stringify(value)}`).join('\n'); + text(agentReviewDetail, `Agent ${operation.agentId} +${operationSummary(operation)} + +Proposed settings +${details}`); + text(agentReviewStatus, operation.browserReviewReady ? 'Review the listed changes before applying.' + : 'This preview is not ready for approval. Refresh Activity to check again.'); + agentReviewApply.disabled = !operation.browserReviewReady; + } catch (error) { + if (agentReviewId === operationId && agentReview.open) text(agentReviewStatus, error.message); + } +} + +agentReviewApply.addEventListener('click', async () => { + const operationId = agentReviewId; + agentReviewApply.disabled = true; + try { + const operation = await agentAdmin('approve', {operationId}); + if (agentReviewId !== operationId || !agentReview.open) return; + text(agentReviewStatus, `Apply queued · ${operation.operationId}`); + await loadOperationHistory(); + } catch (error) { + if (agentReviewId === operationId && agentReview.open) text(agentReviewStatus, error.message); + } +}); + +agentReview.addEventListener('close', () => { + agentReviewId = null; + agentReviewApply.disabled = true; + text(agentReviewDetail, ''); + text(agentReviewStatus, ''); +}); + +function agentReviewFromHash() { + return /^#agent-review\/([0-9a-f-]{36})$/.exec(window.location.hash)?.[1]; +} + function renderOperationHistory() { operationHistory.replaceChildren(); if (operationHistoryItems.length === 0 && deploymentHistoryItems.length === 0) { @@ -1110,6 +1226,12 @@ function renderOperationHistory() { }); actions.append(retry); } + if (operation.type === 'PREVIEW' && operation.agentId) { + const review = text(document.createElement('button'), 'Review agent preview'); + review.type = 'button'; + review.addEventListener('click', () => void reviewAgentPreview(operation.operationId)); + actions.append(review); + } if (operation.type === 'PREVIEW' && operation.state === 'SUCCEEDED' && operation.approvalToken && operation.configuration?.domain === 'quick-setup' && !['proxy-method', 'reward-builder', 'sync-vote-sites'].includes(operation.configuration?.preset)) { @@ -1365,6 +1487,7 @@ async function loadSetupState() { } function applyAuthenticatedSession(body) { + const agentPreview = agentReviewFromHash(); configurationTargetNodeId = null; settingsEditor?.clear(); settingsHealthReader?.clear(); @@ -1376,6 +1499,7 @@ function applyAuthenticatedSession(body) { window.history.replaceState(null, '', '#home'); authenticated = true; csrfToken = body.csrfToken; + if (agentPreview) void reviewAgentPreview(agentPreview); approvedPreview = null; approvedFilePreview = null; approvedQuickPreview = null; @@ -1751,6 +1875,12 @@ function enterGlobalWorkspace() { function applyNavigationRoute() { if (!authenticated) return; + const agentPreview = agentReviewFromHash(); + if (agentPreview) { + window.history.replaceState(null, '', activeNavigationHash || '#home'); + void reviewAgentPreview(agentPreview); + return; + } const route = ControlWorkspace.parseRoute(window.location.hash); const cancelNavigation = () => window.history.replaceState(null, '', activeNavigationHash); if (route.scope === 'GLOBAL' && workspace.managementScope !== 'GLOBAL') { @@ -3754,6 +3884,11 @@ async function waitForDeployment(operation, generation) { } function discardAuthenticationState(reason) { + clearAgentCredential(); + agentGrantForm.reset(); + agentGrants.replaceChildren(); + text(agentGrantStatus, ''); + if (agentReview.open) agentReview.close(); settingsEditor?.clear(); settingsHealthReader?.clear(); voteSitesEditor?.clear(); diff --git a/src/main/resources/web/index.html b/src/main/resources/web/index.html index 6790fba..61b6f28 100644 --- a/src/main/resources/web/index.html +++ b/src/main/resources/web/index.html @@ -706,6 +706,14 @@

Setup

Safe service-site test

Resolve a service name and report whether it would match or auto-create. No fake vote is submitted and no reward runs.

No service tested.
+ +

Review agent vote-site preview

+

+        

+ +
+
+