---
title: An agent mesh over MCP
description: Serve one weft agent over MCP with mcp.Serve and import it into another with mcp.Tools, so a front-desk agent calls a whole billing agent as one remote tool, and keep the imported catalog current with weft.ToolSource.
url: https://weftgo.dev/docs/examples/mcp-mesh/
type: how-to
sources:
  - weft/mcp/server.go:112-144 (Serve; the agent tool is Subagent over the wire; Serve requires a name)
  - weft/mcp/client.go:19-111 (Tools; remote isError is a tool error, readOnlyHint absent is Sequential, ToolSource for a list that changes), 327-330 (Prefix), 348-357 (Policy)
  - weft/mcp/client.go:17 (ErrToolError), 419-425 (error.type mcp_tool_error, mcp_transport)
  - weft/core/agent.go:777-796 (ToolSource replaces the registered tools, re-read every step)
  - docs-site/examples/go.mod (go-sdk v1.8.0)
  - weft/core/subagent.go:166-183 (childRunID needs a parent call)
  - weft/AGENTS.md:61-65 (block 1d)
  - weft/docs/adr/0015-mcp-interop.md
  - weft/mcp/example_test.go:169 (ExampleTools_toolSource)
  - 'weft-arena/internal/suites/realworld_more.go: rwMCPMesh (inspiration only)'
  - docs-site/examples/cookbook/mcpmesh/main.go, main_test.go TestMesh, TestRemoteFailureIsData
---

# An agent mesh over MCP

Two weft agents talk over MCP with two calls. [`mcp.Serve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Serve) exposes an agent as an MCP server: one tool named after the agent that runs it on a prompt, plus the agent's own tools. [`mcp.Tools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Tools) imports a server's tools as ordinary `*weft.ToolDef` values, so another agent calls the whole remote agent like any tool, and a remote failure reaches its model as data.

The billing team serves its agent in `cookbook/mcpmesh/main.go`:

```go title="cookbook/mcpmesh/main.go"
billing := weft.New(wefttest.Script(
	wefttest.ToolCalls(wefttest.Call{Name: "get_invoice", Args: `{"invoice_id":"INV-9"}`}),
	wefttest.Say("INV-9 is 120 EUR, due 2026-10-01, still unpaid."),
), weft.Name("billing"), weft.MaxSteps(5), getInvoice) // mcp.Serve requires a name

srv := sdk.NewServer(&sdk.Implementation{Name: "billing-service", Version: "1"}, nil)
// One tool named "billing" that runs the agent on a prompt, plus the
// agent's own tools, each dispatched through its tool chain.
mcp.Serve(srv, billing, "The billing agent: answers questions about invoices and payments.")
```

[cookbook/mcpmesh/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/mcpmesh/main.go)

## How it works

The shape comes from the weft-arena scenario `rw.mcp-mesh`. The billing team owns an agent with its own model and an invoice tool. It also runs a legacy ledger tool on the same server, and the ledger is down for maintenance. The front desk is another team's agent: it imports everything the billing server lists and mixes it with a local `customer_profile` tool.

The agent tool `mcp.Serve` registers is [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) over the wire: the same `{"prompt": string}` input and the same final-text rule. Its description is the only thing the front desk's model reads to decide when to call it, and you write it; it is never generated. The agent's own tools are listed beside it and dispatched through the billing agent's tool chain, so its middleware and approval policy apply.

## Import the mesh

`connect` in the program runs the server over the SDK's in-memory transport. Across processes you dial it with the SDK's command or streamable HTTP transport instead. Import its tools under a prefix and run the front desk:

```go title="cookbook/mcpmesh/main.go"
imported, err := mcp.Tools(ctx, sess,
	mcp.Prefix("svc_"),                      // billing → svc_billing, on the agent's side only
	mcp.Policy(weft.Timeout(2*time.Minute)), // bounds each remote call, the delegation included
)
if err != nil {
	return err
}
opts := []weft.Option{weft.Name("front-desk"), weft.MaxSteps(6), profile}
for _, td := range imported {
	opts = append(opts, td) // an imported tool is an ordinary *weft.ToolDef
}
front := weft.New(wefttest.Script(
	wefttest.ToolCalls(
		wefttest.Call{ID: "p1", Name: "customer_profile", Args: `{"customer_id":"42"}`},
		wefttest.Call{ID: "b1", Name: "svc_billing", Args: `{"prompt":"What is the status of invoice INV-9?"}`},
		wefttest.Call{ID: "l1", Name: "svc_legacy_ledger", Args: `{"account":"42"}`},
	),
	wefttest.Say("INV-9 (120 EUR) is unpaid and due Oct 1; the ledger is down for maintenance."),
), opts...)
res, err := front.Generate(ctx, weft.Prompt("Customer 42 asks about invoice INV-9."))
```

[cookbook/mcpmesh/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/mcpmesh/main.go)

- [`mcp.Prefix("svc_")`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Prefix) renames the tools on the front desk's side only: `billing` becomes `svc_billing`, and the remote call still uses the server's name.
- [`mcp.Policy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Policy) applies tool options to every imported tool. `weft.Timeout` here bounds each remote call, the delegation to the billing agent included.
- The ledger's `isError` result becomes the call's error result, `ledger offline: maintenance window until 18:00`, verbatim. On the Go side it matches `mcp.ErrToolError`. A transport failure reads `mcp: <err>`. Neither is a run error.

The billing agent runs inside the `svc_billing` call: its own model call, its own `get_invoice` call, its own answer. The front desk's model sees only that answer.

## A catalog that follows the server

`mcp.Tools` lists the tools once. When the server's list changes, serve the import through [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) instead of registering it: the loop reads the source every step, so the next step offers whatever the last refresh produced. The source replaces the agent's registered tools: include any local tools, such as `customer_profile`, in the slice it returns.

```go title="cookbook/mcpmesh/main.go"
var (
	mu      sync.Mutex // refresh runs on the SDK's goroutine, the source on the run's
	current []*weft.ToolDef
)
refresh := func() error {
	tools, err := mcp.Tools(ctx, sess)
	if err != nil {
		return err
	}
	mu.Lock()
	current = tools
	mu.Unlock()
	return nil
}
if err := refresh(); err != nil { // call it again from the SDK's ToolListChangedHandler
	return err
}
model := wefttest.Script(wefttest.Say("ok"), wefttest.Say("ok"))
agt := weft.New(model,
	weft.Name("importer"),
	weft.ToolSource(func() []*weft.ToolDef {
		mu.Lock()
		defer mu.Unlock()
		return current
	}))
```

[cookbook/mcpmesh/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/mcpmesh/main.go)

The refresh runs on the SDK's goroutine when you call it from the client's `ToolListChangedHandler`, and the source runs on the run's goroutine, so the slice lives under a mutex. `mcp.Tools` does not own the session and never closes it. In the program the server adds `summarize`, the program calls `refresh`, and the next run's model call offers both tools. The package example is [`ExampleTools_toolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Tools-ToolSource).

## What to look at in Studio

The program records with `otel.Install(otel.Local(""))`. Both agents ran in this process, so both runs are in the local sink:

- The front desk's run has **no child runs**. The billing agent's run is a separate top-level run of agent `billing`: the MCP call carries no weft parent, so the core cannot chain its id from the front desk's call. Find it in the [runs list](https://weftgo.dev/docs/observe/studio/runs/) by agent.
- On the front desk's [run page](https://weftgo.dev/docs/observe/studio/run-page/), the three calls of step 0 are three `execute_tool` spans. The ledger's carries `error.type` `mcp_tool_error`; a transport failure would read `mcp_transport`.
- Across processes the billing run is recorded only where the billing service records its own runs. Point both services at one Studio to see them side by side.

![The front desk's run in Studio: step 0 ran customer_profile, svc_billing and svc_legacy_ledger; the ledger's call is marked MCP tool error, and the header counts one MCP tool error](https://weftgo.dev/docs/_astro/studio-run-mcp-mesh.light.BApZcfuf.webp)

*The front desk's run: step 0's customer_profile, svc_billing and svc_legacy_ledger calls, the ledger's marked MCP tool error and counted in the header.*

## The weft features it combines

| Feature | What it does here | Guide |
|---|---|---|
| `mcp.Serve` | exposes the billing agent and its tools | [Use MCP both ways](https://weftgo.dev/docs/guides/mcp/) |
| `mcp.Tools`, `mcp.Prefix`, `mcp.Policy` | import the server's tools, renamed and bounded | [Use MCP both ways](https://weftgo.dev/docs/guides/mcp/) |
| `weft.Subagent` semantics | the served agent tool's input and result | [Delegate to another agent](https://weftgo.dev/docs/guides/subagents/) |
| `weft.ToolSource` | a catalog re-read every step | [Define tools at runtime](https://weftgo.dev/docs/guides/dynamic-tools/) |
| Remote failure as data | the ledger's `isError` reaches the model | [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/) |

## The program

```go title="cookbook/mcpmesh/main.go"
// Command mcpmesh is the recipe "An agent mesh over MCP":
// go run ./cookbook/mcpmesh. A billing agent is served over MCP with
// mcp.Serve, beside a legacy ledger tool that is down. A front-desk agent
// imports the server's tools with mcp.Tools under a prefix, mixes them
// with a local tool, and answers in one step: the whole billing agent
// runs as one remote tool, and the ledger's remote failure arrives as
// data. The second part serves the import through weft.ToolSource, so
// the front desk's catalog follows the server when it adds a tool.
// Everything runs over in-memory MCP transports with scripted models, and
// the runs are recorded to the local sink ($WEFT_DB, else ./.weft/weft.db).
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"slices"
	"strings"
	"sync"
	"time"

	sdk "github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/weftgo/weft"
	"github.com/weftgo/weft/mcp"
	"github.com/weftgo/weft/obsdb"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/wefttest"
)

type InvoiceInput struct {
	InvoiceID string `json:"invoice_id" jsonschema:"e.g. INV-9"`
}

type CustomerInput struct {
	CustomerID string `json:"customer_id" jsonschema:"the customer id"`
}

// connect runs srv over an in-memory transport and returns a client
// session on it. Across processes, dial the server with the SDK's
// command or streamable HTTP transport instead.
func connect(ctx context.Context, srv *sdk.Server) (*sdk.ClientSession, error) {
	serverSide, clientSide := sdk.NewInMemoryTransports()
	go func() { _ = srv.Run(ctx, serverSide) }()
	client := sdk.NewClient(&sdk.Implementation{Name: "front-desk", Version: "1"}, nil)
	return client.Connect(ctx, clientSide, nil)
}

// billingServer is the billing team's MCP server: their agent, with its
// own model and tool, plus a legacy tool that answers isError.
func billingServer() *sdk.Server {
	getInvoice := weft.Tool("get_invoice", "Status of an invoice.",
		func(_ context.Context, in InvoiceInput) (string, error) {
			return in.InvoiceID + ": 120 EUR, due 2026-10-01, unpaid", nil
		})
	billing := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "get_invoice", Args: `{"invoice_id":"INV-9"}`}),
		wefttest.Say("INV-9 is 120 EUR, due 2026-10-01, still unpaid."),
	), weft.Name("billing"), weft.MaxSteps(5), getInvoice) // mcp.Serve requires a name

	srv := sdk.NewServer(&sdk.Implementation{Name: "billing-service", Version: "1"}, nil)
	// One tool named "billing" that runs the agent on a prompt, plus the
	// agent's own tools, each dispatched through its tool chain.
	mcp.Serve(srv, billing, "The billing agent: answers questions about invoices and payments.")
	srv.AddTool(&sdk.Tool{
		Name:        "legacy_ledger",
		Description: "Ledger balance for an account (legacy system).",
		InputSchema: json.RawMessage(`{"type":"object","properties":{"account":{"type":"string"}},"required":["account"]}`),
	}, func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
		return &sdk.CallToolResult{IsError: true, Content: []sdk.Content{&sdk.TextContent{Text: "ledger offline: maintenance window until 18:00"}}}, nil
	})
	return srv
}

var profile = weft.Tool("customer_profile", "Profile of a customer.",
	func(_ context.Context, in CustomerInput) (string, error) {
		return "customer " + in.CustomerID + ": Acme SARL, account 42", nil
	})

// mesh imports the billing server's tools into the front desk and runs
// one turn that uses the remote agent, the remote ledger and a local tool.
func mesh(ctx context.Context, w io.Writer, sess *sdk.ClientSession) error {
	imported, err := mcp.Tools(ctx, sess,
		mcp.Prefix("svc_"),                      // billing → svc_billing, on the agent's side only
		mcp.Policy(weft.Timeout(2*time.Minute)), // bounds each remote call, the delegation included
	)
	if err != nil {
		return err
	}
	opts := []weft.Option{weft.Name("front-desk"), weft.MaxSteps(6), profile}
	for _, td := range imported {
		opts = append(opts, td) // an imported tool is an ordinary *weft.ToolDef
	}
	front := weft.New(wefttest.Script(
		wefttest.ToolCalls(
			wefttest.Call{ID: "p1", Name: "customer_profile", Args: `{"customer_id":"42"}`},
			wefttest.Call{ID: "b1", Name: "svc_billing", Args: `{"prompt":"What is the status of invoice INV-9?"}`},
			wefttest.Call{ID: "l1", Name: "svc_legacy_ledger", Args: `{"account":"42"}`},
		),
		wefttest.Say("INV-9 (120 EUR) is unpaid and due Oct 1; the ledger is down for maintenance."),
	), opts...)
	res, err := front.Generate(ctx, weft.Prompt("Customer 42 asks about invoice INV-9."))
	if err != nil {
		return err
	}
	var names []string
	for _, td := range imported {
		names = append(names, td.Name)
	}
	slices.Sort(names)
	fmt.Fprintln(w, "imported:", strings.Join(names, ", "))
	for _, r := range res.Steps[0].Results {
		fmt.Fprintf(w, "%s → %s (error: %t)\n", r.Name, r.Content, r.IsError)
	}
	fmt.Fprintln(w, "answer:", res.Text())

	// The served agent ran in its own run, recorded beside the front desk's.
	page, err := otel.LocalDB().Runs(ctx, obsdb.RunQuery{Agent: "billing"})
	if err != nil {
		return err
	}
	detail, err := otel.LocalDB().Run(ctx, res.ID)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "recorded: front-desk children %d; billing runs %d, parent %q\n",
		len(detail.Children), page.Total, page.Runs[0].ParentRunID)
	return nil
}

// following serves the import through a ToolSource: the loop reads the
// source every step, so a refreshed slice is what the next step offers.
func following(ctx context.Context, w io.Writer) error {
	srv := sdk.NewServer(&sdk.Implementation{Name: "catalog", Version: "1"}, nil)
	addEcho := func(name string) {
		srv.AddTool(&sdk.Tool{Name: name, Description: "Echo.", InputSchema: json.RawMessage(`{"type":"object"}`)},
			func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
				return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: name + " ok"}}}, nil
			})
	}
	addEcho("search")
	sess, err := connect(ctx, srv)
	if err != nil {
		return err
	}
	defer sess.Close()

	var (
		mu      sync.Mutex // refresh runs on the SDK's goroutine, the source on the run's
		current []*weft.ToolDef
	)
	refresh := func() error {
		tools, err := mcp.Tools(ctx, sess)
		if err != nil {
			return err
		}
		mu.Lock()
		current = tools
		mu.Unlock()
		return nil
	}
	if err := refresh(); err != nil { // call it again from the SDK's ToolListChangedHandler
		return err
	}
	model := wefttest.Script(wefttest.Say("ok"), wefttest.Say("ok"))
	agt := weft.New(model,
		weft.Name("importer"),
		weft.ToolSource(func() []*weft.ToolDef {
			mu.Lock()
			defer mu.Unlock()
			return current
		}))

	// offered runs one turn and prints the tools its model call carried.
	offered := func() error {
		if _, err := agt.Generate(ctx, weft.Prompt("status?")); err != nil {
			return err
		}
		reqs := model.Requests()
		var seen []string
		for _, td := range reqs[len(reqs)-1].Tools {
			seen = append(seen, td.Name)
		}
		slices.Sort(seen)
		fmt.Fprintln(w, "offered:", strings.Join(seen, ", "))
		return nil
	}
	if err := offered(); err != nil {
		return err
	}
	addEcho("summarize") // the server's list changed
	if err := refresh(); err != nil {
		return err
	}
	return offered()
}

func run(ctx context.Context, w io.Writer) error {
	defer otel.Install(otel.Local(""))()

	sess, err := connect(ctx, billingServer())
	if err != nil {
		return err
	}
	defer sess.Close()
	fmt.Fprintln(w, "== mesh")
	if err := mesh(ctx, w, sess); err != nil {
		return err
	}
	fmt.Fprintln(w, "== a catalog that follows the server")
	return following(ctx, w)
}

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

[cookbook/mcpmesh/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/mcpmesh/main.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/cookbook/mcpmesh) · run it from `docs-site/examples`:

```sh
go run ./cookbook/mcpmesh
go test ./cookbook/mcpmesh
```

```text
== mesh
imported: svc_billing, svc_get_invoice, svc_legacy_ledger
customer_profile → customer 42: Acme SARL, account 42 (error: false)
svc_billing → INV-9 is 120 EUR, due 2026-10-01, still unpaid. (error: false)
svc_legacy_ledger → ledger offline: maintenance window until 18:00 (error: true)
answer: INV-9 (120 EUR) is unpaid and due Oct 1; the ledger is down for maintenance.
recorded: front-desk children 0; billing runs 1, parent ""
== a catalog that follows the server
offered: search
offered: search, summarize
```

The tests also call the imported tools directly with `ToolDef.Invoke`: the ledger's error matches `mcp.ErrToolError`, and the served agent answers its prompt.

## Best practices & gotchas

- **Expect the agent's tools in the import too.** `mcp.Serve` lists the agent's own tools beside the agent tool, so the front desk can call `svc_get_invoice` directly and bypass the billing agent. Serve only what another team may call. (Source: `weft/mcp/server.go:112-144`)
- **Imported tools run one at a time unless the server says otherwise.** A tool without `readOnlyHint` is `Sequential`, and `mcp.Policy` cannot undo it, so the step's three calls here do not overlap. (Source: `weft/mcp/client.go:55-58`, 234-242)
- **Name the served agent.** `mcp.Serve` panics on an unnamed agent and on a name its own tools already use. (Source: `weft/mcp/server.go:112-144`)
- **Write the served agent's description for the caller's model.** It is the whole routing surface, as for `weft.Subagent`. (Source: `weft/mcp/server.go:112-144`)
- **Handle a partial import.** A tool the core cannot import fails that tool only: the rest are returned with an `*mcp.ImportError` naming the skipped ones. (Source: `weft/mcp/client.go:19-111`)

## See also

- [Use MCP both ways](https://weftgo.dev/docs/guides/mcp/): every import and serve option
- [Delegate to another agent (subagents)](https://weftgo.dev/docs/guides/subagents/): the in-process form of the same delegation
- [Define tools at runtime: RawTool and ToolSource](https://weftgo.dev/docs/guides/dynamic-tools/)
- [Research team: a lead agent and specialist subagents](https://weftgo.dev/docs/examples/research-team/)

Symbols used: [`mcp.Serve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Serve) · [`mcp.Tools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Tools) · [`mcp.Prefix`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Prefix) · [`mcp.Policy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Policy) · [`mcp.ErrToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ErrToolError) · [`mcp.ImportError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) · [`weft.ToolDef`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolDef) · [`ToolDef.Invoke`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.Invoke) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.Sequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Sequential) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`obsdb.RunQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunQuery) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [MCP Go SDK](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk@v1.8.0/mcp)
