Skip to content

Use MCP both ways

View as Markdown

Package weft/mcp bridges weft and the Model Context Protocol in both directions, over the official Go MCP SDK. mcp.Tools turns a connected server’s tools into ordinary weft tools; mcp.AddTools and mcp.Serve register weft tools, or a whole agent, on an MCP server.

Import a server’s tools and give them to an agent, in mcpx/mcpx.go:

mcpx/mcpx.go
tools, err := mcp.Tools(ctx, sess,
mcp.Prefix("gh_"), // search_issues → gh_search_issues
mcp.Policy(weft.Timeout(10*time.Second)), // per-tool policy on every imported tool
)
var skipped *mcp.ImportError
if errors.As(err, &skipped) {
fmt.Fprintln(w, "skipped:", skipped) // some tools were left out; the rest are in tools
} else if err != nil {
return err // the listing itself failed
}
opts := []weft.Option{weft.Name("triage")}
for _, t := range tools {
opts = append(opts, t) // an imported tool is an ordinary *weft.ToolDef
}
model := wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "gh_search_issues", Args: `{"q":"crash","state":"open"}`},
wefttest.Call{Name: "gh_close_issue", Args: `{"id":12}`},
),
wefttest.Say("Two issues are open; #12 is locked."),
)
agt := weft.New(model, opts...)
res, err := agt.Generate(ctx, weft.Prompt("Triage the crash reports."))

mcpx/mcpx.go on GitHub

The tools Tools returns are *weft.ToolDef values, so they register on weft.New like any tool. The model calls gh_search_issues; the bridge forwards the call to the server’s search_issues.

The bridge has no adapter layer of its own: weft’s tool contract and MCP’s are the same shape, so each direction is a field-for-field mapping (ADR 0015). The package imports the SDK as sdk in examples and keeps the name mcp for itself.

Both directions take an SDK value you set up: Tools takes a connected *sdk.ClientSession, and AddTools and Serve take an *sdk.Server. Transports, OAuth and connection pools stay the SDK’s job. The examples on this page connect a client to a server in memory, the way weft’s own tests do:

mcpx/mcpx.go
// connect runs srv over an in-memory transport and returns a client
// session connected to it. A real client dials the server instead:
// sdk.CommandTransport for a subprocess, sdk.StreamableClientTransport
// for HTTP.
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: "support-app", Version: "1"}, nil)
return client.Connect(ctx, clientSide, nil)
}

mcpx/mcpx.go on GitHub

The loop, the two seams, the manifest and wefttest treat an imported tool like any other: it is a weft.RawTool. TestRoundTripIsLossless pins the property both directions rest on: a tool exported with AddTools and imported back with Tools keeps its schema and answers the same. More examples for both directions live in mcp/examples/ and run offline over in-memory transports.

mcp.Tools(ctx, sess, opts...) lists the session’s tools, every page of the listing, and returns one weft tool per server tool. Each keeps the server’s name and description. Its input schema is the document the server sent, kept whole through weft.ParseSchema, so keywords weft’s Schema type cannot hold, such as enum or oneOf, reach the openai and anthropic adapters whole. An object output schema, when the server sends one, is recorded on the tool too.

The google adapter cannot send the document whole. It decodes the schema into the Gemini SDK’s genai.Schema type, which keeps the keywords it has a field for and silently drops the rest:

Gemini receivesKeywords
Kepttype, format, title, description, enum (string values), default, example, nullable, properties, required, propertyOrdering, minProperties, maxProperties, items, minItems, maxItems, minLength, maxLength, pattern, minimum, maximum, anyOf
Droppedeverything else, including oneOf, allOf, not, const, $ref, $defs, additionalProperties, exclusiveMinimum, exclusiveMaximum, multipleOf and uniqueItems
Kept when the document does not decodetype, format, description, required, items and properties, recursively; a node whose type was an array keeps no type

The third row is the fallback for a document with a value genai.Schema cannot hold, such as a numeric enum value or a type given as an array. One such value anywhere puts the whole document on the fallback, so every other keyword is dropped from every node, not only from the one that failed. A property described only by oneOf reaches Gemini as an unconstrained node rather than disappearing.

