---
title: Use MCP both ways
description: Import an MCP server's tools into a weft agent with mcp.Tools, and serve weft tools or a whole agent as an MCP server with mcp.AddTools and mcp.Serve.
url: https://weftgo.dev/docs/guides/mcp/
type: how-to
sources:
  - weft/mcp/client.go:17 (ErrToolError), 30-50 (the three failure kinds), 210-240 (ImportError.Source, Option), 300-345 (Server, Transport, CallerMeta), 405-455 (remoteError, transportError, transportCode, rpcError and their error.type)
  - weft/mcp/meta.go:1-60 (the caller link over params._meta, MetaCaller "dev.weftgo/caller", reporting only)
  - 'weft/core/caller.go:15-60 (Caller, WithCaller: the link, weft.caller.remote, readers keep the run top-level, no inheritance)'
  - docs-site/examples/mcpx/identity.go (mcp-identity, with-caller; TestImportNamed, run against ../weft-rc020b through a scratch go.work)
  - weft/core/tool.go:644-676 (SourceDetail.Skipped, SkippedImport Name and Reason); weft/core/observe.go:930-945 (a cancelled call's error.type is the context error's name)
  - weft/core/tool.go:645-680 (SourceDetail, SkippedImport); weft/facade.go (SkippedImports, OriginDetail)
  - 'weft/CHANGELOG.md:36, 38 (0.20.0: MCP identity; the caller link), 72-73 (0.20.0 breaking: mcp:<name> origin; mcp_rpc_error)'
  - weft/AGENTS.md:61-65 (block 1d)
  - weft/README.md:826-874 (MCP, both ways)
  - weft/mcp/doc.go:1-29
  - weft/mcp/client.go:15-17 (ErrToolError), 19-110 (Tools godoc), 111-208 (Tools), 210-284 (ImportError, SkippedTool), 286-357 (Option, Prefix, Policy), 364-431 (callHandler, remoteError, transportError), 453-488 (renderContent)
  - weft/mcp/server.go:14-47 (AddTools), 112-165 (Serve), 172-195 (chainHandler), 197-223 (toolResult, errorResult)
  - weft/mcp/server.go:26-29 (a name an earlier call registered is replaced, not refused), 151-163 (Serve registers through AddTools and s.AddTool)
  - weft/mcp/example_test.go:21 (ExampleAddTools), 51 (ExampleServe), 134 (ExampleTools), 169 (ExampleTools_toolSource)
  - weft/mcp/client_test.go:164 (TestToolsSkipsUnimportableSchemaAndReportsIt), 279 (TestToolsRemoteErrorIsData)
  - weft/mcp/roundtrip_test.go:17 (TestRoundTripIsLossless)
  - weft/docs/adr/0015-mcp-interop.md (Decision; Out of scope; Amendment 2026-09-27)
  - weft/CHANGELOG.md:5718, 5813, 6207, 6214, 6223
  - weft/core/errors.go:91 (ErrApprovalRequired)
  - weft/mcp/server.go:150 (Serve registers the agent tool as core.Subagent)
  - 'weft/mcp/server.go:172-191 (chainHandler: a.CallTool on the MCP request''s context); weft/core/loop.go:1691-1701 (CallTool outside a run: no run, no event, no span)'
  - 'weft/AGENTS.md:619-621 (block 9, otel.Slog: every line logged on a span-carrying context is an app log record under that span)'
  - weft/core/loop.go:412 (every run, a Subagent child's included, reads the agent's park sources)
  - 'weft/core/subagent.go:327-330 (a child that ended parked: SUBAGENT_PENDING, agent %q ended awaiting approval of %d call(s))'
  - 'weft/google/convert.go:343-352 (convertTool), 354-381 (genaiSchema: a JSON round trip into genai.Schema drops every keyword it lacks), 383-409 (structuredGenaiSchema: the fallback maps type, format, description, required, items, properties, for the whole document), 411-425 (normalizeGenaiTypes)'
  - 'weft/google/model_test.go:278-306 (TestSchemaConversionForeignRaw: enum, pattern, minimum kept; oneOf dropped to an unconstrained node)'
  - the genai v1.71.0 module, types.go lines 1937-2002 (the Schema struct's JSON fields)
  - 'weft/core/schema.go:101-108 (parseSchemaNode: a non-string type is left empty)'
  - weft/openai/convert.go:245-254 (the schema map sent as parameters); weft/anthropic/convert.go:308-341 (every top-level keyword rides ExtraFields)
  - docs-site/examples/mcpx/mcpx.go, mcpx_test.go TestRun, TestImportReportsSkippedTool, TestServeRefusesGatedTool
  - 'weft/mcp/server.go:195-214 (toolResult: structuredContent only for JSON text; non-JSON under an output schema is isError), 92, 191 (AddTools and Serve both answer through it)'
---

# Use MCP both ways

Package [`weft/mcp`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp) bridges weft and the Model Context Protocol in both directions, over the official Go MCP SDK. [`mcp.Tools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Tools) turns a connected server's tools into ordinary weft tools; [`mcp.AddTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#AddTools) and [`mcp.Serve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/mcpx.go)

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`.

## How it works

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](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0015-mcp-interop.md)). 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:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/mcpx.go)

The loop, the two seams, the manifest and `wefttest` treat an imported tool like any other: it is a [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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/`](https://github.com/weftgo/weft/tree/v0.20.2/mcp/examples) and run offline over in-memory transports.

## Import tools

`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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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 receives | Keywords |
|---|---|
| Kept | `type`, `format`, `title`, `description`, `enum` (string values), `default`, `example`, `nullable`, `properties`, `required`, `propertyOrdering`, `minProperties`, `maxProperties`, `items`, `minItems`, `maxItems`, `minLength`, `maxLength`, `pattern`, `minimum`, `maximum`, `anyOf` |
| Dropped | everything else, including `oneOf`, `allOf`, `not`, `const`, `$ref`, `$defs`, `additionalProperties`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf` and `uniqueItems` |
| Kept when the document does not decode | `type`, `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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Option); [`mcp.Server`, `mcp.Transport`](#mcp-identity) and [`mcp.CallerMeta`](#link-a-served-run-to-its-caller) only change what is recorded (and, for `CallerMeta`, what the server is told):

| Option | Effect |
|---|---|
| [`mcp.Server(name)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Server), [`mcp.Transport(kind)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Transport) | Name the server and how it is reached, for the record ([MCP identity](#mcp-identity)) |
| [`mcp.CallerMeta()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#CallerMeta) | Sends each call's caller in `params._meta` ([Link a served run to its caller](#link-a-served-run-to-its-caller)) |
| [`mcp.Prefix(p)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Prefix) | 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...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Policy) | 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.type` | The call | What the model sees |
|---|---|---|
| `mcp_tool_error` | the server answered with an `isError` result: its tool failed | the server's text verbatim, matching [`mcp.ErrToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ErrToolError) with `errors.Is`; an empty one reads `mcp: tool returned an error` |
| `mcp_rpc_error` | the server answered with a JSON-RPC error: its handler failed, the tool is not listed, the arguments were refused | `mcp: <err>` |
| `mcp_transport` | no answer: a closed session, a stdio stream at EOF, a refused or dropped connection, a 5xx or 429 with no JSON-RPC body | `mcp: <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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource): the package example [`ExampleTools_toolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Tools-ToolSource) shows the shape. [`ExampleTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Tools) 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.

## MCP identity

Name the server when you import its tools:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/identity.go)

[`mcp.Server(name)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Server) 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Transport) 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OriginDetail). The package examples [`ExampleServer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Server) and [`ExampleOriginDetail`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-OriginDetail) 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 drawer](https://weftgo.dev/docs/_astro/studio-mcp-graph.light.DiKum4Eo.webp)

*The agents level of the graph scale: billing-desk calling the mcp:billing node, its three calls unreachable, refused and a tool error.*

## Handle tools that cannot be imported

A tool the bridge cannot import fails that tool, not the listing. `Tools` returns every importable tool and, beside them, an [`*mcp.ImportError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError) naming each one it left out. Read it with `errors.As`:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/mcpx.go)

