MCP Integration
Goa-AI provides first-class support for integrating MCP (Model Context Protocol) servers into your agents. MCP toolsets allow agents to consume tools from external MCP servers through generated wrappers and callers.
The handwritten callers currently implement the MCP 2025-06-18 tool
contract. They initialize a session, require the server’s tools capability, and
invoke tools/call. This page does not claim support for the complete MCP
surface such as prompts or resources.
Overview
MCP integration follows this workflow:
- Service design: Declare the MCP server via Goa’s MCP DSL
- Agent design: Reference that suite via a toolset declared with
FromMCP(...)orFromExternalMCP(...) - Code generation: Produces the MCP JSON-RPC server (when Goa-backed) plus runtime registration helpers and toolset-owned specs/codecs for the suite
- Runtime wiring: Instantiate an HTTP or stdio
mcpruntime.Caller. The HTTP caller accepts either a JSON response or an HTTP event stream. Generated helpers register the toolset and adapt JSON-RPC errors intoplanner.ToolFailurevalues - Planner execution: Planners construct calls with generated typed tool descriptors; the runtime forwards canonical JSON to the MCP caller, records results, and surfaces structured telemetry
Declaring MCP Toolsets
In Service Design
First, declare the MCP server in your Goa service design:
package design
import (
. "goa.design/goa/v3/dsl"
. "goa.design/goa-ai/dsl"
)
var _ = Service("assistant", func() {
Description("MCP server for assistant tools")
MCP("assistant-mcp", "1.0.0", ProtocolVersion("2025-06-18"))
JSONRPC(func() {
POST("/mcp")
})
Method("search", func() {
Payload(func() {
Attribute("query", String, "Search query")
Required("query")
})
Result(func() {
Attribute("results", ArrayOf(String), "Search results")
Required("results")
})
Tool("search", "Search documents by query")
})
})
In Agent Design
Then reference the MCP suite in your agent:
var AssistantSuite = Toolset(FromMCP("assistant", "assistant-mcp"))
var _ = Service("orchestrator", func() {
Agent("chat", "Conversational runner", func() {
Use(AssistantSuite)
RunPolicy(func() {
DefaultCaps(MaxToolCalls(8))
TimeBudget("2m")
})
})
})
External MCP Servers with Inline Schemas
For external MCP servers (not Goa-backed), declare tools with inline schemas:
var RemoteSearch = Toolset("remote-search", FromExternalMCP("remote", "search"), func() {
Tool("web_search", "Search the web", func() {
Args(func() { Attribute("query", String) })
Return(func() { Attribute("results", ArrayOf(String)) })
})
})
Agent("helper", "", func() {
Use(RemoteSearch)
})
Runtime Wiring
At runtime, instantiate an MCP caller and register the toolset:
import (
mcpruntime "goa.design/goa-ai/runtime/mcp"
mcpassistant "example.com/assistant/gen/assistant/mcp_assistant"
)
// Create an HTTP MCP caller.
caller, err := mcpruntime.NewHTTPCaller(ctx, mcpruntime.HTTPOptions{
Endpoint: "https://assistant.example.com/mcp",
ClientInfo: mcpruntime.ClientInfo{
Name: "my-agent",
Version: "1.0.0",
},
})
if err != nil {
log.Fatal(err)
}
// Register the MCP toolset
if err := mcpassistant.RegisterAssistantAssistantMcpToolset(ctx, rt, caller); err != nil {
log.Fatal(err)
}
MCP Caller Types
Goa-AI supports HTTP and stdio through the runtime/mcp package. Both callers
implement the Caller interface:
type Caller interface {
CallTool(ctx context.Context, req CallRequest) (CallResponse, error)
}
type CallRequest struct {
Tool string
Payload json.RawMessage
}
type CallResponse struct {
Content []ContentBlock
StructuredContent json.RawMessage
}
HTTP Caller
For MCP servers accessible via HTTP JSON-RPC:
import mcpruntime "goa.design/goa-ai/runtime/mcp"
caller, err := mcpruntime.NewHTTPCaller(ctx, mcpruntime.HTTPOptions{
Endpoint: "https://assistant.example.com/mcp",
Client: customHTTPClient, // Optional; defaults to a client with a 30-second timeout.
ClientInfo: mcpruntime.ClientInfo{
Name: "my-agent",
Version: "1.0.0",
},
InitTimeout: 10 * time.Second, // Optional initialization timeout.
})
The HTTP caller performs the MCP initialize handshake on creation. It sends
each JSON-RPC 2.0 message as an HTTP POST to the configured endpoint. Tool
responses may be JSON or an HTTP event stream; a separate SSE caller is not
needed.
Stdio Caller
For MCP servers running as subprocesses communicating via stdin/stdout:
import mcpruntime "goa.design/goa-ai/runtime/mcp"
caller, err := mcpruntime.NewStdioCaller(ctx, mcpruntime.StdioOptions{
Command: "mcp-server",
Args: []string{"--config", "config.json"},
Env: []string{"MCP_DEBUG=1"}, // Added to the current environment.
Dir: "/path/to/workdir",
ClientInfo: mcpruntime.ClientInfo{
Name: "my-agent",
Version: "1.0.0",
},
InitTimeout: 10 * time.Second, // Optional initialization timeout.
})
defer caller.Close() // Clean up subprocess
The stdio caller launches the command as a subprocess, performs the MCP initialize handshake, and maintains the session across tool invocations. Call Close() to terminate the subprocess when done.
CallerFunc Adapter
For custom caller implementations or testing:
import mcpruntime "goa.design/goa-ai/runtime/mcp"
// Adapt a function to the Caller interface
caller := mcpruntime.CallerFunc(func(ctx context.Context, req mcpruntime.CallRequest) (mcpruntime.CallResponse, error) {
content, structured, err := myCustomMCPCall(ctx, req.Tool, req.Payload)
if err != nil {
return mcpruntime.CallResponse{}, err
}
return mcpruntime.CallResponse{
Content: content,
StructuredContent: structured,
}, nil
})
Goa-Generated JSON-RPC Caller
For Goa-generated MCP clients that wrap service methods:
caller, err := mcpassistant.NewCaller(ctx, client, mcpruntime.ClientInfo{
Name: "my-agent",
Version: "1.0.0",
})
Tool Execution Flow
- Planner returns tool calls constructed from the generated MCP tool
descriptors, or forwards validated model calls with
planner.ToolRequestFromModelCall - Runtime validates the complete planner result and assigns execution IDs,
producing
runtime.ToolCallvalues - Runtime detects MCP toolset registration
- Forwards the runtime call’s canonical JSON payload to the MCP caller
- The MCP caller uses HTTP or stdio and handles the JSON-RPC protocol. An HTTP response may be JSON or an event stream
- Decodes result using generated codec
- Returns
ToolResultto planner
Error Handling
Generated helpers adapt JSON-RPC errors into planner.ToolFailure values:
- Validation errors → invalid-call failures with exact correction evidence
- Network errors → unavailable or timeout failures with an explicit replanning or finish action
- Server errors → structured causes preserved in the failure
This gives MCP and native toolsets the same enforced recovery contract.
Failures returned by a tool become ToolFailure. An invalid completed planner
result becomes OutputContractError instead; it is rejected without another
model request and is not presented as a tool failure.
Complete Example
Design
package design
import (
. "goa.design/goa/v3/dsl"
. "goa.design/goa-ai/dsl"
)
// MCP server service
var _ = Service("assistant", func() {
Description("MCP server for assistant tools")
MCP("assistant-mcp", "1.0.0", ProtocolVersion("2025-06-18"))
JSONRPC(func() {
POST("/mcp")
})
Method("search", func() {
Payload(func() {
Attribute("query", String, "Search query")
Required("query")
})
Result(func() {
Attribute("results", ArrayOf(String), "Search results")
Required("results")
})
Tool("search", "Search documents by query")
})
})
// Agent that uses MCP tools
var AssistantSuite = Toolset(FromMCP("assistant", "assistant-mcp"))
var _ = Service("orchestrator", func() {
Agent("chat", "Conversational runner", func() {
Use(AssistantSuite)
RunPolicy(func() {
DefaultCaps(MaxToolCalls(8))
TimeBudget("2m")
})
})
})
Runtime
package main
import (
"context"
"log"
mcpruntime "goa.design/goa-ai/runtime/mcp"
chat "example.com/assistant/gen/orchestrator/agents/chat"
mcpassistant "example.com/assistant/gen/assistant/mcp_assistant"
"goa.design/goa-ai/runtime/agent/runtime"
storageinmem "goa.design/goa-ai/runtime/agent/storage/inmem"
)
func main() {
rt := runtime.New(storageinmem.New())
ctx := context.Background()
// Wire MCP caller
caller, err := mcpruntime.NewHTTPCaller(ctx, mcpruntime.HTTPOptions{
Endpoint: "https://assistant.example.com/mcp",
ClientInfo: mcpruntime.ClientInfo{
Name: "my-agent",
Version: "1.0.0",
},
})
if err != nil {
log.Fatal(err)
}
if err := mcpassistant.RegisterAssistantAssistantMcpToolset(ctx, rt, caller); err != nil {
log.Fatal(err)
}
// Register agent
if err := chat.RegisterChatAgent(ctx, rt, chat.ChatAgentConfig{
Planner: &MyPlanner{},
}); err != nil {
log.Fatal(err)
}
// Run agent
client := chat.NewClient(rt)
// ... use client ...
}
Planner
Your planner can reference MCP tools just like native toolsets:
func (p *MyPlanner) PlanStart(ctx context.Context, in *planner.PlanInput) (*planner.PlanResult, error) {
call, err := planner.NewToolRequest(
mcpspecs.SearchTool(),
&mcpspecs.SearchPayload{Query: "golang tutorials"},
)
if err != nil {
return nil, err
}
return &planner.PlanResult{
ToolCalls: []planner.ToolRequest{call},
}, nil
}
Here mcpspecs is the generated specs package for the MCP toolset. When
forwarding a validated model-emitted tool call instead, use
planner.ToolRequestFromModelCall so its provider correlation ID is preserved.
Best Practices
- Let codegen manage registration: Use the generated helper to register MCP toolsets; avoid hand-written glue so codecs and structured failure recovery stay consistent
- Use typed callers: Prefer Goa-generated JSON-RPC callers when available for type safety
- Handle errors explicitly: Map MCP errors to
ToolFailurevalues with the correct failure kind and recovery action - Monitor telemetry: MCP calls emit structured telemetry events; use them for observability
- Choose the right transport: Use HTTP for remote servers and stdio for subprocess-based servers. The HTTP caller accepts JSON and event-stream responses
Next Steps
- Toolsets - Understand tool execution models
- Memory & Sessions - Manage state with transcripts and memory stores
- Production - Deploy with Temporal and streaming UI