These options shape the import, all of type mcp.Option; mcp.Server, mcp.Transport and mcp.CallerMeta only change what is recorded (and, for CallerMeta, what the server is told):

OptionEffect
mcp.Server(name), mcp.Transport(kind)Name the server and how it is reached, for the record (MCP identity)
mcp.CallerMeta()Sends each call’s caller in params._meta (Link a served run to its caller)
mcp.Prefix(p)Prepends p to every imported name (search becomes gh_search), so two servers’ tools can share one agent. The remote call still uses the server’s name.
mcp.Policy(opts...)Applies tool options to every imported tool: weft.Timeout, weft.MaxResultBytes, weft.RequireApproval and weft.WrapTools work as on any tool. weft.StrictInput has no effect: a raw tool gets the model’s arguments as sent, and validation is the server’s.

A call forwards the model’s argument bytes to tools/call unchanged; empty or null arguments go as {}. The result comes back as text: the JSON of structuredContent when the server sends it, otherwise the text items joined by newlines. Images, audio and resources become one-line markers such as [image image/png, 2048 bytes], because a weft transcript carries no binary tool results.

Every remote failure is data the model sees, never a run error. The execute_tool span tells the three kinds apart by error.type:

error.typeThe callWhat the model sees
mcp_tool_errorthe server answered with an isError result: its tool failedthe server’s text verbatim, matching mcp.ErrToolError with errors.Is; an empty one reads mcp: tool returned an error
mcp_rpc_errorthe server answered with a JSON-RPC error: its handler failed, the tool is not listed, the arguments were refusedmcp: <err>
mcp_transportno answer: a closed session, a stdio stream at EOF, a refused or dropped connection, a 5xx or 429 with no JSON-RPC bodymcp: <err>, the cause unwrapped. A cancelled call’s error.type is the context error’s name, not mcp_transport

Before 0.20.0 a JSON-RPC error answer read mcp_transport too. Studio says the three as “MCP tool error”, “MCP refused the call” and “MCP unreachable”, and its call graph counts them per server.

A server’s annotations set one default. A tool the server does not mark readOnlyHint is Sequential: foreign tools run one at a time unless the server says parallel is safe. Policy runs after that default, so it cannot undo it, and it can add RequireApproval but never remove it.

Tools does not own the session and never closes it. For a server whose list changes, set the SDK’s ToolListChangedHandler to call Tools again into a slice under a mutex, and serve the slice through weft.ToolSource: the package example ExampleTools_toolSource shows the shape. ExampleTools is the minimal import.

WEFT_MODEL_REQUESTS=deny governs model requests only. A tools/call is not one, so imported tools still run under deny, like any handler that makes a network call.

Name the server when you import its tools:

mcpx/identity.go
tools, err := mcp.Tools(ctx, sess,
mcp.Server("github"), // origin mcp:github: the tools record, weft.tool.origin, the call graph
mcp.Transport("memory"), // how the session reaches it: stdio, http, sse, your word
mcp.CallerMeta(), // send this run and call in params._meta (servers you run only)
)

mcpx/identity.go on GitHub

mcp.Server(name) names the server an import comes from, for the record only. Every imported tool’s Origin reads mcp:<name>. That is the tools record’s source, the execute_tool span’s weft.tool.origin and the node Studio’s call graph draws. mcp.Transport(kind) says how the session reaches it: stdio, http, sse, memory or your own word, since the SDK’s session does not say. Without Server the origin is plain mcp and no server is named. weft never names a node after the server’s own initialize answer, which is untrusted. Neither option changes what the model sees.

The tools record carries each tool’s origin in parts as source_detail, weft.SourceDetail: Server, Transport, Prefix and RemoteName, the tool’s name on the server. Its Skipped field holds the tools the importer left out of the same source, each a weft.SkippedImport with a Name and a Reason. The record lists them once per source in skipped[], as {name, reason, source}. It keeps at most 64, with skipped_more counting the rest, and cuts names at 128 bytes. Neither source_detail nor skipped[] is part of the catalog hash. A tool you build yourself sets its parts with weft.OriginDetail. The package examples ExampleServer and ExampleOriginDetail show both.

Studio’s Request pane names each tool’s origin in parts and lists the skipped tools greyed; the call graph draws mcp:<server> with its calls, its slowest call and its failures by kind (“1 unreachable · 1 refused · 1 tool error”).

