Skip to content

Agent Mesh

7.1 KB
Raw Blame
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package integration_test

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"testing"
	"time"

	"github.com/google/agentmesh/api"
	"github.com/modelcontextprotocol/go-sdk/mcp"
)

// tokenPath writes a secret to a temp file and returns its path: secret
// flags only accept file (or env) input.
func tokenPath(t *testing.T, secret string) string {
	t.Helper()
	p := filepath.Join(t.TempDir(), "secret")
	if err := os.WriteFile(p, []byte(secret), 0o600); err != nil {
		t.Fatalf("write secret file: %v", err)
	}
	return p
}

// svcDecl is one service entry for writeNodeConfig.
type svcDecl struct {
	Type      string
	Name      string
	TargetURL string
	Command   []string
}

// writeNodeConfig writes a node config declaring the node's operator labels
// and its static services, the only way to declare either.
func writeNodeConfig(t *testing.T, dir string, labels map[string]string, services ...svcDecl) string {
	t.Helper()
	var b strings.Builder
	b.WriteString("version: \"v1alpha1\"\n")
	if len(labels) > 0 {
		b.WriteString("labels:\n")
		keys := make([]string, 0, len(labels))
		for k := range labels {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		for _, k := range keys {
			fmt.Fprintf(&b, "  %s: %q\n", k, labels[k])
		}
	}
	b.WriteString("services:\n")
	for _, s := range services {
		fmt.Fprintf(&b, "  - type: %q\n    name: %q\n    description: \"integration test service\"\n", s.Type, s.Name)
		if s.TargetURL != "" {
			fmt.Fprintf(&b, "    target_url: %q\n", s.TargetURL)
		}
		if len(s.Command) > 0 {
			b.WriteString("    command:\n")
			for _, c := range s.Command {
				fmt.Fprintf(&b, "      - %q\n", c)
			}
		}
	}
	p := filepath.Join(dir, "node-config.yaml")
	if err := os.WriteFile(p, []byte(b.String()), 0o600); err != nil {
		t.Fatalf("write node config: %v", err)
	}
	return p
}

func callMCP(t *testing.T, mcpAddr string, toolName string, params map[string]any) string {
	t.Helper()
	ctx := context.Background()

	client := mcp.NewClient(&mcp.Implementation{
		Name:    "test-client",
		Version: "0.1.0",
	}, nil)

	// Custom RoundTripper to inject Authorization header for tests
	transport := http.DefaultTransport
	clientTransport := &mcp.StreamableClientTransport{
		Endpoint: "http://" + mcpAddr + "/mcp",
		HTTPClient: &http.Client{
			Transport: &authRoundTripper{
				token: "test-token", // Token used across all integration tests
				rt:    transport,
			},
		},
	}

	session, err := client.Connect(ctx, clientTransport, nil)
	if err != nil {
		t.Fatalf("Failed to connect: %v", err)
	}
	defer func() {
		if err := session.Close(); err != nil {
			t.Logf("failed to close session: %v", err)
		}
	}()

	result, err := session.CallTool(ctx, &mcp.CallToolParams{
		Name:      toolName,
		Arguments: params,
	})
	if err != nil {
		t.Fatalf("CallTool failed: %v", err)
	}

	for _, content := range result.Content {
		if textContent, ok := content.(*mcp.TextContent); ok {
			return textContent.Text
		}
	}
	return ""
}

type authRoundTripper struct {
	token string
	rt    http.RoundTripper
}

func (a *authRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	clone := req.Clone(req.Context())
	clone.Header.Set(api.HeaderMeshAuthentication, "Bearer "+a.token)
	return a.rt.RoundTrip(clone)
}

func TestCatalogRoutingAndFailover(t *testing.T) {
	nodeBin := buildBinary(t, "./cmd/agentmesh-node")
	_, routerAddr := startMockRouter(t)

	homeA := t.TempDir()
	homeB := t.TempDir()
	homeC := t.TempDir()

	// Start Node A (Client)
	t.Log("Starting Node A...")
	nodeA := startBackgroundNode(t, nodeBin, routerAddr, homeA, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")
	t.Log("Node A started.")

	mcpAddrA := nodeA.waitForAPI(t)

	// Start Node B (Provider 1)
	t.Log("Starting Node B...")
	nodeB := startBackgroundNode(t, nodeBin, routerAddr, homeB, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")
	t.Log("Node B started.")

	// Start Node C (Provider 2)
	t.Log("Starting Node C...")
	nodeC := startBackgroundNode(t, nodeBin, routerAddr, homeC, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")
	t.Log("Node C started.")

	nodeB.waitForAPI(t)
	nodeC.waitForAPI(t)
	addrB := nodeB.p2pAddr
	addrC := nodeC.p2pAddr

	// Force Node A to connect to Node B and Node C
	connectPeer(t, mcpAddrA, addrB)
	connectPeer(t, mcpAddrA, addrC)

	// Wait for them to discover each other and publish catalog by polling get_mesh_info
	t.Log("Polling for discovery...")
	deadline := time.Now().Add(5 * time.Second)
	var connected bool

	for time.Now().Before(deadline) {
		client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0.1.0"}, nil)
		session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{
			Endpoint: "http://" + mcpAddrA + "/mcp",
			HTTPClient: &http.Client{
				Transport: &authRoundTripper{token: "test-token", rt: http.DefaultTransport},
			},
		}, nil)
		if err != nil {
			t.Logf("Poll: failed to connect: %v", err)
			time.Sleep(100 * time.Millisecond)
			continue
		}

		result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: "get_mesh_info", Arguments: map[string]any{}})
		if closeErr := session.Close(); closeErr != nil {
			t.Logf("Poll: failed to close session: %v", closeErr)
		}
		if err != nil {
			t.Logf("Poll: CallTool failed: %v", err)
			time.Sleep(100 * time.Millisecond)
			continue
		}

		var text string
		for _, content := range result.Content {
			if textContent, ok := content.(*mcp.TextContent); ok {
				text = textContent.Text
				break
			}
		}

		t.Logf("Poll result:\n%s", text)

		var data map[string]any
		if err := json.Unmarshal([]byte(text), &data); err != nil {
			t.Logf("Failed to parse JSON: %v", err)
			time.Sleep(100 * time.Millisecond)
			continue
		}
		connectedPeers, ok := data["connected_peers"].([]any)
		if ok && len(connectedPeers) >= 3 {
			connected = true
		}

		if connected {
			break
		}

		time.Sleep(100 * time.Millisecond)
	}
	if !connected {
		t.Fatalf("failed to discover peers (router + 2 nodes) in time")
	}

	respData := callMCP(t, mcpAddrA, "get_mesh_info", map[string]any{})
	t.Logf("First call response: %s", respData)

	// Now kill Node B and assert failover to Node C
	nodeB.kill()

	// Wait a bit for catalog update or failover to happen on next call
	time.Sleep(100 * time.Millisecond)

	respData2 := callMCP(t, mcpAddrA, "get_mesh_info", map[string]any{})
	t.Logf("Second call response: %s", respData2)
}