Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions internal/cli/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
37 changes: 36 additions & 1 deletion internal/computers/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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)
}

Expand Down Expand Up @@ -113,3 +116,35 @@ 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
}
// 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, *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: *computerID,
Items: items, Inheritance: result.Inheritance, Readonly: result.Readonly}, nil
}
21 changes: 19 additions & 2 deletions internal/worker/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand All @@ -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"`
Expand All @@ -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.
Expand Down Expand Up @@ -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":
Expand Down
64 changes: 64 additions & 0 deletions internal/worker/mcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http/httptest"
"net/url"
"os/exec"
"path/filepath"
"strings"
"sync"
"sync/atomic"
Expand Down Expand Up @@ -137,6 +138,69 @@ 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()
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)},
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) {
Expand Down
164 changes: 164 additions & 0 deletions internal/worker/mcpnative.go
Original file line number Diff line number Diff line change
@@ -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()
Comment on lines +55 to +59

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Catálogo MCP não carrega com CLIs instaladas pelo npm no Windows

Ao abrir o catálogo no Windows, ResolveProgram pode encontrar o atalho .cmd instalado pelo npm. O worker tenta executá-lo sem um interpretador, e a consulta falha mesmo com o Harness instalado.

Learn more

O worker encontra o programa antes de ler o catálogo. No Windows, ResolveProgram aceita o primeiro caminho retornado por where.exe que corresponda às extensões suportadas, inclusive .cmd e .bat. Esses arquivos são scripts em lote, não executáveis que o Windows possa iniciar diretamente. A versão TypeScript usa nativeMcp com cross-spawn, que trata esses scripts. O teste Go fornece executable, um binário, e não passa pelo caso de um atalho de npm.

Example: Em um computador Windows em que o programa pi é encontrado apenas como pi.cmd, selecione no painel um Bot cujo catálogo chega a esse computador. A consulta encontra a CLI, mas falha antes de executar mcp list --json.

Recommended fix: Trate .cmd e .bat em um helper de execução para Windows que os inicie por um interpretador com escape apropriado. Preserve o diretório do Bot, o ambiente, o cancelamento e o limite de saída. Adicione um teste Windows que passe um arquivo .cmd válido ao worker.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

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
}
13 changes: 13 additions & 0 deletions internal/worker/worker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
Expand Down
Loading