mcp

package module
v0.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2025 License: Apache-2.0 Imports: 6 Imported by: 0

README

wasmcp-go

Go SDK for building MCP (Model Context Protocol) handlers as WebAssembly components.

Installation

go get github.com/fastertools/wasmcp/src/sdk/wasmcp-go
import mcp "github.com/fastertools/wasmcp/src/sdk/wasmcp-go"

Usage

Basic Example
package main

import (
    "context"
    mcp "github.com/fastertools/wasmcp/src/sdk/wasmcp-go"
)

func init() {
    server := mcp.NewServer(
        &mcp.Implementation{Name: "my-server", Version: "v1.0.0"},
        nil,
    )
    
    // Add a simple tool
    mcp.AddTool(server, &mcp.Tool{
        Name:        "echo",
        Description: "Echo a message",
        InputSchema: mcp.Schema(`{
            "type": "object",
            "properties": {
                "message": {"type": "string"}
            },
            "required": ["message"]
        }`),
    }, func(ctx context.Context, args map[string]any) (string, error) {
        message := args["message"].(string)
        return "Echo: " + message, nil
    })
    
    server.Run(context.Background(), nil)
}

func main() {} // Required for TinyGo
Typed Handlers

For better type safety, use typed handlers with structs:

type EchoArgs struct {
    Message string `json:"message"`
}

func Echo(ctx context.Context, args EchoArgs) (string, error) {
    return "Echo: " + args.Message, nil
}

func init() {
    server := mcp.NewServer(
        &mcp.Implementation{Name: "my-server", Version: "v1.0.0"},
        nil,
    )
    
    mcp.AddTool(server, &mcp.Tool{
        Name:        "echo",
        Description: "Echo a message",
        InputSchema: mcp.Schema(`{
            "type": "object",
            "properties": {
                "message": {"type": "string", "description": "Message to echo"}
            },
            "required": ["message"]
        }`),
    }, mcp.TypedHandler(Echo))
    
    server.Run(context.Background(), nil)
}
Schema Generation

Since TinyGo has limited reflection support, schemas must be defined manually or generated at build time. We recommend:

  1. Manual schemas - Use mcp.Schema() with JSON strings (shown above)
  2. Build-time generation - Use a code generator (coming soon):
    # Future feature
    go run github.com/fastertools/wasmcp/cmd/mcp-gen ./...
    
    This will generate schemas from struct tags:
    type WeatherArgs struct {
        Location string `json:"location" mcp:"required,description:City name"`
        Units    string `json:"units" mcp:"enum:celsius|fahrenheit,default:celsius"`
    }
    

Building

# Build your handler
tinygo build -target=wasip2 -scheduler=asyncify -no-debug -o handler.wasm main.go

# Compose with server
wac plug --plug handler.wasm wasmcp-server.wasm -o composed.wasm

# Run
wasmtime serve -S cli -S http composed.wasm

API

mcp.Handle(func(*Handler))

Register your MCP handler. Must be called in an init() function.

Handler.Tool(name, description string, schema json.RawMessage, fn ToolFunc)

Register a tool that can be called by MCP clients.

Handler.Resource(uri, name, description, mimeType string, fn ResourceFunc)

Register a resource that can be read by MCP clients.

Handler.Prompt(name, description string, arguments []PromptArgument, fn PromptFunc)

Register a prompt template.

mcp.Schema(string) json.RawMessage

Helper to create JSON schema definitions inline.

HTTP Support

The SDK automatically enables WASI HTTP support, so you can use Go's standard net/http package directly:

// Standard net/http just works!
resp, err := http.Get("https://api.example.com/data")

// Concurrent requests with goroutines work too
var wg sync.WaitGroup
for _, url := range urls {
    wg.Add(1)
    go func(u string) {
        defer wg.Done()
        resp, _ := http.Get(u)
        // Process response
    }(url)
}
wg.Wait()

Notes

  • Requires TinyGo with wasip2 support
  • Compatible with any wasip2 runtime (Wasmtime, Spin, etc.)
  • Pure WebAssembly Component Model - no adapters needed

Documentation

Overview