The agents level of the graph scale for a run whose tools come from an MCP server: billing-desk calling an mcp:billing node, 3 calls, 3 failed (1 unreachable, 1 refused, 1 tool error), with the get_invoice call's MCP tool error in the drawerThe agents level of the graph scale for a run whose tools come from an MCP server: billing-desk calling an mcp:billing node, 3 calls, 3 failed (1 unreachable, 1 refused, 1 tool error), with the get_invoice call's MCP tool error in the drawer
The agents level of the graph scale: billing-desk calling the mcp:billing node, its three calls unreachable, refused and a tool error.

A tool the bridge cannot import fails that tool, not the listing. Tools returns every importable tool and, beside them, an *mcp.ImportError naming each one it left out. Read it with errors.As:

mcpx/mcpx.go
tools, err := mcp.Tools(ctx, sess)
var skipped *mcp.ImportError
if errors.As(err, &skipped) { // the importable tools are in tools; these are not
for _, s := range skipped.Skipped {
fmt.Fprintf(w, "skipped %q (listing entry %d): %v\n", s.Name, s.Index, s.Err)
}
err = nil // a warning here; return it to make it a stop
}
if err != nil { // a listing failure: transport, ctx
return err
}

mcpx/mcpx.go on GitHub

ImportError.Skipped is a list of mcp.SkippedTool: Name (the server-side name, empty when the name was the problem), Index (the position in the listing) and Err (why). ImportError.Unwrap returns each tool’s cause, so errors.Is against a ParseSchema failure works through the report.

A tool is skipped for:

  • an input schema weft cannot key on: a non-object root, a $ref root, or no schema;
  • an empty name;
  • a name repeated in the listing (the first importable occurrence stands);
  • a nil entry.

ImportError.Source is the imported tools’ origin (mcp:<server>, or mcp). An imported tool carries its server’s skipped tools into the tools record, so a partial import records them on its own. When every tool was skipped, no imported tool can: pass ImportError.Option() to weft.New and the agent records the skips itself, through weft.SkippedImports. It is harmless beside importable tools; the record lists each skip once (ExampleImportError_Option, and ExampleSkippedImports for a tool source of your own).

The slice is usable whether or not the error is set; you decide whether a skipped tool is a warning to log or a reason to stop. Any other error is a listing failure (the transport, or ctx ending, which returns the ctx error unchanged) and comes with no tools.

mcp.Serve(srv, agent, description) exposes an agent as one MCP tool named after the agent, plus each of the agent’s registered tools. mcp.AddTools(srv, tools...) exposes tools alone:

mcpx/mcpx.go
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
func(_ context.Context, in struct {
OrderID string `json:"order_id"`
}) (string, error) {
return "order " + in.OrderID + " has shipped", nil
})
refund := weft.Tool("refund", "Refund an order.",
func(_ context.Context, _ struct{}) (string, error) { return "refunded", nil },
weft.RequireApproval())
support := weft.New(
wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}),
wefttest.Say("Order 1234 has shipped."),
),
weft.Name("support"), // Serve names the agent tool after the agent
lookup, refund,
)
srv := sdk.NewServer(&sdk.Implementation{Name: "support-server", Version: "1"}, nil)
mcp.Serve(srv, support, "Answer a customer's question about an order.")
tools := sdk.NewServer(&sdk.Implementation{Name: "tools-only", Version: "1"}, nil)
mcp.AddTools(tools, lookup) // tools alone, no agent; AddTools panics on refund

mcpx/mcpx.go on GitHub

The agent tool is weft.Subagent under the agent’s name: it takes {"prompt": string} and returns the run’s final text or submitted output. The description is all a client’s model reads to decide when to call the agent, so write it for routing. Serve requires a name set with weft.Name.

The two differ in how a call is dispatched:

