Skip to content

Agent Mesh

Support Streamable HTTP POST in stdio bridge and migrate handlers

Antonio Ojea74189cbe6eb0
diff --git a/cmd/mcp-client/main.go b/cmd/mcp-client/main.go
index c7e44bf5..90dfd3b2 100644
--- a/cmd/mcp-client/main.go
+++ b/cmd/mcp-client/main.go
@@ -145,9 +145,9 @@ func main() {
}, nil)
// Connect to server using the URL
- var sseTransport mcp.Transport = &mcp.SSEClientTransport{Endpoint: *serverURL}
+ var mcpTransport mcp.Transport = &mcp.StreamableClientTransport{Endpoint: *serverURL}
if *tokenOpt != "" {
- sseTransport = &mcp.SSEClientTransport{
+ mcpTransport = &mcp.StreamableClientTransport{
Endpoint: *serverURL,
HTTPClient: &http.Client{
Transport: &authTransport{
@@ -157,7 +157,7 @@ func main() {
},
}
}
- session, err := client.Connect(ctx, sseTransport, nil)
+ session, err := client.Connect(ctx, mcpTransport, nil)
if err != nil {
log.Fatalf("Failed to connect: %v", err)
}
diff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.go
index 6790efa9..c93a5ec2 100644
--- a/cmd/sam-node/mcp.go
+++ b/cmd/sam-node/mcp.go
@@ -189,12 +189,12 @@ func NewUnauthenticatedMCPServer(hubURL string) *mcp.Server {
func NewUnauthenticatedMCPHandler(hubURL string) http.Handler {
mcpServer := NewUnauthenticatedMCPServer(hubURL)
- sseHandler := mcp.NewSSEHandler(func(request *http.Request) *mcp.Server {
+ streamableHandler := mcp.NewStreamableHTTPHandler(func(request *http.Request) *mcp.Server {
return mcpServer
}, nil)
mux := http.NewServeMux()
- mux.Handle("/mcp", sseHandler)
+ mux.Handle("/mcp", streamableHandler)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Debugf("Unauth MCP Request: %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
@@ -206,13 +206,13 @@ func NewUnauthenticatedMCPHandler(hubURL string) http.Handler {
func NewMCPHandler(node *SamNode) http.Handler {
mcpServer := NewMCPServer(node)
- // Create the SSE handler using the SDK
- sseHandler := mcp.NewSSEHandler(func(request *http.Request) *mcp.Server {
+ // Create the Streamable handler using the SDK
+ streamableHandler := mcp.NewStreamableHTTPHandler(func(request *http.Request) *mcp.Server {
return mcpServer
}, nil)
mux := http.NewServeMux()
- mux.Handle("/mcp", sseHandler)
+ mux.Handle("/mcp", streamableHandler)
// Wrap in logging middleware to debug incoming requests
wrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/cmd/sam-node/stdio_bridge.go b/cmd/sam-node/stdio_bridge.go
index f7fc49d2..bee2a464 100644
--- a/cmd/sam-node/stdio_bridge.go
+++ b/cmd/sam-node/stdio_bridge.go
@@ -16,6 +16,7 @@ package main
import (
"bufio"
+ "encoding/json"
"fmt"
"io"
"net/http"
@@ -102,6 +103,23 @@ func (b *StdioBridge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
_ = r.Body.Close()
+ var msg map[string]any
+ isCall := false
+ var reqID any
+ if err := json.Unmarshal(body, &msg); err == nil {
+ if id, ok := msg["id"]; ok {
+ isCall = true
+ reqID = id
+ }
+ }
+
+ var ch <-chan string
+ var unsub func()
+ if isCall {
+ ch, unsub = b.Subscribe()
+ defer unsub()
+ }
+
b.mu.Lock()
_, err = b.stdin.Write(append(body, '\n'))
b.mu.Unlock()
@@ -110,7 +128,31 @@ func (b *StdioBridge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Failed to write to process stdin", http.StatusInternalServerError)
return
}
- w.WriteHeader(http.StatusOK)
+
+ w.Header().Set("Mcp-Session-Id", "stdio-bridge")
+
+ if !isCall {
+ w.WriteHeader(http.StatusAccepted)
+ return
+ }
+
+ ctx := r.Context()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case line := <-ch:
+ var respMsg map[string]any
+ if err := json.Unmarshal([]byte(line), &respMsg); err == nil {
+ if respID, ok := respMsg["id"]; ok && fmt.Sprintf("%v", respID) == fmt.Sprintf("%v", reqID) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(line))
+ return
+ }
+ }
+ }
+ }
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
diff --git a/site/content/docs/integrations/_index.md b/site/content/docs/integrations/_index.md
index 2b6ade2d..856af7b0 100644
--- a/site/content/docs/integrations/_index.md
+++ b/site/content/docs/integrations/_index.md
@@ -16,6 +16,7 @@ Every `sam-node` runs a local MCP server that allows agents to:
Explore the step-by-step guides to integrate SAM with your favorite AI Agent systems:
- [Google Gemini](gemini.md): Build an interactive client using the official `google-genai` Python SDK.
+- [Google Antigravity](antigravity.md): Connect your local node as a remote MCP server to Google Antigravity.
- [Claude Code](claude-code.md): Connect your local node as a remote MCP server to Claude Code.
- [Claude Desktop](claude-desktop.md): Use SAM to expose the P2P tool mesh to Claude Desktop.
- [OpenClaw](openclaw.md): Integrate your node as a remote tool bridge for OpenClaw.
diff --git a/site/content/docs/integrations/antigravity.md b/site/content/docs/integrations/antigravity.md
new file mode 100644
index 00000000..54b9b554
--- /dev/null
+++ b/site/content/docs/integrations/antigravity.md
@@ -0,0 +1,50 @@
+---
+title: "Integrating SAM with Google Antigravity"
+linkTitle: "Integrating SAM with Google Antigravity"
+---
+You can connect your `sam-node` to Google Antigravity as an MCP server. By exposing the SAM Model Context Protocol (MCP) server to Antigravity, the agent can dynamically discover tools hosted by other peers in the mesh, describe them, and execute them to solve tasks.
+
+## Overview
+
+Antigravity natively supports Streamable HTTP MCP servers via the `serverUrl` configuration. Since `sam-node` implements the Streamable HTTP transport, you can connect it directly without any bridge.
+
+## Prerequisites
+
+- A running `sam-node` (default `http://localhost:8080`) and its `--api-token`.
+
+## Configuration
+
+Edit your Antigravity MCP configuration file:
+
+- Path: `~/.gemini/config/mcp_config.json`
+
+Add the node directly using its HTTP endpoint (replace `<YOUR_TOKEN>` with your `--api-token`):
+
+```json
+{
+ "mcpServers": {
+ "sam-mesh": {
+ "serverUrl": "http://localhost:8080/mcp",
+ "headers": {
+ "Authorization": "Bearer <YOUR_TOKEN>"
+ }
+ }
+ }
+}
+```
+
+Antigravity will automatically discover the change. The `sam-node` tools — `discover_remote_services`, `find_remote_tools`, `describe_remote_tool`, and `call_remote_tool` — will then be available.
+
+## Discovering and Invoking Remote Tools
+
+The tool flow for Antigravity is as follows:
+
+1. `discover_remote_services` → list active services and obtain their `peer_id`s.
+2. `find_remote_tools` (`peer_id`) → list the tools a peer hosts.
+3. `describe_remote_tool` (`peer_id`, `tool_name`) → fetch the tool's `input_schema`.
+4. `call_remote_tool` (`peer_id`, `tool_name`, `arguments`) → invoke it across the mesh.
+
+## Troubleshooting
+
+* **Connection errors**: verify `sam-node` is reachable at the configured URL and that the bearer token matches `--api-token`.
+* **Running `sam-node` in WSL or a container**: the `mcp-remote` bridge runs on the host, so that host must be able to reach the node's bind address. Bind the node to an address the host can reach (e.g. `0.0.0.0`).
diff --git a/tests/integration/catalog_test.go b/tests/integration/catalog_test.go
index 4796df8a..da4e37d4 100644
--- a/tests/integration/catalog_test.go
+++ b/tests/integration/catalog_test.go
@@ -75,7 +75,7 @@ func callMCP(t *testing.T, mcpAddr string, toolName string, params map[string]an
Version: "0.1.0",
}, nil)
- session, err := client.Connect(ctx, &mcp.SSEClientTransport{Endpoint: "http://" + mcpAddr + "/mcp"}, nil)
+ session, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: "http://" + mcpAddr + "/mcp"}, nil)
if err != nil {
t.Fatalf("Failed to connect: %v", err)
}
@@ -172,7 +172,7 @@ func TestCatalogRoutingAndFailover(t *testing.T) {
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.SSEClientTransport{Endpoint: "http://" + mcpAddrA + "/mcp"}, nil)
+ session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{Endpoint: "http://" + mcpAddrA + "/mcp"}, nil)
if err != nil {
t.Logf("Poll: failed to connect: %v", err)
time.Sleep(500 * time.Millisecond)
diff --git a/tests/integration/datapath_test.go b/tests/integration/datapath_test.go
index 20dd68ee..9b8907b0 100644
--- a/tests/integration/datapath_test.go
+++ b/tests/integration/datapath_test.go
@@ -15,7 +15,6 @@
package integration_test
import (
- "bufio"
"bytes"
"fmt"
"io"
@@ -110,64 +109,44 @@ func TestIntegrationStdioDatapath(t *testing.T) {
// Node B calls Node A's service via its local egress proxy
// URL format: http://localhost:<port>/sam/{peer_id}/{service_type}/{service_name}/{upstream_path}
- sseURL := fmt.Sprintf("http://%s/sam/%s/mcp/%s/", actualApiAddrB, peerIDA, serviceName)
postURL := fmt.Sprintf("http://%s/sam/%s/mcp/%s/", actualApiAddrB, peerIDA, serviceName)
client := &http.Client{}
- // Establish SSE stream
- var sseResp *http.Response
+ // Test Streamable HTTP (http-first mode)
+ // Send message via POST and expect the response in the HTTP response body
+ testMessage := `{"jsonrpc":"2.0","method":"ping","id":1}`
+ postReq, _ := http.NewRequest("POST", postURL, bytes.NewBufferString(testMessage))
+ postReq.Header.Set("Authorization", "Bearer "+apiToken)
+ postReq.Header.Set("Content-Type", "application/json")
+ postReq.Header.Set("Accept", "application/json")
+
+ var postResp *http.Response
for i := 0; i < 3; i++ {
- req, _ := http.NewRequest("GET", sseURL, nil)
- req.Header.Set("Authorization", "Bearer "+apiToken)
- sseResp, err = client.Do(req)
- if err == nil && sseResp.StatusCode == http.StatusOK {
+ postResp, err = client.Do(postReq)
+ if err == nil && postResp.StatusCode == http.StatusOK {
break
}
- t.Logf("SSE Connect Attempt %d failed: %v, status: %v", i+1, err, sseResp)
+ t.Logf("POST Attempt %d failed: %v, status: %v", i+1, err, postResp)
time.Sleep(1 * time.Second)
}
if err != nil {
t.Fatal(err)
}
- defer func() { _ = sseResp.Body.Close() }()
-
- if sseResp.StatusCode != http.StatusOK {
- t.Fatalf("Expected SSE status OK, got %d", sseResp.StatusCode)
- }
-
- // Send message via POST
- testMessage := `{"jsonrpc":"2.0","method":"ping","id":1}`
- postReq, _ := http.NewRequest("POST", postURL, bytes.NewBufferString(testMessage))
- postReq.Header.Set("Authorization", "Bearer "+apiToken)
- postReq.Header.Set("Content-Type", "application/json")
- postResp, err := client.Do(postReq)
- if err != nil {
- t.Fatal(err)
- }
- _ = postResp.Body.Close()
+ defer func() { _ = postResp.Body.Close() }()
if postResp.StatusCode != http.StatusOK {
t.Fatalf("Expected POST status OK, got %d", postResp.StatusCode)
}
- // Read from SSE stream
- reader := bufio.NewReader(sseResp.Body)
- line, err := reader.ReadString('\n')
+ bodyBytes, err := io.ReadAll(postResp.Body)
if err != nil {
t.Fatal(err)
}
- expectedPrefix := "data: "
- if !strings.HasPrefix(line, expectedPrefix) {
- t.Fatalf("Expected line to start with %q, got %q", expectedPrefix, line)
- }
-
- receivedMessage := strings.TrimPrefix(line, expectedPrefix)
- receivedMessage = strings.TrimSpace(receivedMessage)
-
+ receivedMessage := strings.TrimSpace(string(bodyBytes))
if receivedMessage != testMessage {
- t.Fatalf("Expected to receive %q, got %q", testMessage, receivedMessage)
+ t.Fatalf("Expected to receive %q in POST response, got %q", testMessage, receivedMessage)
}
}
diff --git a/tests/integration/pubsub_test.go b/tests/integration/pubsub_test.go
index 20dd8269..28d507fc 100644
--- a/tests/integration/pubsub_test.go
+++ b/tests/integration/pubsub_test.go
@@ -105,7 +105,7 @@ func TestPubSubTools(t *testing.T) {
Version: "0.1.0",
}, nil)
- session, err := client.Connect(context.Background(), &mcp.SSEClientTransport{Endpoint: "http://" + mcpAddr + "/mcp"}, nil)
+ session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{Endpoint: "http://" + mcpAddr + "/mcp"}, nil)
if err != nil {
t.Fatalf("Failed to connect: %v", err)
}