Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
fix: cap concurrent subprocesses per command-backed MCP service
Antonio Ojeab1c231140ded
diff --git a/internal/node/mcp_service.go b/internal/node/mcp_service.goindex 3d0e5f10..04cc5278 100644--- a/internal/node/mcp_service.go+++ b/internal/node/mcp_service.go@@ -16,6 +16,7 @@ package nodeimport ("context"+ "errors""fmt""os""os/exec"@@ -29,6 +30,13 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp")+// commandSessionLimit caps the subprocesses one command-backed MCP service+// runs at once. Every mesh stream now costs a process, so without a bound an+// authorized peer holding streams open could fork the node out of memory.+const commandSessionLimit = 16++var errTooManyCommandSessions = errors.New("too many concurrent sessions to command backend")+// MCPService extends baseService to handle MCP protocol proxying.type MCPService struct {baseService@@ -36,6 +44,52 @@ type MCPService struct {toolsMu sync.MutexcachedTools []stringtoolsExpires time.Time++ // sessions is the slot pool for command-backend subprocesses. Nil until+ // first use, when it gets commandSessionLimit slots; a preset channel+ // (tests) is kept as is.+ sessionsOnce sync.Once+ sessions chan struct{}+}++func (m *MCPService) sessionSlots() chan struct{} {+ m.sessionsOnce.Do(func() {+ if m.sessions == nil {+ m.sessions = make(chan struct{}, commandSessionLimit)+ }+ })+ return m.sessions+}++// boundedTransport takes a slot from slots on Connect and gives it back once+// the connection's Close has reaped the child.+type boundedTransport struct {+ mcp.Transport+ slots chan struct{}+}++func (t *boundedTransport) Connect(ctx context.Context) (mcp.Connection, error) {+ select {+ case t.slots <- struct{}{}:+ default:+ return nil, errTooManyCommandSessions+ }+ conn, err := t.Transport.Connect(ctx)+ if err != nil {+ <-t.slots+ return nil, err+ }+ return &boundedConn{Connection: conn, release: sync.OnceFunc(func() { <-t.slots })}, nil+}++type boundedConn struct {+ mcp.Connection+ release func()+}++func (c *boundedConn) Close() error {+ defer c.release()+ return c.Connection.Close()}// Probe reports whether the backend actually speaks MCP, by completing an@@ -97,7 +151,10 @@ func (m *MCPService) backendTransport() (mcp.Transport, error) {for k, v := range x.Command.Env {cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))}- return &mcp.CommandTransport{Command: cmd}, nil+ return &boundedTransport{+ Transport: &mcp.CommandTransport{Command: cmd},+ slots: m.sessionSlots(),+ }, nildefault:return nil, fmt.Errorf("unsupported backend type %T for MCP service %q", m.backend, m.info.GetName())}