Wire hexis.resolve_target to real Nexus, fix changes cursor, pass full execute fields over MCP

resolve_target previously returned a hardcoded "requires_nexus_resolution"
placeholder; it now calls Nexus's /api/v1/resolve via a new minimal
internal/nexusclient, configurable with -nexus (default localhost:8987).

/api/v1/changes ignored the since query param and always returned from
sequence 0 (`since = 0` regardless of what was parsed) — fixed to actually
parse and use it, so change-cursor polling works.

The MCP hexis.execute tool only forwarded capability_id/target_entity_id/
arguments/idempotency_key, silently dropping entity_version, requested_by,
origin, correlation_id, causation_id, resolution_evidence, and
confirmation_id even though the native HTTP API and domain.ExecuteRequest
already supported all of them — MCP callers now get full parity.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018ghELqYhZNLub2TXGMazqA
This commit is contained in:
kami
2026-07-20 11:28:13 +04:00
parent ed593efb71
commit 74b19e091e
5 changed files with 262 additions and 13 deletions
+10 -1
View File
@@ -12,6 +12,7 @@ import (
"github.com/kami/hexis/internal/api"
"github.com/kami/hexis/internal/execution"
"github.com/kami/hexis/internal/mcp"
"github.com/kami/hexis/internal/nexusclient"
"github.com/kami/hexis/internal/provider"
"github.com/kami/hexis/internal/storage"
)
@@ -22,12 +23,14 @@ func main() {
var mcpMode bool
var workspaceURL string
var workspaceAllowlist string
var nexusURL string
flag.StringVar(&httpAddr, "http", "", "HTTP listen address (default localhost:9741)")
flag.StringVar(&dataDir, "data", "", "Data directory for SQLite database")
flag.BoolVar(&mcpMode, "mcp", false, "Run in MCP stdio mode")
flag.StringVar(&workspaceURL, "workspace-url", "", "Workspace MCP HTTP API URL (e.g. http://localhost:9930)")
flag.StringVar(&workspaceAllowlist, "workspace-allowlist", "", "Path to workspace tool allowlist YAML")
flag.StringVar(&nexusURL, "nexus", "", "Nexus base URL for hexis.resolve_target (default http://localhost:8987)")
flag.Parse()
if dataDir == "" {
@@ -42,6 +45,12 @@ func main() {
if workspaceURL == "" {
workspaceURL = os.Getenv("WORKSPACE_MCP_URL")
}
if nexusURL == "" {
nexusURL = os.Getenv("HEXIS_NEXUS_URL")
}
if nexusURL == "" {
nexusURL = "http://localhost:8987"
}
dbPath := filepath.Join(dataDir, "hexis.db")
@@ -88,7 +97,7 @@ func main() {
if mcpMode {
log.Printf("starting MCP stdio adapter")
adapter := mcp.New(store, engine)
adapter := mcp.New(store, engine, nexusclient.New(nexusURL))
if err := adapter.ServeStdio(); err != nil {
log.Fatalf("MCP error: %v", err)
}
+7 -1
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"time"
@@ -334,7 +335,12 @@ func (h *Handler) handleChanges(w http.ResponseWriter, r *http.Request) {
seqStr := r.URL.Query().Get("since")
var since int64
if seqStr != "" {
since = 0
parsed, err := strconv.ParseInt(seqStr, 10, 64)
if err != nil {
writeJSON(w, http.StatusBadRequest, errorResponse("since must be an integer sequence"))
return
}
since = parsed
}
events, err := h.store.EventsAfter(since, 100)
+80
View File
@@ -0,0 +1,80 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"github.com/kami/hexis/internal/domain"
"github.com/kami/hexis/internal/execution"
"github.com/kami/hexis/internal/provider"
"github.com/kami/hexis/internal/storage"
)
func newTestHandler(t *testing.T) (*Handler, *storage.Store) {
t.Helper()
path := filepath.Join(t.TempDir(), "hexis.db")
store, err := storage.Open(path)
if err != nil {
t.Fatalf("open store: %v", err)
}
t.Cleanup(func() { store.Close() })
engine := execution.New(store, provider.NewRegistry())
return NewHandler(store, engine), store
}
// TestHandleChanges_SinceFiltersEvents verifies the `since` query param
// actually filters to events after that sequence number, rather than being
// silently reset to 0 (the bug: `since = 0` unconditionally, ignoring the
// parsed value).
func TestHandleChanges_SinceFiltersEvents(t *testing.T) {
h, store := newTestHandler(t)
for i := 0; i < 3; i++ {
if err := store.AppendEvent(&domain.Event{
ID: domain.NewEventID(),
Type: domain.EventCapabilityRegistered,
Timestamp: time.Now().UTC(),
}); err != nil {
t.Fatalf("append event %d: %v", i, err)
}
}
all, err := store.EventsAfter(0, 100)
if err != nil {
t.Fatalf("events after 0: %v", err)
}
if len(all) != 3 {
t.Fatalf("expected 3 seed events, got %d", len(all))
}
cutoff := all[0].Sequence
req := httptest.NewRequest(http.MethodGet, "/api/v1/changes?since="+itoa(cutoff), nil)
w := httptest.NewRecorder()
h.handleChanges(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
var events []*domain.Event
if err := json.Unmarshal(w.Body.Bytes(), &events); err != nil {
t.Fatalf("decode response: %v", err)
}
if len(events) != 2 {
t.Fatalf("expected 2 events after sequence %d, got %d", cutoff, len(events))
}
for _, e := range events {
if e.Sequence <= cutoff {
t.Errorf("event with sequence %d should have been excluded by since=%d", e.Sequence, cutoff)
}
}
}
func itoa(n int64) string {
b, _ := json.Marshal(n)
return string(b)
}
+85 -11
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/mark3labs/mcp-go/mcp"
@@ -11,6 +12,7 @@ import (
"github.com/kami/hexis/internal/domain"
"github.com/kami/hexis/internal/execution"
"github.com/kami/hexis/internal/nexusclient"
"github.com/kami/hexis/internal/storage"
)
@@ -18,12 +20,14 @@ type Adapter struct {
server *server.MCPServer
store storage.Interface
engine *execution.Engine
nexus nexusclient.Client
}
func New(store storage.Interface, engine *execution.Engine) *Adapter {
func New(store storage.Interface, engine *execution.Engine, nexus nexusclient.Client) *Adapter {
a := &Adapter{
store: store,
engine: engine,
nexus: nexus,
}
mcpServer := server.NewMCPServer(
@@ -75,6 +79,27 @@ func New(store storage.Interface, engine *execution.Engine) *Adapter {
mcp.WithString("idempotency_key",
mcp.Description("Idempotency key for safe retry"),
),
mcp.WithString("entity_version",
mcp.Description("Expected Nexus entity version, for optimistic concurrency"),
),
mcp.WithString("requested_by",
mcp.Description("JSON string describing the requester (e.g. {\"type\":\"user\",\"id\":\"...\"})"),
),
mcp.WithString("origin",
mcp.Description("JSON string describing the request origin (e.g. {\"system\":\"maven\",\"channel\":\"voice\"})"),
),
mcp.WithString("correlation_id",
mcp.Description("Correlation ID for cross-system tracing"),
),
mcp.WithString("causation_id",
mcp.Description("Causation ID of the event/request that triggered this execute"),
),
mcp.WithString("resolution_evidence",
mcp.Description("JSON array of evidence objects backing target_entity_id's resolution"),
),
mcp.WithString("confirmation_id",
mcp.Description("Confirmation ID for capabilities that require confirmation"),
),
), a.handleExecute)
mcpServer.AddTool(mcp.NewTool("hexis.execution_status",
@@ -167,13 +192,25 @@ func (a *Adapter) handleResolveTarget(ctx context.Context, req mcp.CallToolReque
if query == "" {
return mcp.NewToolResultError("query is required"), nil
}
if a.nexus == nil {
return mcp.NewToolResultError("resolve_target unavailable: no Nexus URL configured"), nil
}
// In a real setup, this would call Nexus API.
// For now, return a placeholder indicating Nexus resolution is needed.
result := map[string]any{
"query": query,
"status": "requires_nexus_resolution",
"message": "Connect to Nexus to resolve this query to a canonical entity ID",
var types []string
if capName := req.GetString("capability", ""); capName != "" {
if caps, err := a.store.ListCapabilities(""); err == nil {
for _, c := range caps {
if c.Name == capName {
types = c.TargetTypes
break
}
}
}
}
result, err := a.nexus.Resolve(ctx, query, types)
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("nexus resolve: %v", err)), nil
}
data, _ := json.MarshalIndent(result, "", " ")
@@ -199,11 +236,48 @@ func (a *Adapter) handleExecute(ctx context.Context, req mcp.CallToolRequest) (*
json.Unmarshal([]byte(argsStr), &args)
}
var entityVersion int64
if v := req.GetString("entity_version", ""); v != "" {
parsed, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("entity_version must be an integer: %v", err)), nil
}
entityVersion = parsed
}
var requestedBy map[string]string
if v := req.GetString("requested_by", ""); v != "" {
if err := json.Unmarshal([]byte(v), &requestedBy); err != nil {
return mcp.NewToolResultError(fmt.Sprintf("requested_by must be a JSON object: %v", err)), nil
}
}
var origin map[string]string
if v := req.GetString("origin", ""); v != "" {
if err := json.Unmarshal([]byte(v), &origin); err != nil {
return mcp.NewToolResultError(fmt.Sprintf("origin must be a JSON object: %v", err)), nil
}
}
var resolutionEvidence []map[string]any
if v := req.GetString("resolution_evidence", ""); v != "" {
if err := json.Unmarshal([]byte(v), &resolutionEvidence); err != nil {
return mcp.NewToolResultError(fmt.Sprintf("resolution_evidence must be a JSON array: %v", err)), nil
}
}
execReq := &domain.ExecuteRequest{
CapabilityID: capID,
TargetEntityID: targetID,
Arguments: args,
IdempotencyKey: idempKey,
CapabilityID: capID,
TargetEntityID: targetID,
EntityVersion: entityVersion,
Arguments: args,
RequestedBy: requestedBy,
Origin: origin,
IdempotencyKey: idempKey,
CorrelationID: req.GetString("correlation_id", ""),
CausationID: req.GetString("causation_id", ""),
ResolutionEvidence: resolutionEvidence,
ConfirmationID: req.GetString("confirmation_id", ""),
}
result, err := a.engine.Execute(execReq)
+80
View File
@@ -0,0 +1,80 @@
// Package nexusclient is the minimal Nexus resolve client used by Hexis's
// hexis.resolve_target MCP tool to turn a free-text query into a canonical
// entity ID, matching the /api/v1/resolve contract Nexus and Praxis already
// speak.
package nexusclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
type Entity struct {
ID string `json:"id"`
Type string `json:"type"`
DisplayName string `json:"display_name"`
}
type Candidate struct {
EntityID string `json:"entity_id"`
DisplayName string `json:"display_name"`
Score float64 `json:"score"`
}
type ResolveResult struct {
Status string `json:"status"`
Entity *Entity `json:"entity,omitempty"`
Score float64 `json:"score,omitempty"`
Candidates []Candidate `json:"candidates,omitempty"`
}
type Client interface {
Resolve(ctx context.Context, query string, types []string) (*ResolveResult, error)
}
type httpClient struct {
baseURL string
http *http.Client
}
func New(baseURL string) Client {
return &httpClient{baseURL: baseURL, http: &http.Client{Timeout: 10 * time.Second}}
}
func (c *httpClient) Resolve(ctx context.Context, query string, types []string) (*ResolveResult, error) {
body := map[string]any{"query": query}
if len(types) > 0 {
body["types"] = types
}
data, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/api/v1/resolve", bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Nexus-Version", "v1")
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("nexus resolve: %s", http.StatusText(resp.StatusCode))
}
var result ResolveResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("decode nexus resolve response: %w", err)
}
return &result, nil
}