AddToolsServe
DispatchToolDef.Invoke: the tool alonethe agent’s own tools: Agent.CallTool, through the agent’s WrapTools chain, so mw.Allow and mw.Audit see each call; the agent tool: the weft.Subagent’s own ToolDef.Invoke, outside that chain, while its child run’s tool calls go through the chain
A RequireApproval toolPanics at registration: MCP has no approval channelCalled directly, answers weft: tool call requires approval: tool "refund" with isError, without running; reached by the agent tool, see the gotcha on parking below
Timeout, MaxResultBytesNot appliedNot applied; the SDK’s request handling bounds the call
Tools from a ToolSource—Not listed; they still run inside the agent tool’s own steps
Recorded by weft/otelNo: a call outside a runthe agent’s own tools: no, since CallTool outside a run leaves no run, event or span; the agent tool: yes, its child run is recorded like any run

Every failure on the serving side is an MCP tool result with isError, carrying the text weft’s own model would see: undecodable arguments, a handler error, a panic. A tool with an output schema also returns its JSON as structuredContent; if its result text is not valid JSON, the call is an isError result instead, reading tool "<name>" advertised an output schema, so its result must be JSON; got non-JSON text, never structuredContent. AddTools panics on a nil tool or a name repeated within one call, but a name an earlier AddTools or Serve call registered on the same server is replaced without an error: the MCP SDK replaces same-named tools and offers no lookup. So an AddTools after Serve can silently shadow one of the agent’s tools, and the replacement runs outside the agent’s WrapTools chain.

Serve panics on a nil or unnamed agent and on a tool whose name collides with the agent’s. The package examples ExampleAddTools and ExampleServe call each from a client.

When one of your agents calls another you serve with mcp.Serve, the served run can record the call that made it. Opt in on the client with mcp.CallerMeta() beside mcp.Tools’ other options, as in MCP identity. Every call the imported tools make then sends two things in params._meta:

  • the W3C traceparent (and tracestate) of its execute_tool span;
  • mcp.MetaCaller, "dev.weftgo/caller", holding {"run_id", "call_id"}.

mcp.Serve and AddTools’ tools read it back. The served run’s invoke_agent span starts its own trace with an OpenTelemetry link to the caller’s span, never as the caller’s child. So the client’s sampling flag never decides whether the server records the run. The run records weft.caller.run.id, weft.caller.call.id and weft.caller.remote "true": a link, never weft.parent.*. A remote caller is the caller’s own statement, so readers never place a run by it. The run stays top-level, and Studio says “started over MCP by run … in another process (not linked)”. A missing or malformed _meta links nothing and refuses nothing.

CallerMeta is off by default: the run and call ids and the trace state name your runs to the server. Send them to servers you run, not to a third party’s.

Code that is not an MCP server, such as a queue consumer or an RPC handler, links its runs the same way with weft.WithCaller:

mcpx/identity.go
ctx = weft.WithCaller(ctx, weft.Caller{RunID: job.RunID, CallID: job.CallID})
res, err := worker.Generate(ctx, weft.Prompt(job.Prompt)) // records weft.caller.* and weft.caller.remote

mcpx/identity.go on GitHub

Every run started directly on that context, not inside a tool call, records the caller. A Caller’s Span adds the OpenTelemetry link. No run started inside such a run inherits the caller. The examples ExampleCallerMeta, ExampleServe (callerLink) and ExampleWithCaller show each side.

What the bridge does not do, by decision:

  • Resources, prompts and sampling are not bridged; only tools are.
  • Progress notifications are not surfaced. The calling step’s ToolStart and ToolFinish bracket the remote call.
  • Elicitation is not answered. A server that asks fails the call, as a tool error.
  • Schema bytes are re-encoded. The SDK’s client decodes the listed schema before Tools sees it, so the kept document has keys in canonical order, and an integer above 2^53 is rounded through float64.
  • A non-object output schema has no weft form and is not recorded; the result text is the tool’s output either way.
  • An unconstrained schema node reaches OpenAI and Anthropic as {}.

Before the tag mcp v0.1.4 (2026-09-27, when weft/mcp was its own module), one unparseable input schema failed the whole import. Since then it fails that tool alone, as the previous section describes.

mcpx/mcpx.go imports a stand-in GitHub server’s tools into an agent, imports from a server with one bad tool, and serves an agent and a tool, all in memory:

