Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
48 changes: 48 additions & 0 deletions docs/agent-setup.md
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 8 additions & 0 deletions docs/control-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> ACTIONS = Set.of("discover", "read", "preview", "status");
private final Map<UUID, Grant> 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<GrantView> 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<String, String> 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<String, Object> project(ConfigurationOperations.OperationView operation) {
Map<String, Object> 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<String, Object> results = new LinkedHashMap<>();
operation.results().forEach((node, value) -> {
Map<String, Object> 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<String, String> values, String field, String value) {
if (value != null) values.put(field, bounded(value, 200));
}

private static ManagedConfiguration configuration(Map<String, String> 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<String> nodeIds, List<String> actions, Integer minutes) { }
public record Issued(UUID id, String token, Instant expiresAt) { }
public record GrantView(UUID id, Set<String> nodeIds, Set<String> 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<String> nodes, Set<String> actions, Instant expiresAt, byte[] verifier) { }
}
Loading
Loading