Harden Harness runtime, persistence and execution for Hand

This commit is contained in:
sausheong committed 2026-09-09 22:55:55 +08:00
1 parent 09c30fe2d5
commit 0972eed3ea
164 files changed
+15912 -506

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
//go:build darwin || linux
package mcp
import (
"context"
"errors"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"testing"
"time"
)
func TestCancelledHandshakeReapsChildPromptly(t *testing.T) {
path := filepath.Join(t.TempDir(), "pid")
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
start := time.Now()
cli, err := Connect(ctx, ServerConfig{Name: "hung", Command: "sh", Args: []string{"-c", `echo $$ > "$1"; exec sleep 30`, "fixture", path}})
elapsed := time.Since(start)
if cli != nil {
cli.Close()
t.Fatal("hung handshake connected")
}
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("connect error %v", err)
}
data, readErr := os.ReadFile(path)
if readErr != nil {
t.Fatal(readErr)
}
pid, parseErr := strconv.Atoi(strings.TrimSpace(string(data)))
if parseErr != nil {
t.Fatal(parseErr)
}
aliveErr := syscall.Kill(pid, 0)
if aliveErr == nil {
syscall.Kill(pid, syscall.SIGKILL)
t.Fatal("connection returned with child still alive")
}
if !errors.Is(aliveErr, syscall.ESRCH) {
t.Fatalf("child status %v", aliveErr)
}
if elapsed > 2*time.Second {
t.Fatalf("cancelled handshake took %s", elapsed)
}
}
+19 -12
View File
@@ -24,9 +24,11 @@ import (
"fmt"
"net/http"
"os"
"os/exec"
"sync"
"time"
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/sausheong/harness/process"
"github.com/sausheong/harness/tool"
)
@@ -34,6 +36,10 @@ import (
// transport must be specified: Command (stdio, the most common) or URL
// (Streamable HTTP via the SDK's StreamableClientTransport).
type ServerConfig struct {
// Optional permits construction to continue when this server fails.
Optional bool
// ConnectTimeout bounds this server; optional servers default to five seconds.
ConnectTimeout time.Duration
// Name namespaces the server's tools. Adapter tool names become
// "mcp__<Name>__<tool>" — the conventional double-underscore
// scheme that prevents collisions with built-in tools.
@@ -71,16 +77,20 @@ type ServerConfig struct {
// Client is a connected MCP server with its discovered tools adapted as
// harness tool.Tool implementations.
type Client struct {
name string
session *sdk.ClientSession
tools []tool.Tool
closed bool
name string
session *sdk.ClientSession
tools []tool.Tool
closeOnce sync.Once
closeErr error
}
// Connect opens a session to the MCP server in cfg, lists its tools,
// and adapts each into a tool.Tool. Returned Client owns the session;
// call Close to release it.
func Connect(ctx context.Context, cfg ServerConfig) (*Client, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if cfg.Name == "" {
return nil, fmt.Errorf("mcp: ServerConfig.Name is required")
}
@@ -135,11 +145,8 @@ func (c *Client) Ping(ctx context.Context) error {
// Close releases the underlying MCP session. Safe to call multiple
// times — subsequent calls are no-ops.
func (c *Client) Close() error {
if c.closed {
return nil
}
c.closed = true
return c.session.Close()
c.closeOnce.Do(func() { c.closeErr = c.session.Close() })
return c.closeErr
}
// buildTransport selects a transport based on cfg. stdio uses
@@ -149,9 +156,9 @@ func (c *Client) Close() error {
// applied via wrapHTTPClient.
func buildTransport(cfg ServerConfig) (sdk.Transport, error) {
if cfg.Command != "" {
cmd := exec.Command(cfg.Command, cfg.Args...)
cmd := process.Command(context.Background(), cfg.Command, cfg.Args...)
cmd.Env = mergeEnv(os.Environ(), cfg.Env)
return &sdk.CommandTransport{Command: cmd}, nil
return &managedCommandTransport{CommandTransport: sdk.CommandTransport{Command: cmd, TerminateDuration: 250 * time.Millisecond}}, nil
}
return &sdk.StreamableClientTransport{
Endpoint: cfg.URL,
+39
View File
@@ -0,0 +1,39 @@
package mcp
import (
"context"
"os/exec"
"sync"
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/sausheong/harness/process"
)
type managedCommandTransport struct{ sdk.CommandTransport }
func (t *managedCommandTransport) Connect(ctx context.Context) (sdk.Connection, error) {
conn, err := t.CommandTransport.Connect(ctx)
if err != nil {
return nil, err
}
return &managedCommandConnection{Connection: conn, command: t.Command}, nil
}
type managedCommandConnection struct {
sdk.Connection
command *exec.Cmd
once sync.Once
closeErr error
}
func (c *managedCommandConnection) Close() error {
c.once.Do(func() {
// Let the SDK close stdin and join the server first, then remove any
// descendants it left behind. WaitDelay bounds inherited-pipe draining.
c.closeErr = c.Connection.Close()
if err := process.KillGroup(c.command); c.closeErr == nil {
c.closeErr = err
}
})
return c.closeErr
}