mcpx/mcpx.go
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"time"
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/weftgo/weft"
"github.com/weftgo/weft/mcp"
"github.com/weftgo/weft/wefttest"
)
// connect runs srv over an in-memory transport and returns a client
// session connected to it. A real client dials the server instead:
// sdk.CommandTransport for a subprocess, sdk.StreamableClientTransport
// for HTTP.
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: "support-app", Version: "1"}, nil)
return client.Connect(ctx, clientSide, nil)
}
// githubServer stands in for a remote MCP server with three tools: a
// read-only search whose schema carries an enum, a write the server does
// not mark read-only, and one that always answers isError.
func githubServer() *sdk.Server {
srv := sdk.NewServer(&sdk.Implementation{Name: "github", Version: "0"}, nil)
srv.AddTool(&sdk.Tool{
Name: "search_issues",
Description: "Search issues by state.",
InputSchema: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"},"state":{"type":"string","enum":["open","closed"]}},"required":["q"]}`),
Annotations: &sdk.ToolAnnotations{ReadOnlyHint: true},
}, func(_ context.Context, req *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "2 open issues match: #12, #31"}}}, nil
})
srv.AddTool(&sdk.Tool{
Name: "create_issue",
Description: "Open an issue.",
InputSchema: json.RawMessage(`{"type":"object","properties":{"title":{"type":"string"}},"required":["title"]}`),
}, func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "opened #40"}}}, nil
})
srv.AddTool(&sdk.Tool{
Name: "close_issue",
Description: "Close an issue.",
InputSchema: json.RawMessage(`{"type":"object","properties":{"id":{"type":"integer"}},"required":["id"]}`),
}, func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
return &sdk.CallToolResult{IsError: true, Content: []sdk.Content{&sdk.TextContent{Text: "issue #12 is locked"}}}, nil
})
return srv
}
// importTools imports the server's tools into an agent and runs one step
// that calls two of them.
func importTools(ctx context.Context, w io.Writer) error {
sess, err := connect(ctx, githubServer())
if err != nil {
return err
}
defer sess.Close()
tools, err := mcp.Tools(ctx, sess,
mcp.Prefix("gh_"), // search_issues → gh_search_issues
mcp.Policy(weft.Timeout(10*time.Second)), // per-tool policy on every imported tool
)
var skipped *mcp.ImportError
if errors.As(err, &skipped) {
fmt.Fprintln(w, "skipped:", skipped) // some tools were left out; the rest are in tools
} else if err != nil {
return err // the listing itself failed
}
opts := []weft.Option{weft.Name("triage")}
for _, t := range tools {
opts = append(opts, t) // an imported tool is an ordinary *weft.ToolDef
}
model := wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "gh_search_issues", Args: `{"q":"crash","state":"open"}`},
wefttest.Call{Name: "gh_close_issue", Args: `{"id":12}`},
),
wefttest.Say("Two issues are open; #12 is locked."),
)
agt := weft.New(model, opts...)
res, err := agt.Generate(ctx, weft.Prompt("Triage the crash reports."))
if err != nil {
return err
}
for _, t := range tools {
schema, _ := json.Marshal(t.InputSchema)
fmt.Fprintf(w, "imported %s %s\n", t.Name, schema)
}
for _, r := range res.Steps[0].Results {
fmt.Fprintf(w, "%s → %q error=%v\n", r.Name, r.Content, r.IsError)
}
fmt.Fprintln(w, "answer:", res.Text())
// The isError result is a tool error the model sees; middleware and
// your own code match it with errors.Is.
close := tools[0] // gh_close_issue: Tools keeps the server's listing order
_, err = close.Invoke(ctx, json.RawMessage(`{"id":12}`))
fmt.Fprintf(w, "%s: errors.Is(err, mcp.ErrToolError) = %v\n", close.Name, errors.Is(err, mcp.ErrToolError))
return nil
}
// importWithSkips imports from a server whose listing holds one tool the
// bridge cannot import.
func importWithSkips(ctx context.Context, w io.Writer) error {
srv := sdk.NewServer(&sdk.Implementation{Name: "mixed", Version: "0"}, nil)
ok := func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "ok"}}}, nil
}
srv.AddTool(&sdk.Tool{Name: "ping", InputSchema: json.RawMessage(`{"type":"object"}`)}, ok)
// The Go SDK refuses a non-object root at AddTool; a server written in
// another language can list one, so the example swaps it in afterwards.
odd := &sdk.Tool{Name: "nullable", InputSchema: json.RawMessage(`{"type":"object"}`)}
srv.AddTool(odd, ok)
odd.InputSchema = json.RawMessage(`{"type":["object","null"]}`)
sess, err := connect(ctx, srv)
if err != nil {
return err
}
defer sess.Close()
tools, err := mcp.Tools(ctx, sess)
var skipped *mcp.ImportError
if errors.As(err, &skipped) { // the importable tools are in tools; these are not
for _, s := range skipped.Skipped {
fmt.Fprintf(w, "skipped %q (listing entry %d): %v\n", s.Name, s.Index, s.Err)
}
err = nil // a warning here; return it to make it a stop
}
if err != nil { // a listing failure: transport, ctx
return err
}
for _, t := range tools {
fmt.Fprintln(w, "imported", t.Name)
}
return nil
}
// serveAgent exposes a tool and an agent on an MCP server and calls them
// as an MCP client would.
func serveAgent(ctx context.Context, w io.Writer) error {
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
func(_ context.Context, in struct {
OrderID string `json:"order_id"`
}) (string, error) {
return "order " + in.OrderID + " has shipped", nil
})
refund := weft.Tool("refund", "Refund an order.",
func(_ context.Context, _ struct{}) (string, error) { return "refunded", nil },
weft.RequireApproval())
support := weft.New(
wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}),
wefttest.Say("Order 1234 has shipped."),
),
weft.Name("support"), // Serve names the agent tool after the agent
lookup, refund,
)
srv := sdk.NewServer(&sdk.Implementation{Name: "support-server", Version: "1"}, nil)
mcp.Serve(srv, support, "Answer a customer's question about an order.")
tools := sdk.NewServer(&sdk.Implementation{Name: "tools-only", Version: "1"}, nil)
mcp.AddTools(tools, lookup) // tools alone, no agent; AddTools panics on refund
sess, err := connect(ctx, srv)
if err != nil {
return err
}
defer sess.Close()
for t, err := range sess.Tools(ctx, nil) {
if err != nil {
return err
}
fmt.Fprintln(w, "listed", t.Name)
}
for _, c := range []struct {
name string
args map[string]any
}{
{"support", map[string]any{"prompt": "Where is order 1234?"}},
{"lookup_order", map[string]any{"order_id": "5678"}},
{"refund", map[string]any{}},
} {
out, err := sess.CallTool(ctx, &sdk.CallToolParams{Name: c.name, Arguments: c.args})
if err != nil {
return err
}
fmt.Fprintf(w, "%s → %q isError=%v\n", c.name, out.Content[0].(*sdk.TextContent).Text, out.IsError)
}
sess2, err := connect(ctx, tools)
if err != nil {
return err
}
defer sess2.Close()
out, err := sess2.CallTool(ctx, &sdk.CallToolParams{Name: "lookup_order", Arguments: map[string]any{"order_id": "42"}})
if err != nil {
return err
}
fmt.Fprintf(w, "tools-only lookup_order → %q\n", out.Content[0].(*sdk.TextContent).Text)
return nil
}
// run is the page's complete example.
func run(ctx context.Context, w io.Writer) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel() // stops the in-memory servers
for _, demo := range []func(context.Context, io.Writer) error{importTools, importWithSkips, serveAgent} {
if err := demo(ctx, w); err != nil {
return err
}
}
return nil
}

