Files
VCCPlusOSS/platforms/macos/Tools/MCP/main.mm
T
Brian Holman 5534005799 Sync VCC Plus 3.7.1 build 67 source
Refresh reviewed MCP output export, four-drive owned playtests, bounded BASIC readiness, and pinned CMOC 0.1.101 source/patches. Preserve independent source-edition identity, empty libraries, notices and privacy boundaries.

Validated 74 export/privacy checks, pinned dependency sources, and an independent unsigned universal Release build. A subsequent documentation-only correction removes an excluded qualification link; all build inputs remain identical.
2026-11-17 08:42:27 -07:00

584 lines
37 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-or-later
// VCC Plus MCP server, standard input/output transport.
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import "MCPGuestTools.h"
#import "MCPProjectTools.h"
#include <arpa/inet.h>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <string>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
namespace {
using Clock = std::chrono::steady_clock;
constexpr size_t maxClientFrame = 64 * 1024;
constexpr size_t maxHostRequest = 48 * 1024;
constexpr size_t maxHostFrame = 1024 * 1024;
struct Descriptor {
int fd;
explicit Descriptor(int fd) : fd(fd) {}
~Descriptor() { if (fd >= 0) close(fd); }
Descriptor(const Descriptor&) = delete;
Descriptor& operator=(const Descriptor&) = delete;
};
bool object(id value) { return [value isKindOfClass:NSDictionary.class]; }
bool string(id value) { return [value isKindOfClass:NSString.class]; }
bool integer(id value) {
if (![value isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)value) == CFBooleanGetTypeID())
return false;
return !CFNumberIsFloatType((__bridge CFNumberRef)value);
}
NSData *jsonBytes(id value) {
return [NSJSONSerialization dataWithJSONObject:value options:0 error:nil];
}
id parse(const void *bytes, size_t length) {
// NSJSONSerialization also accepts UTF-16/32. MCP frames are UTF-8.
if (!length || memchr(bytes, 0, length)) return nil;
NSData *data = [NSData dataWithBytes:bytes length:length];
if (![[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]) return nil;
return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingFragmentsAllowed error:nil];
}
NSDictionary *loadGrant(const char *path) {
Descriptor file(open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK));
struct stat st{};
if (file.fd < 0 || fstat(file.fd, &st) || !S_ISREG(st.st_mode) || st.st_uid != geteuid() ||
(st.st_mode & 0077) || st.st_size < 1 || st.st_size > 4096) return nil;
char bytes[4097];
size_t size = 0;
while (size < sizeof(bytes)) {
ssize_t count = read(file.fd, bytes + size, sizeof(bytes) - size);
if (count < 0 && errno == EINTR) continue;
if (count < 0) return nil;
if (count == 0) break;
size += static_cast<size_t>(count);
}
if (size != static_cast<size_t>(st.st_size)) return nil;
id grant = parse(bytes, size);
if (!object(grant) || !integer(grant[@"version"]) || !string(grant[@"token"]) || [grant[@"token"] length] == 0)
return nil;
// Older helpers reject a version-2 archive grant instead of treating it as a BASIC grant.
if (![grant[@"version"] isEqual:([grant[@"kind"] isEqual:@"archive"] ? @2 : @1)]) return nil;
return grant;
}
bool ready(int fd, short events, Clock::time_point deadline) {
pollfd p{fd, events, 0};
for (;;) {
const auto now = Clock::now();
if (now >= deadline) return false;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count();
if (ms < 1) ms = 1;
int n = poll(&p, 1, static_cast<int>(ms));
if (n < 0 && errno == EINTR) continue;
if (n == 0) continue;
return n > 0 && (p.revents & events);
}
}
NSDictionary *hostCall(NSDictionary *grant, bool loopback, NSString *tool, NSDictionary *args) {
sockaddr_storage storage{};
sockaddr *address = reinterpret_cast<sockaddr *>(&storage);
if (loopback || !grant[@"socket"]) {
NSNumber *port = grant[@"port"];
if (!integer(port) || port.longLongValue < 1 || port.longLongValue > 65535) return @{@"error":@"invalid_endpoint"};
sockaddr_in *tcp = reinterpret_cast<sockaddr_in *>(&storage);
tcp->sin_family = AF_INET;
tcp->sin_len = sizeof(*tcp);
tcp->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
tcp->sin_port = htons(port.unsignedShortValue);
} else {
NSString *path = grant[@"socket"];
sockaddr_un *local = reinterpret_cast<sockaddr_un *>(&storage);
if (!string(path) || ![path hasPrefix:@"/"] || [path lengthOfBytesUsingEncoding:NSUTF8StringEncoding] >= sizeof(local->sun_path) ||
strlen(path.UTF8String) != [path lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) return @{@"error":@"invalid_endpoint"};
local->sun_family = AF_UNIX;
local->sun_len = sizeof(*local);
strlcpy(local->sun_path, path.UTF8String, sizeof(local->sun_path));
}
NSData *payload = jsonBytes(@{@"version":@1, @"token":grant[@"token"], @"tool":tool, @"arguments":args});
if (!payload || payload.length + 1 > maxHostRequest) return @{@"error":@"request_too_large"};
std::string request(static_cast<const char *>(payload.bytes), payload.length);
request.push_back('\n');
Descriptor peer(socket(address->sa_family, SOCK_STREAM, 0));
const bool playtestCall = [@[@"start_playtest", @"playtest_input", @"playtest_debug", @"capture_playtest",
@"restart_playtest", @"stop_playtest", @"get_debug_snapshot", @"capture_playtest_graphics",
@"exchange_playtest_media", @"start_playtest_video", @"stop_playtest_video"] containsObject:tool];
const auto deadline = Clock::now() + std::chrono::seconds(playtestCall ? 55 : 5);
if (peer.fd < 0 || fcntl(peer.fd, F_SETFL, O_NONBLOCK) < 0) return @{@"error":@"host_unavailable"};
if (connect(peer.fd, address, address->sa_len) != 0) {
int error = 0;
socklen_t size = sizeof(error);
if (errno != EINPROGRESS) return @{@"error":@"host_unavailable"};
if (!ready(peer.fd, POLLOUT, deadline))
return @{@"error":Clock::now() >= deadline ? @"transport_timeout" : @"host_unavailable"};
if (getsockopt(peer.fd, SOL_SOCKET, SO_ERROR, &error, &size) || error) return @{@"error":@"host_unavailable"};
}
if (address->sa_family == AF_UNIX) {
uid_t uid;
gid_t gid;
if (getpeereid(peer.fd, &uid, &gid) || uid != geteuid()) return @{@"error":@"host_identity_mismatch"};
}
size_t offset = 0;
while (offset < request.size()) {
if (!ready(peer.fd, POLLOUT, deadline))
return @{@"error":Clock::now() >= deadline ? @"transport_timeout" : @"host_unavailable"};
ssize_t n = write(peer.fd, request.data() + offset, request.size() - offset);
if (n < 0 && (errno == EINTR || errno == EAGAIN)) continue;
if (n <= 0) return @{@"error":@"host_unavailable"};
offset += static_cast<size_t>(n);
}
std::string response;
while (response.size() < maxHostFrame && ready(peer.fd, POLLIN, deadline)) {
char buffer[8192];
ssize_t n = read(peer.fd, buffer, sizeof(buffer));
if (n < 0 && (errno == EAGAIN || errno == EINTR)) continue;
if (n <= 0) break;
const char *end = static_cast<const char *>(memchr(buffer, '\n', n));
response.append(buffer, end ? static_cast<size_t>(end-buffer) : static_cast<size_t>(n));
if (end && response.size() < maxHostFrame) {
id reply = parse(response.data(), response.size());
if (object(reply) && ((object(reply[@"result"]) && !reply[@"error"]) ||
(string(reply[@"error"]) && !reply[@"result"]))) return reply;
break;
}
}
if (Clock::now() >= deadline) return @{@"error":@"transport_timeout"};
return @{@"error":@"invalid_or_incomplete_host_reply"};
}
NSDictionary *tool(NSString *name, NSString *description, NSString *argument) {
NSDictionary *properties = argument ? @{argument:@{@"type":@"string", @"minLength":@1}} : @{};
return @{@"name":name, @"description":description,
@"inputSchema":@{@"type":@"object", @"properties":properties,
@"required":argument ? @[argument] : @[], @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@YES, @"openWorldHint":@NO}};
}
NSDictionary *proposalTool(bool listing) {
NSDictionary *str = @{@"type":@"string", @"minLength":@1, @"maxLength":@128};
if (listing) {
NSDictionary *fields = @{@"document_id":str, @"request_id":str,
@"revision":@{@"type":@"integer", @"minimum":@0},
@"source":@{@"type":@"string", @"minLength":@1, @"maxLength":@12288}};
return @{@"name":@"propose_listing",
@"description":@"Propose a complete numbered ASCII BASIC listing (up to 12 KiB) to create or revise the shared draft. Read its document_id and revision first. The user reviews before applying or running it. Reuse request_id (up to 128 UTF-8 bytes) only for an identical proposal.",
@"inputSchema":@{@"type":@"object", @"properties":fields, @"required":@[@"document_id", @"revision", @"source", @"request_id"], @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@NO, @"destructiveHint":@NO, @"idempotentHint":@YES, @"openWorldHint":@NO}};
}
NSDictionary *props = @{@"document_id":str, @"request_id":str, @"revision":@{@"type":@"integer", @"minimum":@0},
@"line_number":@{@"type":@"integer", @"minimum":@0, @"maximum":@63999},
@"replacement":@{@"type":@"string", @"minLength":@1, @"maxLength":@249}};
return @{@"name":@"propose_edit", @"description":@"Propose replacing exactly one existing numbered BASIC line for native review. Read the current source revision first. Include the number in the replacement. Reuse request_id only for the same proposal.",
@"inputSchema":@{@"type":@"object", @"properties":props, @"required":@[@"document_id", @"revision", @"line_number", @"replacement", @"request_id"], @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@NO, @"destructiveHint":@NO, @"idempotentHint":@YES, @"openWorldHint":@NO}};
}
NSArray *archiveTools() {
NSDictionary *readOnly = @{@"readOnlyHint":@YES, @"openWorldHint":@NO};
NSDictionary *fields = @{
@"query":@{@"type":@"string", @"minLength":@1, @"maxLength":@256},
@"category":@{@"type":@"string", @"minLength":@1, @"maxLength":@512,
@"description":@"An optional Archive collection path such as Books or Magazines."},
@"limit":@{@"type":@"integer", @"minimum":@1, @"maximum":@50, @"default":@10},
@"offset":@{@"type":@"integer", @"minimum":@0, @"maximum":@250000, @"default":@0}
};
return @[
@{@"name":@"search_archive", @"description":@"Search the installed Color Computer Archive index by terms or title. Returns public citations and upstream source links. Inspect the original source to verify a passage.",
@"inputSchema":@{@"type":@"object", @"properties":fields, @"required":@[@"query"], @"additionalProperties":@NO},
@"annotations":readOnly},
@{@"name":@"get_archive_citation", @"description":@"Resolve a citation_id returned by search_archive to its original Archive source and location. This lookup does not fetch the source or return page text.",
@"inputSchema":@{@"type":@"object", @"properties":@{@"citation_id":@{@"type":@"string", @"minLength":@1, @"maxLength":@128}},
@"required":@[@"citation_id"], @"additionalProperties":@NO},
@"annotations":readOnly}
];
}
NSDictionary *inspectionTool(NSString *name, NSString *description, NSDictionary *properties, BOOL readOnly) {
NSArray *required = [properties.allKeys sortedArrayUsingSelector:@selector(compare:)];
return @{@"name":name, @"description":description,
@"inputSchema":@{@"type":@"object", @"properties":properties, @"required":required, @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@(readOnly), @"openWorldHint":@NO}};
}
NSArray *debuggerTools() {
NSDictionary *identifier = @{@"type":@"string", @"minLength":@1, @"maxLength":@128};
return @[
inspectionTool(@"get_debug_snapshot", @"Inspect a verified stopped run. Returns registers, available source or function information, watches, readable ranges and an opaque snapshot ID.",
@{@"run_id":identifier}, YES),
inspectionTool(@"read_debug_memory", @"Read 1–256 bytes from an advertised range of the same stopped program using its run and snapshot IDs.",
@{@"run_id":identifier, @"snapshot_id":identifier, @"address":@{@"type":@"integer", @"minimum":@0, @"maximum":@65535},
@"count":@{@"type":@"integer", @"minimum":@1, @"maximum":@256}}, YES)
];
}
NSDictionary *projectEditsTool(bool assembly) {
NSDictionary *identifier = @{@"type":@"string", @"minLength":@1, @"maxLength":@128};
NSDictionary *file = @{@"type":@"object", @"required":@[@"path", @"source"], @"additionalProperties":@NO,
@"properties":@{@"path":@{@"type":@"string", @"minLength":@1, @"maxLength":@512},
@"source":@{@"type":@"string", @"maxLength":@16384}}};
NSString *description = [NSString stringWithFormat:@"Propose one reviewed change to 1–8 existing %@ files. Each entry contains a shared relative path and complete replacement text. All replacements together must fit 16 KiB UTF-8. Use the current revision. Reuse request_id only for the identical request.", assembly ? @"assembly or include" : @"C or header"];
return inspectionTool(@"propose_project_edits", description,
@{@"project_id":identifier, @"revision":@{@"type":@"integer", @"minimum":@0}, @"request_id":identifier,
@"edits":@{@"type":@"array", @"minItems":@1, @"maxItems":@8, @"items":file}}, NO);
}
NSDictionary *rpcError(id rid, NSInteger code, NSString *message) {
return @{@"jsonrpc":@"2.0", @"id":rid ?: NSNull.null, @"error":@{@"code":@(code), @"message":message}};
}
NSDictionary *toolError(id rid, NSString *message) {
return @{@"jsonrpc":@"2.0", @"id":rid, @"result":@{@"isError":@YES,
@"content":@[@{@"type":@"text", @"text":message}]}};
}
// Validate schema values recursively: array items can themselves be scalars,
// arrays or objects. Bounds apply only when declared in the tool's schema.
NSString *schemaValueError(id value, NSDictionary *schema, unsigned depth, unsigned& nodes) {
if (depth > 16 || ++nodes > 8192) return @"Tool argument nesting or item limit exceeded";
if (!object(schema)) return @"Invalid tool schema";
NSString *type = schema[@"type"];
if ([type isEqual:@"object"]) {
if (!object(value)) return @"arguments must be an object";
NSDictionary *properties = schema[@"properties"] ?: @{};
for (NSString *key in schema[@"required"])
if (!value[key]) return [NSString stringWithFormat:@"Missing required argument: %@", key];
for (NSString *key in value) {
NSDictionary *field = properties[key];
if (!field) {
if ([schema[@"additionalProperties"] isEqual:@YES]) continue;
return @"Unexpected tool argument. Use the properties in tools/list.";
}
NSString *problem = schemaValueError(value[key], field, depth + 1, nodes);
if (problem) return [NSString stringWithFormat:@"%@: %@", key, problem];
}
} else if ([type isEqual:@"array"]) {
if (![value isKindOfClass:NSArray.class]) return @"must be an array";
if ((schema[@"minItems"] && [value count] < [schema[@"minItems"] unsignedIntegerValue]) ||
(schema[@"maxItems"] && [value count] > [schema[@"maxItems"] unsignedIntegerValue]))
return @"must be an array within its allowed size";
if ([schema[@"uniqueItems"] isEqual:@YES] && [NSSet setWithArray:value].count != [value count])
return @"array items must be unique";
NSUInteger index = 0;
for (id member in value) {
NSString *problem = schemaValueError(member, schema[@"items"], depth + 1, nodes);
if (problem) return [NSString stringWithFormat:@"item %lu: %@", (unsigned long)index, problem];
++index;
}
} else if ([type isEqual:@"integer"]) {
if (!integer(value)) return @"must be an integer";
if ((schema[@"minimum"] && [value compare:schema[@"minimum"]] == NSOrderedAscending) ||
(schema[@"maximum"] && [value compare:schema[@"maximum"]] == NSOrderedDescending))
return @"is outside the allowed numeric range";
} else if ([type isEqual:@"boolean"]) {
if (![value isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)value) != CFBooleanGetTypeID())
return @"must be a boolean";
} else if ([type isEqual:@"string"]) {
if (!string(value)) return @"must be a string";
NSUInteger length = [value lengthOfBytesUsingEncoding:NSUTF32LittleEndianStringEncoding] / 4;
if ((schema[@"minLength"] && length < [schema[@"minLength"] unsignedIntegerValue]) ||
(schema[@"maxLength"] && length > [schema[@"maxLength"] unsignedIntegerValue]))
return @"is outside the allowed string length";
if (NSString *pattern = schema[@"pattern"]) {
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
if (!expression) return @"Invalid tool schema pattern";
NSTextCheckingResult *match = [expression firstMatchInString:value options:0 range:NSMakeRange(0, [value length])];
if (!match || !NSEqualRanges(match.range, NSMakeRange(0, [value length])))
return @"does not match the required string pattern";
}
} else return @"Unsupported tool schema type";
NSArray *choices = schema[@"enum"];
if (choices && ![choices containsObject:value]) return @"must be one of the listed values";
if (id alternatives = schema[@"oneOf"]) {
if (![alternatives isKindOfClass:NSArray.class] || ![alternatives count]) return @"Invalid tool schema alternatives";
unsigned matches = 0;
for (id alternative in alternatives) {
if (!object(alternative)) return @"Invalid tool schema alternative";
if (!schemaValueError(value, alternative, depth + 1, nodes)) ++matches;
if (nodes > 8192) return @"Tool argument nesting or item limit exceeded";
}
if (matches != 1) return @"arguments must match exactly one advertised action schema";
}
return nil;
}
NSString *argumentError(NSDictionary *args, NSDictionary *schema) {
unsigned nodes = 0;
return schemaValueError(args, schema, 0, nodes);
}
NSDictionary *success(id rid, NSDictionary *result) {
return @{@"jsonrpc":@"2.0", @"id":rid, @"result":result};
}
enum class Phase { fresh, initializing, active };
NSDictionary *handle(id message, NSDictionary *grant, bool loopback, NSArray *tools, Phase& phase, NSString *__strong& version) {
if (!object(message)) return rpcError(nil, -32600, @"Expected a JSON-RPC request");
id rid = message[@"id"];
NSString *method = message[@"method"];
// This server never calls client methods. A stray response does not need a reply.
if (!method && [message[@"jsonrpc"] isEqual:@"2.0"] && (integer(rid) || string(rid))) {
if ((object(message[@"result"]) && !message[@"error"]) ||
(object(message[@"error"]) && !message[@"result"])) return nil;
}
const bool validID = integer(rid) || string(rid);
if ((rid && !validID) || !string(method) || ![message[@"jsonrpc"] isEqual:@"2.0"])
return rpcError(validID ? rid : nil, -32600, @"Invalid JSON-RPC request");
NSDictionary *params = message[@"params"] ?: @{};
if (!rid) {
if (phase == Phase::initializing && [method isEqual:@"notifications/initialized"] && object(params)) phase = Phase::active;
return nil;
}
if (!object(params)) return rpcError(rid, -32602, @"Expected object parameters");
if ([method isEqual:@"ping"]) return success(rid, @{});
if ([method isEqual:@"initialize"]) {
if (phase != Phase::fresh) return rpcError(rid, -32600, @"Already initialized");
id info = params[@"clientInfo"];
if (!string(params[@"protocolVersion"]) || !object(params[@"capabilities"]) || !object(info) ||
!string(info[@"name"]) || !string(info[@"version"])) return rpcError(rid, -32602, @"Invalid initialization parameters");
NSArray *supported = @[@"2025-11-25", @"2025-06-18", @"2025-03-26"];
version = [supported containsObject:params[@"protocolVersion"]] ? params[@"protocolVersion"] : supported.firstObject;
phase = Phase::initializing;
return success(rid, @{@"protocolVersion":version, @"capabilities":@{@"tools":@{}},
@"serverInfo":@{@"name":@"vcc-plus", @"version":@"1.0"}});
}
if (phase != Phase::active) return rpcError(rid, -32002, @"Initialize the MCP session first");
if ([method isEqual:@"tools/list"]) {
if (params[@"cursor"]) return rpcError(rid, -32602, @"Unknown cursor");
return success(rid, @{@"tools":tools});
}
if (![method isEqual:@"tools/call"]) return rpcError(rid, -32601, @"Unknown method");
NSString *name = params[@"name"];
NSDictionary *args = params[@"arguments"] ?: @{};
if (!string(name) || !object(args)) return rpcError(rid, -32602, @"tools/call needs a tool name and object arguments");
for (NSDictionary *item in tools) {
if (![item[@"name"] isEqual:name]) continue;
NSString *problem = argumentError(args, item[@"inputSchema"]);
if (problem) {
if ([version isEqual:@"2025-11-25"]) return toolError(rid, problem);
return rpcError(rid, -32602, problem);
}
NSDictionary *reply = hostCall(grant, loopback, name, args);
if (reply[@"error"]) {
if (object(reply[@"error_details"])) {
NSMutableDictionary *failure = [toolError(rid, reply[@"error"]) mutableCopy];
NSMutableDictionary *result = [failure[@"result"] mutableCopy];
result[@"structuredContent"] = reply[@"error_details"];
failure[@"result"] = result;
return failure;
}
return toolError(rid, reply[@"error"]);
}
NSMutableDictionary *data = [reply[@"result"] mutableCopy];
NSMutableArray *content = [NSMutableArray array];
if ([name isEqual:@"read_playtest_video"]) {
NSString *encoded = data[@"video_chunk_base64"], *hash = data[@"sha256"];
if (!string(encoded) || encoded.length > 87384 || !string(hash) || hash.length != 64 ||
[hash rangeOfCharacterFromSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdef"] invertedSet]].location != NSNotFound ||
![data[@"mime_type"] isEqual:@"video/mp4"] || ![data[@"clip_id"] isEqual:args[@"clip_id"]] ||
!integer(data[@"offset"]) || !integer(data[@"next_offset"]) || !integer(data[@"byte_count"]) ||
![data[@"eof"] isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)data[@"eof"]) != CFBooleanGetTypeID())
return toolError(rid, @"invalid_playtest_video");
NSData *chunk = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
const long long offset = [data[@"offset"] longLongValue], next = [data[@"next_offset"] longLongValue], total = [data[@"byte_count"] longLongValue];
const long long requestedOffset = args[@"offset"] ? [args[@"offset"] longLongValue] : 0;
const NSUInteger limit = args[@"limit"] ? [args[@"limit"] unsignedIntegerValue] : 65536;
if (!chunk || chunk.length > limit || chunk.length > 65536 || offset != requestedOffset || offset < 0 ||
total < 1 || total > 67108864 || offset > total || next != offset + (long long)chunk.length || next > total ||
[data[@"eof"] boolValue] != (next == total) || (!chunk.length && next < total))
return toolError(rid, @"invalid_playtest_video");
}
if ([name isEqual:@"capture_playtest_audio"]) {
NSString *encoded = data[@"audio_wav_base64"];
if (!string(encoded) || !object(data[@"audio"])) return toolError(rid, @"invalid_playtest_audio");
NSData *wav = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
if (!wav || wav.length < 44 || wav.length > 524332) return toolError(rid, @"invalid_playtest_audio");
const auto *p = static_cast<const unsigned char *>(wav.bytes);
auto u16 = [&](unsigned at) -> uint32_t { return p[at] | (uint32_t(p[at+1]) << 8); };
auto u32 = [&](unsigned at) -> uint32_t { return u16(at) | (u16(at+2) << 16); };
if (memcmp(p,"RIFF",4) || memcmp(p+8,"WAVEfmt ",8) || memcmp(p+36,"data",4) ||
u32(4) != wav.length-8 || u32(16) != 16 || u16(20) != 1 || u16(22) != 2 ||
u32(24) != 44100 || u32(28) != 176400 || u16(32) != 4 || u16(34) != 16 ||
u32(40) != wav.length-44 || (wav.length-44)%4) return toolError(rid, @"invalid_playtest_audio");
NSDictionary *audio = data[@"audio"];
const NSUInteger frames = (wav.length-44)/4;
if (!integer(audio[@"sample_rate"]) || [audio[@"sample_rate"] unsignedIntegerValue] != 44100 ||
!integer(audio[@"channels"]) || [audio[@"channels"] unsignedIntegerValue] != 2 ||
![audio[@"encoding"] isEqual:@"pcm_s16le"] ||
!integer(audio[@"sample_frames"]) || [audio[@"sample_frames"] unsignedIntegerValue] != frames ||
!integer(audio[@"sample_count"]) || [audio[@"sample_count"] unsignedIntegerValue] != frames*2 ||
!integer(audio[@"byte_count"]) || [audio[@"byte_count"] unsignedIntegerValue] != wav.length)
return toolError(rid, @"invalid_playtest_audio");
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(wav.bytes, static_cast<CC_LONG>(wav.length), digest);
NSMutableString *hash = [NSMutableString string];
for (auto byte : digest) [hash appendFormat:@"%02x",byte];
if (![audio[@"sha256"] isEqual:hash]) return toolError(rid, @"invalid_playtest_audio");
[data removeObjectForKey:@"audio_wav_base64"];
data[@"audio_content"] = @YES;
[content addObject:@{@"type":@"audio", @"mimeType":@"audio/wav", @"data":encoded}];
}
if ([name isEqual:@"capture_playtest_graphics"]) {
NSArray *buffers = data[@"buffers"];
if (![buffers isKindOfClass:NSArray.class] || buffers.count < 1 || buffers.count > 2)
return toolError(rid, @"invalid_playtest_capture");
NSMutableArray *metadata = [NSMutableArray array];
NSUInteger total = 0;
for (id row in buffers) {
if (!object(row) || !string(row[@"png_base64"])) return toolError(rid, @"invalid_playtest_capture");
NSString *encoded = row[@"png_base64"];
NSData *png = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
const unsigned char signature[] = {137,80,78,71,13,10,26,10};
if (!png || png.length < 33 || png.length > 350000 || memcmp(png.bytes, signature, 8))
return toolError(rid, @"invalid_playtest_capture");
total += png.length;
if (total > 700000) return toolError(rid, @"invalid_playtest_capture");
NSMutableDictionary *fields = [row mutableCopy];
[fields removeObjectForKey:@"png_base64"]; fields[@"image_content"] = @YES;
[metadata addObject:fields];
[content addObject:@{@"type":@"image", @"mimeType":@"image/png", @"data":encoded}];
}
data[@"buffers"] = metadata;
}
if ([@[@"capture_playtest", @"start_playtest"] containsObject:name] && string(data[@"png_base64"])) {
NSString *encoded = data[@"png_base64"];
NSData *png = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
const unsigned char signature[] = {137,80,78,71,13,10,26,10};
if (!png || png.length < 8 || png.length > 650000 || memcmp(png.bytes, signature, 8))
return toolError(rid, @"invalid_playtest_capture");
[data removeObjectForKey:@"png_base64"];
data[@"image_content"] = @YES;
[content addObject:@{@"type":@"image", @"mimeType":@"image/png", @"data":encoded}];
}
NSString *text = [[NSString alloc] initWithData:jsonBytes(data) encoding:NSUTF8StringEncoding];
[content insertObject:@{@"type":@"text", @"text":text} atIndex:0];
NSMutableDictionary *result = [@{@"content":content} mutableCopy];
if (![version isEqual:@"2025-03-26"]) result[@"structuredContent"] = data;
return success(rid, result);
}
return rpcError(rid, -32602, @"Unknown tool name");
}
} // namespace
int main(int argc, char **argv) {
@autoreleasepool {
const char *usage = "Usage: vcc-mcp --grant FILE [--loopback]\n"
"Select a private grant file exported by VCC Plus. Use --loopback for local TCP instead of the Unix socket.\n";
if (argc == 2 && !strcmp(argv[1], "--help")) { fputs(usage, stdout); return 0; }
bool loopback = argc == 4 && !strcmp(argv[3], "--loopback");
if ((argc != 3 && !loopback) || strcmp(argv[1], "--grant")) { fputs(usage, stderr); return 2; }
NSDictionary *grant = loadGrant(argv[2]); // Pin the original capability for this helper's lifetime.
if (!grant) { fputs("Invalid grant. Select an owner-only grant file exported by VCC Plus.\n", stderr); return 1; }
signal(SIGPIPE, SIG_IGN);
NSArray *manualTools = @[
tool(@"search_help", @"Find matching sections of the installed VCC Plus manuals. Supply 1 to 160 UTF-8 bytes of search terms.", @"query"),
tool(@"read_topic", @"Read a manual section using its topic_id from search_help (up to 512 UTF-8 bytes).", @"topic_id")
];
NSArray *tools;
const bool archive = [grant[@"kind"] isEqual:@"archive"];
const NSInteger toolset = integer(grant[@"toolset"]) ? [grant[@"toolset"] integerValue] : 0;
if (archive) {
tools = archiveTools();
} else if ([grant[@"kind"] isEqual:@"cmoc"] || [grant[@"kind"] isEqual:@"assembly"]) {
const bool customMake = [grant[@"kind"] isEqual:@"cmoc"] &&
toolset >= 4 && [grant[@"customMake"] isEqual:@YES];
const bool mediaExchange = [grant[@"kind"] isEqual:@"cmoc"] && toolset >= 11 &&
[grant[@"playtest"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() &&
[grant[@"playtestMedia"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtestMedia"]) == CFBooleanGetTypeID();
const bool multiDrive = mediaExchange && toolset >= 13 &&
[grant[@"playtestMultiDrive"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtestMultiDrive"]) == CFBooleanGetTypeID();
tools = [MCPProjectTools([grant[@"kind"] isEqual:@"assembly"], toolset >= 3,
customMake) arrayByAddingObjectsFromArray:manualTools];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 13 &&
[grant[@"buildExport"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"buildExport"]) == CFBooleanGetTypeID())
tools = [tools arrayByAddingObjectsFromArray:MCPBuildExportTools()];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 6 && [grant[@"projectRefresh"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:MCPProjectRefreshTools()];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 7 && [grant[@"projectDiagnostics"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:MCPBuildDiagnosticTools()];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 5 && [grant[@"playtest"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestTools(
toolset >= 8 && [grant[@"playtestProcessors"] isEqual:@YES],
toolset >= 9 && [grant[@"playtestJoysticks"] isEqual:@YES] &&
CFGetTypeID((__bridge CFTypeRef)grant[@"playtestJoysticks"]) == CFBooleanGetTypeID(), mediaExchange)];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 7 &&
[grant[@"playtest"] isEqual:@YES] && [grant[@"playtestAudio"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestAudioTools()];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 12 &&
[grant[@"playtest"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() &&
[grant[@"playtestVideo"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtestVideo"]) == CFBooleanGetTypeID())
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestVideoTools()];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 10 && [grant[@"playtest"] isEqual:@YES] &&
CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() &&
[grant[@"playtestCallContext"] isEqual:@YES] &&
CFGetTypeID((__bridge CFTypeRef)grant[@"playtestCallContext"]) == CFBooleanGetTypeID())
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestCallContextTools()];
if (mediaExchange)
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestMediaTools(multiDrive)];
} else {
tools = [@[tool(@"get_capabilities", @"Identify the connected VCC Plus session and selected BASIC document.", nil),
tool(@"read_source", @"Read the selected BASIC draft using its document_id from get_capabilities.", @"document_id")]
arrayByAddingObjectsFromArray:manualTools];
if ([grant[@"canPropose"] isEqual:@YES]) {
tools = [tools arrayByAddingObjectsFromArray:@[proposalTool(false), proposalTool(true),
tool(@"get_proposal", @"Check the status of a proposal in this session.", @"proposal_id")]];
tools = [tools arrayByAddingObjectsFromArray:MCPGuestTools(toolset >= 3)];
}
}
// A newly installed helper may be used with a connection from an older running app.
if (!archive && toolset >= 2) {
tools = [tools arrayByAddingObject:tool(@"get_machine_status", @"Read the active guest CPU, media status, and build and run blockers for the shared workspace.", nil)];
const bool cmoc = [grant[@"kind"] isEqual:@"cmoc"];
if (cmoc || [grant[@"kind"] isEqual:@"assembly"] || [grant[@"canPropose"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:debuggerTools()];
if (cmoc || [grant[@"kind"] isEqual:@"assembly"]) tools = [tools arrayByAddingObject:projectEditsTool(!cmoc)];
}
Phase phase = Phase::fresh;
NSString *version = nil;
for (;;) {
@autoreleasepool {
std::string line;
int ch;
while ((ch = getchar()) != EOF && ch != '\n')
if (line.size() <= maxClientFrame) line.push_back(static_cast<char>(ch));
if (ch == EOF) return ferror(stdin) ? 1 : 0;
id record = line.size() <= maxClientFrame ? parse(line.data(), line.size()) : nil;
if ([record isKindOfClass:NSArray.class] && [record count] && [version isEqual:@"2025-03-26"]) {
// March requires batch reception. Stream one result at a time so a batch of
// large tool responses cannot exhaust the helper's memory.
bool emitted = false;
for (id item in record) {
@autoreleasepool {
NSDictionary *reply = handle(item, grant, loopback, tools, phase, version);
if (!reply) continue;
NSData *out = jsonBytes(reply);
if (!out || putchar(emitted ? ',' : '[') == EOF ||
fwrite(out.bytes, 1, out.length, stdout) != out.length) return 1;
emitted = true;
}
}
if (emitted && (fputs("]\n", stdout) == EOF || fflush(stdout))) return 1;
continue;
}
NSDictionary *reply;
if (line.size() > maxClientFrame) reply = rpcError(nil, -32600, @"Request exceeds 64 KiB");
else reply = record ? handle(record, grant, loopback, tools, phase, version) : rpcError(nil, -32700, @"Invalid JSON");
if (reply) {
NSData *out = jsonBytes(reply);
if (!out || fwrite(out.bytes, 1, out.length, stdout) != out.length || putchar('\n') == EOF || fflush(stdout)) return 1;
}
}
}
}
}