[`ImportError.Skipped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError) is a list of [`mcp.SkippedTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError.Option) to `weft.New` and the agent records the skips itself, through [`weft.SkippedImports`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SkippedImports). It is harmless beside importable tools; the record lists each skip once ([`ExampleImportError_Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-ImportError.Option), and [`ExampleSkippedImports`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-SkippedImports) 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.

## Serve an agent

`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:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/mcpx.go)

The agent tool is [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name).

The two differ in how a call is dispatched:

| | `AddTools` | `Serve` |
|---|---|---|
| Dispatch | [`ToolDef.Invoke`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.Invoke): the tool alone | the agent's own tools: [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#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` tool | Panics at registration: MCP has no approval channel | Called 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`, `MaxResultBytes` | Not applied | Not 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/otel` | No: a call outside a run | the 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-AddTools) and [`ExampleServe`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Serve) call each from a client.

## Link a served run to its caller

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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#CallerMeta) beside `mcp.Tools`' other options, as in [MCP identity](#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WithCaller):

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/identity.go)

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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-CallerMeta), [`ExampleServe (callerLink)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Serve-CallerLink) and [`ExampleWithCaller`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-WithCaller) show each side.

## Limits

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.

## Complete example

`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:

```go title="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
}
```

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

Run it from `docs-site/examples`:

```sh
go run ./mcpx
go test ./mcpx
```

```text
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.

## Best practices & gotchas

- **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](https://weftgo.dev/docs/guides/approvals/)). (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)

## See also

- [How do tools work?](https://weftgo.dev/docs/concepts/tools/)
- [Define tools at runtime: RawTool and ToolSource](https://weftgo.dev/docs/guides/dynamic-tools/)
- [Delegate to another agent (subagents)](https://weftgo.dev/docs/guides/subagents/)
- [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/)
- [Let Claude Code or Cursor read your runs (weft mcp)](https://weftgo.dev/docs/observe/weft-mcp/): a different thing, the CLI that serves Studio's read routes over MCP

Symbols used: [`mcp.Tools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Tools) · [`mcp.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Option) · [`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) · [`ImportError.Unwrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError.Unwrap) · [`mcp.SkippedTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#SkippedTool) · [`mcp.AddTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#AddTools) · [`mcp.Serve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Serve) · [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) · [`weft.ParseSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParseSchema) · [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`ToolDef.Invoke`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.Invoke) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [Go MCP SDK `mcp` package](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk@v1.8.0/mcp)
