use harn_serve::adapters::acp::{
ACP_SCHEMA_COMPATIBILITY, HARN_AGENT_EVENT_KINDS, HARN_AGENT_EVENT_METHOD,
HARN_CONTENT_EXTENSION_FIELDS, HARN_PROVIDER_CATALOG_METHOD, HARN_SESSION_UPDATE_EXTENSIONS,
HARN_TOOL_LIFECYCLE_EXTENSION_FIELDS,
};
use harn_serve::{A2A_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION};
use harn_vm::llm::receipts::{TOOL_CALL_RECEIPT_EXECUTORS, TOOL_CALL_RECEIPT_STATUSES};
use super::constants::*;
use super::support::*;
use super::values::*;
pub(super) fn generate_go() -> String {
let mut out = String::new();
out.push_str("// GENERATED by `harn dump-protocol-artifacts` - do not edit by hand.\n");
out.push_str("// Source: Harn adapter schemas and Rust wire vocabulary.\n\n");
out.push_str("// Package harnprotocol mirrors the host/integrator surface generated for\n");
out.push_str("// TypeScript, Swift, and Python. Field names match the wire JSON; optional\n");
out.push_str("// fields use pointer types or `omitempty` so encoding/json round-trips\n");
out.push_str("// produce minimal envelopes equivalent to the Rust adapters.\n");
out.push_str("package harnprotocol\n\n");
out.push_str("import \"encoding/json\"\n\n");
for (doc, name, value) in [
(
"// ArtifactVersion pins the Harn release that generated this binding.\n",
"ArtifactVersion",
env!("CARGO_PKG_VERSION"),
),
(
"// HarnAgentEventMethod is the JSON-RPC method for `_harn/agentEvent` notifications.\n",
"HarnAgentEventMethod",
HARN_AGENT_EVENT_METHOD,
),
(
"// HarnProviderCatalogMethod is the JSON-RPC method for Harn's provider catalog extension.\n",
"HarnProviderCatalogMethod",
HARN_PROVIDER_CATALOG_METHOD,
),
(
"// ACPSchemaCompatibility is the upstream ACP schema version Harn tracks.\n",
"ACPSchemaCompatibility",
ACP_SCHEMA_COMPATIBILITY,
),
(
"// A2AProtocolVersion is the A2A protocol version Harn implements.\n",
"A2AProtocolVersion",
A2A_PROTOCOL_VERSION,
),
(
"// MCPProtocolVersion is the MCP protocol version Harn implements.\n",
"MCPProtocolVersion",
MCP_PROTOCOL_VERSION,
),
(
"// MCPStableProtocolVersion is the stable MCP protocol version Harn implements at runtime.\n",
"MCPStableProtocolVersion",
MCP_PROTOCOL_VERSION,
),
(
"// MCPDraftProtocolVersion is the opt-in MCP release-candidate profile identity.\n",
"MCPDraftProtocolVersion",
MCP_DRAFT_PROTOCOL_VERSION,
),
(
"// MCPFinal2026ProtocolVersion is the scheduled final identity for the RC profile.\n",
"MCPFinal2026ProtocolVersion",
MCP_FINAL_2026_PROTOCOL_VERSION,
),
(
"// MCPJSONSchema202012Dialect is the JSON Schema dialect used by the MCP RC artifact profile.\n",
"MCPJSONSchema202012Dialect",
MCP_JSON_SCHEMA_2020_12_DIALECT,
),
(
"// MCPInputRequiredResultType is the resultType discriminator for multi round-trip requests.\n",
"MCPInputRequiredResultType",
MCP_INPUT_REQUIRED_RESULT_TYPE,
),
(
"// MCPUnsupportedProtocolVersionErrorMessage is the standard message for unsupported versions.\n",
"MCPUnsupportedProtocolVersionErrorMessage",
MCP_UNSUPPORTED_PROTOCOL_VERSION_ERROR_MESSAGE,
),
] {
out.push_str(doc);
out.push_str(&format!(
"const {name} = {}\n\n",
json_string_literal(value)
));
}
out.push_str(&format!(
"// MCPUnsupportedProtocolVersionErrorCode is the JSON-RPC server error for unsupported versions.\nconst MCPUnsupportedProtocolVersionErrorCode = {MCP_UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE}\n\n"
));
out.push_str(&go_typed_array(
"ACPAgentMethod",
"ACPAgentMethods",
ACP_AGENT_METHODS,
));
out.push_str(&go_typed_array(
"ACPClientMethod",
"ACPClientMethods",
ACP_CLIENT_METHODS,
));
out.push_str(&go_typed_array(
"ACPAgentNotification",
"ACPAgentNotifications",
ACP_AGENT_NOTIFICATIONS,
));
let session_updates = all_acp_session_updates();
out.push_str(&go_typed_array_owned(
"ACPSessionUpdate",
"ACPSessionUpdates",
&session_updates,
));
out.push_str(&go_typed_array(
"HarnACPSessionUpdateExtension",
"HarnACPSessionUpdateExtensions",
HARN_SESSION_UPDATE_EXTENSIONS,
));
out.push_str(&go_typed_array(
"HarnAgentEventKind",
"HarnAgentEventKinds",
HARN_AGENT_EVENT_KINDS,
));
out.push_str(&go_typed_array(
"ACPContentBlockType",
"ACPContentBlockTypes",
ACP_CONTENT_BLOCK_TYPES,
));
out.push_str(&go_typed_array_owned(
"ACPToolKind",
"ACPToolKinds",
&tool_kind_values(),
));
out.push_str(&go_typed_array_owned(
"ACPToolCallStatus",
"ACPToolCallStatuses",
&tool_call_status_values(),
));
out.push_str(&go_typed_array_owned(
"HarnToolCallErrorCategory",
"HarnToolCallErrorCategories",
&tool_call_error_category_values(),
));
out.push_str(&go_typed_array_owned(
"HarnSideEffectLevel",
"HarnSideEffectLevels",
&side_effect_level_values(),
));
out.push_str(&go_typed_array_owned(
"HarnWorkerStatus",
"HarnWorkerStatuses",
&worker_status_values(),
));
out.push_str(&go_typed_array(
"ToolCallReceiptStatus",
"ToolCallReceiptStatuses",
TOOL_CALL_RECEIPT_STATUSES,
));
out.push_str(&go_typed_array(
"ToolCallReceiptExecutor",
"ToolCallReceiptExecutors",
TOOL_CALL_RECEIPT_EXECUTORS,
));
out.push_str(&go_typed_array(
"A2ATaskState",
"A2ATaskStates",
A2A_TASK_STATES,
));
out.push_str(&go_typed_array(
"A2ATaskEventType",
"A2ATaskEventTypes",
A2A_TASK_EVENT_TYPES,
));
out.push_str(&go_typed_array(
"MCPProtocolVersionValue",
"MCPProtocolVersions",
MCP_PROTOCOL_VERSIONS,
));
out.push_str(&go_typed_array("MCPMethod", "MCPMethods", MCP_METHODS));
out.push_str(&go_typed_array(
"MCPCacheScope",
"MCPCacheScopes",
MCP_CACHE_SCOPES,
));
out.push_str(&go_typed_array(
"MCPResultType",
"MCPResultTypes",
MCP_RESULT_TYPES,
));
out.push_str(&go_typed_array(
"MCPLoggingLevel",
"MCPLoggingLevels",
MCP_LOGGING_LEVELS,
));
out.push_str(&go_string_array(
"HarnToolLifecycleExtensionFields",
HARN_TOOL_LIFECYCLE_EXTENSION_FIELDS,
));
out.push_str(&go_string_array(
"HarnContentExtensionFields",
HARN_CONTENT_EXTENSION_FIELDS,
));
out.push_str(&go_string_array("A2AMethods", A2A_METHODS));
out.push_str(&go_string_array(
"MCPRequiredMetadataKeys",
MCP_REQUIRED_METADATA_KEYS,
));
out.push_str(&go_string_array("MCPMetadataKeys", MCP_METADATA_KEYS));
out.push_str(&go_string_array(
"MCPStandardHTTPHeaders",
MCP_STANDARD_HTTP_HEADERS,
));
out.push_str(&go_string_array(
"MCPCacheResultFields",
MCP_CACHE_RESULT_FIELDS,
));
out.push_str(GO_TYPE_DEFINITIONS);
out
}
pub(super) const GO_TYPE_DEFINITIONS: &str = r#"// JSONValue is the Go counterpart of the TypeScript ACPValue / Python JsonValue
// type. Concrete fields generally use json.RawMessage so callers can defer
// decoding to their own dataclasses.
type JSONValue = json.RawMessage
// JSONObject mirrors `Record<string, JsonValue>`.
type JSONObject = map[string]json.RawMessage
// JSONRPCID encodes a JSON-RPC id, which may be an integer, a string, or null.
// Use NewJSONRPCIDInt / NewJSONRPCIDString to construct, or NullJSONRPCID for
// the null variant.
type JSONRPCID struct {
raw json.RawMessage
present bool
}
// NewJSONRPCIDInt builds a JSON-RPC id from an integer.
func NewJSONRPCIDInt(value int64) JSONRPCID {
bytes, _ := json.Marshal(value)
return JSONRPCID{raw: bytes, present: true}
}
// NewJSONRPCIDString builds a JSON-RPC id from a string.
func NewJSONRPCIDString(value string) JSONRPCID {
bytes, _ := json.Marshal(value)
return JSONRPCID{raw: bytes, present: true}
}
// NullJSONRPCID returns a JSON-RPC id explicitly encoded as null.
func NullJSONRPCID() JSONRPCID {
return JSONRPCID{raw: json.RawMessage("null"), present: true}
}
// IsPresent reports whether the id field was present on the wire.
func (id JSONRPCID) IsPresent() bool { return id.present }
// MarshalJSON implements json.Marshaler.
func (id JSONRPCID) MarshalJSON() ([]byte, error) {
if !id.present {
return []byte("null"), nil
}
return id.raw, nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (id *JSONRPCID) UnmarshalJSON(data []byte) error {
id.raw = append(id.raw[:0], data...)
id.present = true
return nil
}
// Raw exposes the encoded bytes for callers that need to inspect the variant.
func (id JSONRPCID) Raw() json.RawMessage { return id.raw }
// ACPRequest is a JSON-RPC request envelope.
type ACPRequest struct {
JSONRPC string `json:"jsonrpc"`
ID JSONRPCID `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
// ACPError is the JSON-RPC error sub-envelope.
type ACPError struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data,omitempty"`
}
// ACPResponse is a JSON-RPC response envelope.
type ACPResponse struct {
JSONRPC string `json:"jsonrpc"`
ID JSONRPCID `json:"id"`
Result json.RawMessage `json:"result,omitempty"`
Error *ACPError `json:"error,omitempty"`
}
// ACPNotification is a JSON-RPC notification envelope.
type ACPNotification struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
// HarnExtensionMeta is the canonical envelope for `_meta.harn` payloads.
type HarnExtensionMeta struct {
Harn JSONObject `json:"harn,omitempty"`
}
// ACPContentBlock is one element inside a session update or message content array.
type ACPContentBlock struct {
Type string `json:"type"`
Text *string `json:"text,omitempty"`
Meta *HarnExtensionMeta `json:"_meta,omitempty"`
}
// HarnToolLifecycleMeta is the Harn-specific tool-call lifecycle metadata
// living under `_meta.harn` on tool_call / tool_call_update notifications.
type HarnToolLifecycleMeta struct {
Audit json.RawMessage `json:"audit,omitempty"`
DurationMs *float64 `json:"durationMs,omitempty"`
Error *string `json:"error,omitempty"`
ErrorCategory *string `json:"errorCategory,omitempty"`
ExecutionDurationMs *float64 `json:"executionDurationMs,omitempty"`
Executor json.RawMessage `json:"executor,omitempty"`
Parsing *bool `json:"parsing,omitempty"`
RawInputPartial *string `json:"rawInputPartial,omitempty"`
}
// ToolCallReceipt is the typed, privacy-preserving receipt emitted for an
// audited tool call.
type ToolCallReceipt struct {
SchemaVersion int `json:"schema_version"`
SessionID string `json:"session_id"`
RunID *string `json:"run_id"`
ToolCallID string `json:"tool_call_id"`
ToolName string `json:"tool_name"`
Iteration uint64 `json:"iteration"`
TurnIndex *uint64 `json:"turn_index"`
EmitOrder uint64 `json:"emit_order"`
Reason *string `json:"reason"`
Kind *string `json:"kind"`
Executor *ToolCallReceiptExecutor `json:"executor"`
Status ToolCallReceiptStatus `json:"status"`
ErrorCategory *string `json:"error_category"`
DurationMs uint64 `json:"duration_ms"`
ArgsHash string `json:"args_hash"`
ResultHash *string `json:"result_hash"`
Audit json.RawMessage `json:"audit"`
EmittedAt string `json:"emitted_at"`
Model *string `json:"model"`
Provider *string `json:"provider"`
}
// ACPToolCall is the `tool_call` session update.
type ACPToolCall struct {
SessionUpdate string `json:"sessionUpdate"`
ToolCallID string `json:"toolCallId"`
Title string `json:"title"`
Kind *string `json:"kind,omitempty"`
Status *string `json:"status,omitempty"`
Content []ACPContentBlock `json:"content,omitempty"`
Locations []json.RawMessage `json:"locations,omitempty"`
RawInput json.RawMessage `json:"rawInput,omitempty"`
RawOutput json.RawMessage `json:"rawOutput,omitempty"`
Meta *HarnExtensionMeta `json:"_meta,omitempty"`
}
// ACPToolCallUpdate is the `tool_call_update` session update.
type ACPToolCallUpdate struct {
SessionUpdate string `json:"sessionUpdate"`
ToolCallID string `json:"toolCallId"`
Title *string `json:"title,omitempty"`
Kind *string `json:"kind,omitempty"`
Status *string `json:"status,omitempty"`
Content []ACPContentBlock `json:"content,omitempty"`
Locations []json.RawMessage `json:"locations,omitempty"`
RawInput json.RawMessage `json:"rawInput,omitempty"`
RawOutput json.RawMessage `json:"rawOutput,omitempty"`
Meta *HarnExtensionMeta `json:"_meta,omitempty"`
}
// ACPSessionUpdateEnvelope is the discriminated `update` payload carried inside
// an ACP `session/update` notification. Only fields relevant to a given
// `sessionUpdate` discriminator will be populated; the rest stay zero-value
// and are stripped via `omitempty` on serialization.
type ACPSessionUpdateEnvelope struct {
SessionUpdate string `json:"sessionUpdate"`
Content json.RawMessage `json:"content,omitempty"`
MessageID *string `json:"messageId,omitempty"`
Entries []json.RawMessage `json:"entries,omitempty"`
KeptTurnCount *int `json:"keptTurnCount,omitempty"`
RemovedTurnCount *int `json:"removedTurnCount,omitempty"`
NewTipTurnID *string `json:"newTipTurnId,omitempty"`
Reason *string `json:"reason,omitempty"`
ToolCallID *string `json:"toolCallId,omitempty"`
Title *string `json:"title,omitempty"`
Kind *string `json:"kind,omitempty"`
Status *string `json:"status,omitempty"`
RawInput json.RawMessage `json:"rawInput,omitempty"`
RawOutput json.RawMessage `json:"rawOutput,omitempty"`
Meta *HarnExtensionMeta `json:"_meta,omitempty"`
}
// ACPSessionUpdateParams is the params payload of `session/update`.
type ACPSessionUpdateParams struct {
SessionID string `json:"sessionId"`
Update ACPSessionUpdateEnvelope `json:"update"`
}
// ACPSessionUpdateNotification is the full `session/update` envelope.
type ACPSessionUpdateNotification struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params ACPSessionUpdateParams `json:"params"`
}
// HarnAgentEventNotification is the `_harn/agentEvent` envelope.
type HarnAgentEventNotification struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params JSONObject `json:"params"`
}
// HarnToolArgSchema describes the static slice of a Harn tool's argument shape.
type HarnToolArgSchema struct {
PathParams []string `json:"path_params"`
ArgAliases map[string]string `json:"arg_aliases"`
Required []string `json:"required"`
}
// HarnToolAnnotations describes Harn-side metadata for a tool.
type HarnToolAnnotations struct {
Kind string `json:"kind"`
SideEffectLevel string `json:"side_effect_level"`
ArgSchema HarnToolArgSchema `json:"arg_schema"`
Capabilities map[string][]string `json:"capabilities"`
EmitsArtifacts bool `json:"emits_artifacts"`
ResultReaders []string `json:"result_readers"`
InlineResult bool `json:"inline_result"`
}
// A2AMessage is one message inside an A2A task history.
type A2AMessage struct {
ID string `json:"id"`
Role string `json:"role"`
Parts []json.RawMessage `json:"parts"`
}
// A2ATaskStatus is the status block on an A2A task.
type A2ATaskStatus struct {
State string `json:"state"`
Message *A2AMessage `json:"message,omitempty"`
Timestamp *string `json:"timestamp,omitempty"`
}
// A2ATask is the canonical A2A task envelope.
type A2ATask struct {
ID string `json:"id"`
ContextID *string `json:"contextId,omitempty"`
Status A2ATaskStatus `json:"status"`
History []A2AMessage `json:"history,omitempty"`
Artifacts []json.RawMessage `json:"artifacts,omitempty"`
Metadata JSONObject `json:"metadata,omitempty"`
}
// MCPJSONSchema202012 is the JSON Schema dialect surface used by the MCP RC
// tool input/output schema profile.
type MCPJSONSchema202012 = JSONObject
// MCPImplementation describes an MCP client or server implementation.
type MCPImplementation struct {
Name string `json:"name"`
Version string `json:"version"`
Title *string `json:"title,omitempty"`
Description *string `json:"description,omitempty"`
WebsiteURL *string `json:"websiteUrl,omitempty"`
}
// MCPRequestMeta is the per-request metadata required by the MCP RC profile.
type MCPRequestMeta struct {
ProtocolVersion string `json:"io.modelcontextprotocol/protocolVersion"`
ClientInfo MCPImplementation `json:"io.modelcontextprotocol/clientInfo"`
ClientCapabilities JSONObject `json:"io.modelcontextprotocol/clientCapabilities"`
LogLevel *MCPLoggingLevel `json:"io.modelcontextprotocol/logLevel,omitempty"`
ProgressToken json.RawMessage `json:"progressToken,omitempty"`
Traceparent *string `json:"traceparent,omitempty"`
Tracestate *string `json:"tracestate,omitempty"`
Baggage *string `json:"baggage,omitempty"`
}
// MCPHTTPHeaders names the HTTP headers used by the MCP RC Streamable HTTP profile.
type MCPHTTPHeaders struct {
ProtocolVersion string `json:"MCP-Protocol-Version"`
Method string `json:"Mcp-Method"`
Name *string `json:"Mcp-Name,omitempty"`
}
// MCPCacheHints captures the RC ttlMs/cacheScope cache fields.
type MCPCacheHints struct {
TTLMS uint64 `json:"ttlMs"`
CacheScope MCPCacheScope `json:"cacheScope"`
}
// MCPDiscoverResult is the result returned by server/discover.
type MCPDiscoverResult struct {
ResultType MCPResultType `json:"resultType"`
SupportedVersions []string `json:"supportedVersions"`
Capabilities JSONObject `json:"capabilities"`
ServerInfo MCPImplementation `json:"serverInfo"`
Instructions *string `json:"instructions,omitempty"`
Meta JSONObject `json:"_meta,omitempty"`
}
// MCPInputRequiredResult carries server-to-client requests for multi round-trip calls.
type MCPInputRequiredResult struct {
ResultType MCPResultType `json:"resultType"`
InputRequests JSONObject `json:"inputRequests,omitempty"`
RequestState *string `json:"requestState,omitempty"`
Meta JSONObject `json:"_meta,omitempty"`
}
// MCPUnsupportedProtocolVersionErrorData is the typed data payload for -32004.
type MCPUnsupportedProtocolVersionErrorData struct {
Requested string `json:"requested"`
Supported []string `json:"supported"`
}
// MCPUnsupportedProtocolVersionError is the JSON-RPC error response shape for
// an unsupported MCP protocol version.
type MCPUnsupportedProtocolVersionError struct {
JSONRPC string `json:"jsonrpc"`
ID JSONRPCID `json:"id,omitempty"`
Error ACPError `json:"error"`
}
// MCPTool is the MCP `tools/list` entry.
type MCPTool struct {
Name string `json:"name"`
Title *string `json:"title,omitempty"`
Description *string `json:"description,omitempty"`
InputSchema MCPJSONSchema202012 `json:"inputSchema"`
OutputSchema MCPJSONSchema202012 `json:"outputSchema,omitempty"`
Annotations JSONObject `json:"annotations,omitempty"`
}
// MCPResource is the MCP `resources/list` entry.
type MCPResource struct {
URI string `json:"uri"`
Name string `json:"name"`
Title *string `json:"title,omitempty"`
Description *string `json:"description,omitempty"`
MimeType *string `json:"mimeType,omitempty"`
}
// MCPResourceTemplate is the MCP `resources/templates/list` entry.
type MCPResourceTemplate struct {
URITemplate string `json:"uriTemplate"`
Name string `json:"name"`
Title *string `json:"title,omitempty"`
Description *string `json:"description,omitempty"`
MimeType *string `json:"mimeType,omitempty"`
}
// MCPPrompt is the MCP `prompts/list` entry.
type MCPPrompt struct {
Name string `json:"name"`
Title *string `json:"title,omitempty"`
Description *string `json:"description,omitempty"`
Arguments []JSONObject `json:"arguments,omitempty"`
}
// IsRequest reports whether a decoded JSON-RPC envelope is a request.
func IsRequest(envelope map[string]json.RawMessage) bool {
_, hasID := envelope["id"]
_, hasMethod := envelope["method"]
return hasID && hasMethod
}
// IsResponse reports whether a decoded JSON-RPC envelope is a response.
func IsResponse(envelope map[string]json.RawMessage) bool {
_, hasID := envelope["id"]
_, hasMethod := envelope["method"]
return hasID && !hasMethod
}
// IsNotification reports whether a decoded JSON-RPC envelope is a notification.
func IsNotification(envelope map[string]json.RawMessage) bool {
_, hasID := envelope["id"]
_, hasMethod := envelope["method"]
return !hasID && hasMethod
}
"#;
pub(super) fn generate_go_mod() -> String {
"module github.com/burin-labs/harn/spec/protocol-artifacts/go/harnprotocol\n\n\
go 1.22\n"
.to_string()
}
pub(super) fn go_typed_array(type_name: &str, slice_name: &str, values: &[&str]) -> String {
go_typed_array_owned(type_name, slice_name, &strs_to_strings(values))
}
pub(super) fn go_typed_array_owned(type_name: &str, slice_name: &str, values: &[String]) -> String {
let mut out =
format!("// {type_name} is the typed alias for the {slice_name} wire vocabulary.\n");
out.push_str(&format!("type {type_name} = string\n\n"));
out.push_str(&format!(
"// {slice_name} enumerates every wire value Harn currently emits for {type_name}.\n"
));
out.push_str(&format!("var {slice_name} = []{type_name}{{\n"));
for value in values {
out.push('\t');
out.push_str(&json_string_literal(value));
out.push_str(",\n");
}
out.push_str("}\n\n");
out
}
pub(super) fn go_string_array(name: &str, values: &[&str]) -> String {
let mut out = format!("// {name} enumerates the wire values Harn currently emits.\n");
out.push_str(&format!("var {name} = []string{{\n"));
for value in values {
out.push('\t');
out.push_str(&json_string_literal(value));
out.push_str(",\n");
}
out.push_str("}\n\n");
out
}