Package mcp provides the Go SDK for building MCP (Model Context Protocol) handlers in WebAssembly components using pure wasip2.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddPrompt added in v0.2.4

func AddPrompt[In any](server *Server, prompt *Prompt, handler func(context.Context, In) ([]PromptMessage, error))

AddPrompt adds a prompt to the server with a generic typed handler. The handler is automatically wrapped to unmarshal JSON arguments into the In type.

func AddTool added in v0.2.4

func AddTool[In any](server *Server, tool *Tool, handler func(context.Context, In) (*CallToolResult, error))

AddTool adds a tool to the server with a generic typed handler. The handler is automatically wrapped to unmarshal JSON arguments into the In type.

The handler should have the signature:

func(ctx context.Context, args In) (*CallToolResult, error)

For tools that return simple text, you can return a CallToolResult with TextContent. The In type should match your tool's input schema.

Since TinyGo has limited reflection, you must manually provide the input schema. Use the Schema() helper to create schemas from JSON strings.

func ObjectSchema added in v0.2.4

func ObjectSchema(properties map[string]any) json.RawMessage

ObjectSchema creates a JSON schema for an object with properties.

func RequiredObjectSchema added in v0.2.4

func RequiredObjectSchema(properties map[string]any, required []string) json.RawMessage

RequiredObjectSchema creates a JSON schema for an object with required properties.

func Schema

func Schema(s string) json.RawMessage

Schema creates a json.RawMessage from a JSON string.

Types

type CallToolResult added in v0.2.4

type CallToolResult struct {
	Content []Content `json:"content"`
	IsError bool      `json:"isError,omitempty"`
}

CallToolResult represents the result of calling a tool.

type Content added in v0.2.4

type Content interface {
	// contains filtered or unexported methods
}

Content represents content in a tool result.

type Implementation added in v0.2.4

type Implementation struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

Implementation defines the server implementation details.

type Prompt added in v0.2.4

type Prompt struct {
	Name        string           `json:"name"`
	Description string           `json:"description,omitempty"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

Prompt represents an MCP prompt definition.

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required"`
}

PromptArgument defines an argument for a prompt.

type PromptMessage

type PromptMessage struct {
	Role    string `json:"role"` // "user" or "assistant"
	Content string `json:"content"`
}

PromptMessage represents a message in a prompt conversation.

type Resource added in v0.2.4

type Resource struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	MimeType    string `json:"mimeType,omitempty"`
}

Resource represents an MCP resource definition.

type Server added in v0.2.4

type Server struct {
	// contains filtered or unexported fields
}

Server represents an MCP server instance. In WASM components, there's only one global server.

func NewServer added in v0.2.4

func NewServer(impl *Implementation, options any) *Server

NewServer creates a new MCP server. In WASM components, this returns the global server instance.

func (*Server) AddResource added in v0.2.4

func (s *Server) AddResource(resource *Resource, handler func(context.Context) (string, error))

AddResource adds a resource to the server. Resources are read-only and return text or binary content.

func (*Server) Run added in v0.2.4

func (s *Server) Run(ctx context.Context, transport any) error

Run initializes the WASM exports. Call this in init().

type TextContent added in v0.2.4

type TextContent struct {
	Text string `json:"text"`
}

TextContent represents text content.

type Tool added in v0.2.4

type Tool struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"inputSchema,omitempty"`
}

Tool represents an MCP tool definition.

Directories

Path Synopsis
cmd
extract-wit command
Command extract-wit extracts embedded WIT files to a specified directory.
Command extract-wit extracts embedded WIT files to a specified directory.
internal
assets
Package assets contains embedded WIT files for the wasmcp-go SDK.
Package assets contains embedded WIT files for the wasmcp-go SDK.
wasmcp
mcp/handler
Package handler represents the exported interface "wasmcp:mcp/handler@0.1.0".
Package handler represents the exported interface "wasmcp:mcp/handler@0.1.0".
mcp/mcp-handler
Package mcphandler represents the world "wasmcp:mcp/mcp-handler@0.1.0".
Package mcphandler represents the world "wasmcp:mcp/mcp-handler@0.1.0".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL