An agent mesh over MCP
Two weft agents talk over MCP with two calls. 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 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:
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.")How it works
Section titled “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 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
Section titled “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:
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."))mcp.Prefix("svc_")renames the tools on the front desk’s side only:billingbecomessvc_billing, and the remote call still uses the server’s name.mcp.Policyapplies tool options to every imported tool.weft.Timeouthere bounds each remote call, the delegation to the billing agent included.- The ledger’s
isErrorresult becomes the call’s error result,ledger offline: maintenance window until 18:00, verbatim. On the Go side it matchesmcp.ErrToolError. A transport failure readsmcp: <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
Section titled “A catalog that follows the server”mcp.Tools lists the tools once. When the server’s list changes, serve the import through weft.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.
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 }))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.
What to look at in Studio
Section titled “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 by agent. - On the front desk’s run page, the three calls of step 0 are three
execute_toolspans. The ledger’s carrieserror.typemcp_tool_error; a transport failure would readmcp_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 weft features it combines
Section titled “The weft features it combines”| Feature | What it does here | Guide |
|---|---|---|
mcp.Serve | exposes the billing agent and its tools | Use MCP both ways |
mcp.Tools, mcp.Prefix, mcp.Policy | import the server’s tools, renamed and bounded | Use MCP both ways |
weft.Subagent semantics | the served agent tool’s input and result | Delegate to another agent |
weft.ToolSource | a catalog re-read every step | Define tools at runtime |
| Remote failure as data | the ledger’s isError reaches the model | Tool errors are data, run errors are yours |
The program
Section titled “The program”// 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) }}View on GitHub · run it from docs-site/examples:
go run ./cookbook/mcpmeshgo test ./cookbook/mcpmesh== meshimported: svc_billing, svc_get_invoice, svc_legacy_ledgercustomer_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 serveroffered: searchoffered: search, summarizeThe 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
Section titled “Best practices & gotchas”- Expect the agent’s tools in the import too.
mcp.Servelists the agent’s own tools beside the agent tool, so the front desk can callsvc_get_invoicedirectly 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
readOnlyHintisSequential, andmcp.Policycannot 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.Servepanics 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.ImportErrornaming the skipped ones. (Source:weft/mcp/client.go:19-111)
See also
Section titled “See also”- Use MCP both ways: every import and serve option
- Delegate to another agent (subagents): the in-process form of the same delegation
- Define tools at runtime: RawTool and ToolSource
- Research team: a lead agent and specialist subagents
Symbols used: mcp.Serve · mcp.Tools · mcp.Prefix · mcp.Policy · mcp.ErrToolError · mcp.ImportError · weft.Subagent · weft.ToolSource · weft.ToolDef · ToolDef.Invoke · weft.Timeout · weft.Sequential · otel.Install · otel.LocalDB · obsdb.RunQuery · wefttest.Script · MCP Go SDK