View mcpx/mcpx.go on GitHub

Run it from docs-site/examples:

Terminal window
go run ./mcpx
go test ./mcpx
imported gh_close_issue {"properties":{"id":{"type":"integer"}},"required":["id"],"type":"object"}
imported gh_create_issue {"properties":{"title":{"type":"string"}},"required":["title"],"type":"object"}
imported gh_search_issues {"properties":{"q":{"type":"string"},"state":{"enum":["open","closed"],"type":"string"}},"required":["q"],"type":"object"}
gh_search_issues → "2 open issues match: #12, #31" error=false
gh_close_issue → "issue #12 is locked" error=true
answer: Two issues are open; #12 is locked.
gh_close_issue: errors.Is(err, mcp.ErrToolError) = true
skipped "nullable" (listing entry 0): weft: ParseSchema: top-level type must be "object", got ""
imported ping
listed lookup_order
listed refund
listed support
support → "Order 1234 has shipped." isError=false
lookup_order → "order 5678 has shipped" isError=false
refund → "weft: tool call requires approval: tool \"refund\"" isError=true
tools-only lookup_order → "order 42 has shipped"

The enum on state survived the import. The locked issue came back as an error result the model read, and the run went on.

  • Treat a server’s tool descriptions as untrusted input. They land in your model’s tool list, text you did not write. Read what Tools returns before registering it, or filter calls with mw.Allow. (Source: weft/README.md:862-867)
  • Expect foreign tools to run one at a time. A tool without readOnlyHint is Sequential, the conservative reading of an untrusted hint. (Source: weft/mcp/client.go:54-57, weft/mcp/client.go:164-190)
  • Do not return on every error from Tools. An *mcp.ImportError comes with the good tools; check for it with errors.As first. (Source: weft/mcp/client.go:89-110, weft/CHANGELOG.md:5718)
  • Keep a schema’d tool’s output JSON. Under AddTools and Serve, a tool with an OutputSchema whose result is not JSON becomes an isError result. That bites a RawTool given an output schema that returns plain text, and tool middleware that rewrites a typed tool’s output into prose. (Source: weft/mcp/server.go:195-214)
  • Check an imported schema against Gemini’s subset. On the google adapter, oneOf, $ref and the other keywords genai.Schema lacks are dropped without an error, so the model sees a looser schema than the server declared. Validate the arguments in the server, or keep such tools on openai or anthropic. (Source: weft/google/convert.go:354-381, weft/google/model_test.go:278-306)
  • Keep tool names unique across every registration on one server. A later AddTools or Serve replaces an earlier tool of the same name without an error, so check names yourself, or use mcp.Prefix on imported tools you re-export. (Source: weft/mcp/server.go:26-29, weft/mcp/server.go:151-163)
  • Use Serve, not AddTools, for an approval-gated tool. AddTools panics on it; Serve answers with the approval error instead of running it. (Source: weft/mcp/server.go:26-30, weft/mcp/server.go:172-177)
  • Do not serve an agent whose run can park. The agent tool is a weft.Subagent. When its child run parks, on a RequireApproval tool, a weft.ParkSource or middleware returning ErrApprovalRequired, the client gets an isError result: SUBAGENT_PENDING: agent "support" ended awaiting approval of 1 call(s). Nothing can approve it over MCP, so the call never runs. (Source: weft/mcp/server.go:150, weft/core/subagent.go:327-330, weft/core/loop.go:412)
  • Keep gated actions in your own app. The support agent above has a gated refund; its scripted run never calls it, but a real model routing a refund to it would park. Serve an agent built without gated tools, and resume parked runs in your app with weft.Approve or a session’s Decide (Require human approval for a tool). (Source: docs-site/examples/mcpx/mcpx.go:164-177)
  • Expect no Studio record of direct served calls. Serve dispatches the agent’s own tools through Agent.CallTool on the MCP request’s context, outside any run, so with otel.Install on they leave no run, event or span. Only calls to the agent tool show up in Studio, as the child run it starts. To keep a record of direct calls in your own logs, add mw.Audit to the agent’s WrapTools. Its lines do not reach Studio either: otel.Slog() bridges only lines logged on a span-carrying context, and these calls have none. (Source: weft/mcp/server.go:172-191; weft/core/loop.go:1691-1701)
  • Bound imported calls with mcp.Policy(weft.Timeout(d)). A remote call is a network call; the run’s tool timeout is what stops a hung server. (Source: weft/README.md:842, AGENTS.md rule 9)

Symbols used: mcp.Tools · mcp.Option · mcp.Prefix · mcp.Policy · mcp.ErrToolError · mcp.ImportError · ImportError.Unwrap · mcp.SkippedTool · mcp.AddTools · mcp.Serve · weft.RawTool · weft.ParseSchema · weft.ToolSource · weft.Subagent · weft.Name · weft.Timeout · weft.RequireApproval · ToolDef.Invoke · Agent.CallTool · wefttest.Script · Go MCP SDK mcp package