package mcp import ( "encoding/json" "fmt" "sync" "time" ) // localReadTools answer from the server's own state (device hub, history, // audit file) and never open a channel to a client. Everything else is assumed // to act on one host, so a call that names an id takes that host's lock. var localReadTools = map[string]bool{ "list_hosts": true, "get_host_detail": true, "get_server_status": true, "get_audit_log": true, } // deviceLocks enforces one in-flight device operation per host. The lock is // per device, not per channel: the client can share state between the main // connection and its sub-connections, so overlapping commands only make the // situation harder to reason about (design ยง9). type deviceLocks struct { mu sync.Mutex held map[string]deviceHold } // deviceHold describes the call currently owning a device, so a rejection can // tell the caller who is in the way and for how long. type deviceHold struct { tool string since time.Time } func newDeviceLocks() *deviceLocks { return &deviceLocks{held: make(map[string]deviceHold)} } // tryAcquire takes the device lock without waiting. The second return value is // false when another call holds it; held then describes that call. func (l *deviceLocks) tryAcquire(deviceID, tool string) (held deviceHold, ok bool) { l.mu.Lock() defer l.mu.Unlock() if h, busy := l.held[deviceID]; busy { return h, false } l.held[deviceID] = deviceHold{tool: tool, since: time.Now()} return deviceHold{}, true } func (l *deviceLocks) release(deviceID string) { l.mu.Lock() delete(l.held, deviceID) l.mu.Unlock() } // deviceIDFromArgs extracts the one host a tool call targets. Tools with a // batch `ids` array are handled by their handler one id at a time (matching the // Win32 server); this function deliberately looks only at the single-host // spellings. func deviceIDFromArgs(raw json.RawMessage) string { if len(raw) == 0 || string(raw) == "null" { return "" } var args struct { ID string `json:"id"` DeviceID string `json:"device_id"` } if err := json.Unmarshal(raw, &args); err != nil { // Malformed arguments are reported by the handler as -32602; there is // no device to lock here. return "" } if args.ID != "" { return args.ID } return args.DeviceID } // busyMessage mirrors the Win32 server's -32003 text: // "Device busy: another request is pending for this host (tool=..., elapsed=Ns)". func busyMessage(held deviceHold) string { return fmt.Sprintf( "Device busy: another request is pending for this host (tool=%s, elapsed=%ds)", held.tool, int(time.Since(held.since).Seconds())) }