From a5410393a70876ab6965fb1b5426a32c31fde17c Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 21:09:20 +0000 Subject: [PATCH 1/3] Add native MCP action to Go worker Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- internal/cli/serve.go | 1 + internal/computers/mcp.go | 30 +++++- internal/worker/mcp.go | 21 ++++- internal/worker/mcp_test.go | 60 ++++++++++++ internal/worker/mcpnative.go | 164 +++++++++++++++++++++++++++++++++ internal/worker/worker_test.go | 13 +++ 6 files changed, 286 insertions(+), 3 deletions(-) create mode 100644 internal/worker/mcpnative.go diff --git a/internal/cli/serve.go b/internal/cli/serve.go index b9d9128..85603a0 100644 --- a/internal/cli/serve.go +++ b/internal/cli/serve.go @@ -227,6 +227,7 @@ func serve(ctx context.Context, args []string, stdout io.Writer) error { server.RegisterWork(procedures, bots, runtime, work) connections := mcp.NewService(records, credentials, nil) connections.Runner = catalog.MCPRunner() + connections.Catalog = catalog.NativeCatalog service.MCP = connections service.Files = server.AgentFiles(bots.Files) if !*headless { diff --git a/internal/computers/mcp.go b/internal/computers/mcp.go index 8506530..952c516 100644 --- a/internal/computers/mcp.go +++ b/internal/computers/mcp.go @@ -46,7 +46,7 @@ func (c *Catalog) MCP(ctx context.Context, computerID string, botID int64, input if botID == 0 { return worker.MCPResult{}, rpc.NewError("BAD_REQUEST", "请先为此电脑分配 Bot,再测试 MCP。") } - transport, _, err := c.target(*item).transport(botID) + transport, workDir, err := c.target(*item).transport(botID) if err != nil { return worker.MCPResult{}, err } @@ -55,6 +55,9 @@ func (c *Catalog) MCP(ctx context.Context, computerID string, botID int64, input return worker.MCPResult{}, err } defer func() { _ = client.Close() }() + if input.Action == "native" { + input.Cwd = workDir + } return client.MCP(ctx, input, nil) } @@ -113,3 +116,28 @@ func present(raw json.RawMessage) json.RawMessage { } return raw } + +// NativeCatalog reads the Bot's native Harness connections on its work +// computer, as open-agent.ts nativeCatalog. +func (c *Catalog) NativeCatalog(ctx context.Context, botID int64) (mcp.NativeCatalog, error) { + engine, _, err := agent.Snapshot(ctx, c.h, agent.EngineDoc, botID) + if err != nil { + return mcp.NativeCatalog{}, err + } + if engine.ComputerID == nil { + return mcp.NativeCatalog{}, errors.New("请先选择 Bot 的工作电脑和 Harness。") + } + result, err := c.MCP(ctx, *engine.ComputerID, botID, worker.MCPInput{ + Action: "native", + Config: &worker.MCPConfig{Provider: engine.Config.Provider}, + }) + if err != nil { + return mcp.NativeCatalog{}, err + } + items := make([]mcp.NativeItem, len(result.Items)) + for i, item := range result.Items { + items[i] = mcp.NativeItem{Name: item.Name, Source: item.Source, Enabled: item.Enabled, Status: item.Status} + } + return mcp.NativeCatalog{Provider: engine.Config.Provider, ComputerID: *engine.ComputerID, + Items: items, Inheritance: result.Inheritance, Readonly: result.Readonly}, nil +} diff --git a/internal/worker/mcp.go b/internal/worker/mcp.go index 48cab55..07c801e 100644 --- a/internal/worker/mcp.go +++ b/internal/worker/mcp.go @@ -20,6 +20,7 @@ import ( // MCPConfig is a saved MCP connection: a stdio program or an HTTP endpoint. type MCPConfig struct { + Provider string `json:"provider,omitempty"` Transport string `json:"transport"` Command string `json:"command,omitempty"` Args []string `json:"args,omitempty"` @@ -29,11 +30,13 @@ type MCPConfig struct { } // MCPInput is one managed MCP operation, in the shape the TypeScript worker -// accepted: inspect, connect, request, disconnect, authorize or complete. +// accepted: inspect, connect, request, disconnect, authorize, complete or +// native. Config holds the connection config or native Harness config. type MCPInput struct { Action string `json:"action"` ID string `json:"id,omitempty"` Config *MCPConfig `json:"config,omitempty"` + Cwd string `json:"cwd,omitempty"` OAuth *OAuthState `json:"oauth,omitempty"` RedirectURL string `json:"redirectUrl,omitempty"` State string `json:"state,omitempty"` @@ -43,13 +46,25 @@ type MCPInput struct { } // MCPResult answers an MCPInput. OAuth is the connection's OAuth state after -// the operation, which the service stores again. +// the operation, which the service stores again. Items, Inheritance and +// Readonly answer a "native" operation. type MCPResult struct { Capabilities *mcp.ServerCapabilities `json:"capabilities,omitempty"` Tools []*mcp.Tool `json:"tools"` Result json.RawMessage `json:"result,omitempty"` AuthorizationURL string `json:"authorizationUrl,omitempty"` OAuth *OAuthState `json:"oauth"` + Items []MCPNativeItem `json:"items,omitempty"` + Inheritance string `json:"inheritance,omitempty"` + Readonly bool `json:"readonly,omitempty"` +} + +// MCPNativeItem is one connection the Bot's native Harness configures itself. +type MCPNativeItem struct { + Name string `json:"name"` + Source string `json:"source"` + Enabled bool `json:"enabled"` + Status string `json:"status"` } // MCPProgress is a progress notification for a forwarded request. @@ -94,6 +109,8 @@ func (s *server) mcp(ctx context.Context, id uint32, input MCPInput) (*MCPResult func (s *server) mcpOperation(ctx context.Context, id uint32, input MCPInput) (*MCPResult, error) { switch input.Action { + case "native": + return nativeMCP(ctx, input.Config, input.Cwd) case "authorize", "complete": return authorizeMCP(ctx, input) case "request": diff --git a/internal/worker/mcp_test.go b/internal/worker/mcp_test.go index 45922c4..db76b68 100644 --- a/internal/worker/mcp_test.go +++ b/internal/worker/mcp_test.go @@ -137,6 +137,66 @@ func TestMCPStdio(t *testing.T) { } } +func TestMCPNativeCatalog(t *testing.T) { + clients, _ := mcpClients(t) + for name, client := range clients { + t.Run(name, func(t *testing.T) { + cwd := t.TempDir() + result, err := client.MCP(context.Background(), MCPInput{ + Action: "native", + Config: &MCPConfig{Provider: "pi", Command: executable(t)}, + Cwd: cwd, + }, nil) + if err != nil { + t.Fatal(err) + } + if len(result.Items) != 2 || result.Items[0].Name != "docs" || result.Items[0].Source != cwd || + result.Items[0].Enabled || result.Items[0].Status != "disabled" || + result.Items[1].Name != "local" || result.Items[1].Enabled != true { + t.Fatalf("native items = %+v", result.Items) + } + if result.Inheritance != "native" || !result.Readonly { + t.Fatalf("native catalog flags = inheritance %q, readonly %t", result.Inheritance, result.Readonly) + } + }) + } +} + +func TestParseNativeCatalogText(t *testing.T) { + tests := []struct { + provider string + output string + want []MCPNativeItem + }{ + { + provider: "claude", + output: "docs: connected\npersona: connected\n", + want: []MCPNativeItem{ + {Name: "docs", Source: "claude 用户/项目配置", Enabled: true, Status: "unknown"}, + }, + }, + { + provider: "opencode", + output: "\x1b[32m● docs connected\x1b[0m\n○ local disabled\npersona connected\n", + want: []MCPNativeItem{ + {Name: "docs", Source: "opencode 用户/项目配置", Enabled: true, Status: "connected"}, + {Name: "local", Source: "opencode 用户/项目配置", Enabled: false, Status: "disabled"}, + }, + }, + } + for _, test := range tests { + t.Run(test.provider, func(t *testing.T) { + items, err := parseNativeCatalog(test.provider, false, test.output) + if err != nil { + t.Fatal(err) + } + if fmt.Sprint(items) != fmt.Sprint(test.want) { + t.Fatalf("items = %+v, want %+v", items, test.want) + } + }) + } +} + // oauthServer is an MCP endpoint at /mcp behind OAuth with resource metadata, // dynamic registration and refresh, plus an unauthenticated legacy SSE endpoint. func oauthServer(t *testing.T) (*httptest.Server, *atomic.Value) { diff --git a/internal/worker/mcpnative.go b/internal/worker/mcpnative.go new file mode 100644 index 0000000..b64224b --- /dev/null +++ b/internal/worker/mcpnative.go @@ -0,0 +1,164 @@ +package worker + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "os" + "os/exec" + "regexp" + "strings" + "time" +) + +// nativeProgram is the default program each native Harness provides. +var nativeProgram = map[string]string{"claude": "claude", "codex": "codex", "pi": "pi", "opencode": "opencode"} + +// nativeOutputLimit bounds the catalog output, as the TypeScript worker does. +const nativeOutputLimit = 1 << 20 + +var errNativeOutputLarge = errors.New("native MCP catalog is too large") + +// nativeMCP lists the connections the Bot's native Harness configures on this +// work computer by running its "mcp list" command under the account +// environment, as packages/agent/src/harness/native-mcp.mjs does. +func nativeMCP(ctx context.Context, engine *MCPConfig, cwd string) (*MCPResult, error) { + if engine == nil { + return nil, codeError("EINVAL", "native MCP engine is missing", "") + } + program, known := nativeProgram[engine.Provider] + if !known { + return nil, codeError("EINVAL", "此 ACP 程序未提供原生 MCP 目录接口。", "") + } + command := engine.Command + if command == "" { + command = program + } + env := AccountEnvironment(os.Environ(), "", nil) + path, err := ResolveProgram(ctx, command, env) + if err != nil { + return nil, err + } + if path == "" { + return nil, codeError("ENOENT", "工作电脑未安装所选 Harness。", command) + } + args := []string{"mcp", "list"} + jsonOutput := engine.Provider == "codex" || engine.Provider == "pi" + if jsonOutput { + args = append(args, "--json") + } + run, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + var out bytes.Buffer + cmd := exec.CommandContext(run, path, args...) + cmd.Env, cmd.Stderr = env, io.Discard + cmd.Dir = cwd + cmd.Stdout = &nativeOutputWriter{buf: &out, limit: nativeOutputLimit} + err = cmd.Run() + switch { + case ctx.Err() != nil: + return nil, ctx.Err() + case errors.Is(err, errNativeOutputLarge): + return nil, codeError("EFBIG", "原生 MCP 目录过大。", "") + case run.Err() != nil: + return nil, codeError("timeout", "原生 MCP 目录读取超时。", "") + case err != nil && out.Len() == 0: + return nil, codeError("MCP_FAILED", "原生 MCP 目录不可用。", "") + } + items, err := parseNativeCatalog(engine.Provider, jsonOutput, out.String()) + if err != nil { + return nil, err + } + inheritance := "native" + if engine.Provider == "claude" { + inheritance = "selectable" + } + return &MCPResult{Items: items, Inheritance: inheritance, Readonly: true}, nil +} + +type nativeOutputWriter struct { + buf *bytes.Buffer + limit int +} + +func (w *nativeOutputWriter) Write(p []byte) (int, error) { + if w.buf.Len()+len(p) > w.limit { + return 0, errNativeOutputLarge + } + return w.buf.Write(p) +} + +var ( + vtControl = regexp.MustCompile(`\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\)|[@-Z\\-_])`) + claudeLine = regexp.MustCompile(`^([\w.-]+):\s`) + opencodeLine = regexp.MustCompile(`[●○]\s+([\w.-]+)\s+(connected|disabled|failed|needs_auth)`) +) + +// parseNativeCatalog reads the "mcp list" output into catalog items and drops +// the Persona entry. +func parseNativeCatalog(provider string, jsonOutput bool, output string) ([]MCPNativeItem, error) { + source := provider + " 用户/项目配置" + var items []MCPNativeItem + if jsonOutput { + var raw any + if err := json.Unmarshal([]byte(output), &raw); err != nil { + return nil, codeError("EINVAL", "原生 MCP 目录不是有效的 JSON。", "") + } + var entries []map[string]any + switch value := raw.(type) { + case []any: + entries = toMaps(value) + case map[string]any: + if servers, ok := value["servers"].([]any); ok { + entries = toMaps(servers) + } + } + for _, entry := range entries { + name, _ := entry["name"].(string) + item := MCPNativeItem{Name: name, Source: source, Enabled: true, Status: "unknown"} + if s, ok := entry["source"].(string); ok { + item.Source = s + } + if enabled, ok := entry["enabled"].(bool); ok { + item.Enabled = enabled + } + if status, ok := entry["state"].(string); ok { + item.Status = status + } + items = append(items, item) + } + } else { + text := vtControl.ReplaceAllString(output, "") + for _, line := range strings.Split(text, "\n") { + line = strings.TrimRight(line, "\r") + if provider == "claude" { + if m := claudeLine.FindStringSubmatch(line); m != nil { + items = append(items, MCPNativeItem{Name: m[1], Source: source, Enabled: true, Status: "unknown"}) + } + continue + } + if m := opencodeLine.FindStringSubmatch(line); m != nil { + items = append(items, MCPNativeItem{Name: m[1], Source: source, Enabled: m[2] != "disabled", Status: m[2]}) + } + } + } + kept := items[:0] + for _, item := range items { + if item.Name != "persona" { + kept = append(kept, item) + } + } + return kept, nil +} + +func toMaps(values []any) []map[string]any { + var out []map[string]any + for _, value := range values { + if m, ok := value.(map[string]any); ok { + out = append(out, m) + } + } + return out +} diff --git a/internal/worker/worker_test.go b/internal/worker/worker_test.go index 6e0780a..dcea6b8 100644 --- a/internal/worker/worker_test.go +++ b/internal/worker/worker_test.go @@ -26,6 +26,10 @@ import ( // TestMain lets the test binary act as the persona binary and as a portable cat. func TestMain(m *testing.M) { if len(os.Args) > 1 { + if os.Args[1] == "mcp" && len(os.Args) > 2 && os.Args[2] == "list" { + fmt.Fprintf(os.Stdout, `[{"name":"persona"},{"name":"docs","source":%q,"enabled":false,"state":"disabled"},{"name":"local","state":"connected"}]`, mustGetwd()) + os.Exit(0) + } switch os.Args[1] { case "worker": if err := Main(context.Background(), os.Args[2:], os.Stdin, os.Stdout, os.Stderr); err != nil { @@ -69,6 +73,15 @@ func TestMain(m *testing.M) { os.Exit(m.Run()) } +func mustGetwd() string { + cwd, err := os.Getwd() + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return cwd +} + func executable(t *testing.T) string { t.Helper() path, err := os.Executable() From cbf5f63bcc28c6de2b891d85682860d5de8d41a5 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 22:19:17 +0000 Subject: [PATCH 2/3] Keep native MCP cwd test portable Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- internal/worker/mcp_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/worker/mcp_test.go b/internal/worker/mcp_test.go index db76b68..d8db5fd 100644 --- a/internal/worker/mcp_test.go +++ b/internal/worker/mcp_test.go @@ -8,6 +8,7 @@ import ( "net/http/httptest" "net/url" "os/exec" + "path/filepath" "strings" "sync" "sync/atomic" @@ -142,6 +143,9 @@ func TestMCPNativeCatalog(t *testing.T) { for name, client := range clients { t.Run(name, func(t *testing.T) { cwd := t.TempDir() + if resolved, err := filepath.EvalSymlinks(cwd); err == nil { + cwd = resolved + } result, err := client.MCP(context.Background(), MCPInput{ Action: "native", Config: &MCPConfig{Provider: "pi", Command: executable(t)}, From fdc8dbeee620c92835568a388afcb9cda701eabb Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 07:14:32 +0000 Subject: [PATCH 3/3] Read the Bot's work computer from its binding in the native MCP catalog The engine document's computerId is only written when the engine runs, so Bots configured through Assign but not yet run, and Bots whose assignment changed after their last session, resolved the wrong computer. The computers binding is the source switchSession mirrors. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- internal/computers/mcp.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/internal/computers/mcp.go b/internal/computers/mcp.go index 952c516..882ddc2 100644 --- a/internal/computers/mcp.go +++ b/internal/computers/mcp.go @@ -124,10 +124,17 @@ func (c *Catalog) NativeCatalog(ctx context.Context, botID int64) (mcp.NativeCat if err != nil { return mcp.NativeCatalog{}, err } - if engine.ComputerID == nil { + // The Bot's work computer is its computers binding, which Assign owns; + // switchSession only mirrors it into the engine document when the engine + // runs, so a Bot configured without a run still has no computerId there. + computerID, err := c.ComputerID(ctx, botID) + if err != nil { + return mcp.NativeCatalog{}, err + } + if computerID == nil { return mcp.NativeCatalog{}, errors.New("请先选择 Bot 的工作电脑和 Harness。") } - result, err := c.MCP(ctx, *engine.ComputerID, botID, worker.MCPInput{ + result, err := c.MCP(ctx, *computerID, botID, worker.MCPInput{ Action: "native", Config: &worker.MCPConfig{Provider: engine.Config.Provider}, }) @@ -138,6 +145,6 @@ func (c *Catalog) NativeCatalog(ctx context.Context, botID int64) (mcp.NativeCat for i, item := range result.Items { items[i] = mcp.NativeItem{Name: item.Name, Source: item.Source, Enabled: item.Enabled, Status: item.Status} } - return mcp.NativeCatalog{Provider: engine.Config.Provider, ComputerID: *engine.ComputerID, + return mcp.NativeCatalog{Provider: engine.Config.Provider, ComputerID: *computerID, Items: items, Inheritance: result.Inheritance, Readonly: result.Readonly}, nil }