### GOMCP Basic Client Example Source: https://github.com/localrivet/gomcp/blob/main/docs/getting-started/README.md Shows how to create a GOMCP client and call a registered tool. This example connects via stdio and invokes the 'add' tool with specific arguments, printing the result. ```go package main import ( "fmt" "log" "github.com/localrivet/gomcp/client" ) func main() { // Create a new client c, err := client.NewClient("stdio:///") if err != nil { log.Fatalf("Failed to create client: %v", err) } defer c.Close() // Call the "add" tool result, err := c.CallTool("add", map[string]interface{}{ "x": 5, "y": 3, }) if err != nil { log.Fatalf("Failed to call tool: %v", err) } fmt.Printf("Result: %v\n", result) } ``` -------------------------------- ### GOMCP Basic Server Example Source: https://github.com/localrivet/gomcp/blob/main/docs/getting-started/README.md Demonstrates how to create and run a basic GOMCP server. It registers a simple 'add' tool that sums two float64 numbers and listens for requests over stdio. ```go package main import ( "log" "github.com/localrivet/gomcp/server" ) func main() { // Create a new server ss := server.NewServer("example-server").AsStdio() // Register a tool ss.Tool("add", "Add two numbers", func(ctx *server.Context, args struct { X float64 `json:"x" required:"true"` Y float64 `json:"y" required:"true"` }) (float64, error) { return args.X + args.Y, nil }) // Start the server if err := ss.Run(); err != nil { log.Fatalf("Server error: %v", err) } } ``` -------------------------------- ### Run Go Quickstart Test Example Source: https://github.com/localrivet/gomcp/blob/main/examples/quickstart_test/README.md This command demonstrates how to navigate to the quickstart test directory and execute the test script. Running this test verifies that the transport configuration fix in the README quickstart example works correctly, allowing client creation without transport errors and confirming expected behavior like timeouts when no server is connected. ```bash cd examples/quickstart_test ``` ```bash go run main.go ``` -------------------------------- ### Install GOMCP Source: https://github.com/localrivet/gomcp/blob/main/docs/getting-started/README.md Installs the GOMCP library using the Go module system. This command fetches the latest version of the library. ```bash go get github.com/localrivet/gomcp ``` -------------------------------- ### GOMCP Server API Setup Source: https://github.com/localrivet/gomcp/blob/main/docs/api-reference/README.md Provides examples of setting up an MCP server using a fluent interface, including adding tools, resources, and prompts, and starting the server. ```go // Create a server server := server.NewServer("serverName").AsStdio() // Add a tool server.Tool("toolName", "description", toolHandler) // Add a resource server.Resource("/path/to/resource", "description", resourceHandler) // Add a prompt server.Prompt("promptName", "description", template) // Start the server server.Run() ``` -------------------------------- ### GoMCP Server Quick Start Source: https://github.com/localrivet/gomcp/blob/main/server/README.md Demonstrates the basic setup of a GoMCP server, including registering a tool and a resource, and starting the server using standard I/O. ```go package main import ( "fmt" "github.com/localrivet/gomcp/server" ) func main() { // Create a new server ssrv := server.NewServer("my-server") // Register a tool ssrv.Tool("hello", "Says hello to someone", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) { name, _ := args["name"].(string) if name == "" { name = "world" } return "Hello, " + name + "!", nil }) // Register a resource ssrv.Resource("/greeting/{name}", "A greeting resource", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) { name, _ := args["name"].(string) if name == "" { name = "world" } return "Hello, " + name + "!", nil }) // Start the server using standard I/O (default transport) if err := srv.AsStdio().Serve(); err != nil { panic(err) } } ``` -------------------------------- ### Build and Run GoMCP Server Example Source: https://github.com/localrivet/gomcp/blob/main/examples/README.md Demonstrates how to build and execute the GoMCP server example. This involves compiling the Go source code and then running the resulting executable to start the server. ```bash # Build the server example go build -o examples/server/server examples/server/main.go # Run the server ./examples/server/server ``` -------------------------------- ### Running the MCP Server Example Source: https://github.com/localrivet/gomcp/blob/main/examples/server_config/README.md Shows the command to execute the Go example. This process involves creating a sample configuration file, starting the configured MCP servers, establishing client connections, and performing sample operations. ```bash go run examples/server_config/main.go ``` -------------------------------- ### Define and Start Multiple Servers Source: https://github.com/localrivet/gomcp/blob/main/examples/server_registry/README.md Illustrates how to define multiple server configurations using `client.ServerDefinition` and start them concurrently using the `ServerRegistry`. This includes setting commands, arguments, and environment variables. ```go // Define multiple server configurations servers := map[string]client.ServerDefinition{ "math-server": { Command: execPath, Args: []string{"math-server"}, Env: map[string]string{ "SERVER_NAME": "Math Operations Server", }, }, "text-server": { Command: execPath, Args: []string{"text-server"}, // ... more config }, } // Start all servers for name, def := range servers { registry.StartServer(name, def) } ``` -------------------------------- ### Install GOMCP with Go Modules Source: https://github.com/localrivet/gomcp/blob/main/docs/installation/README.md Installs the GOMCP library using the `go get` command, which is the recommended method for integrating GOMCP into your Go projects. After installation, you can import the necessary packages into your code. ```bash go get github.com/localrivet/gomcp ``` ```go import ( "github.com/localrivet/gomcp/client" "github.com/localrivet/gomcp/server" ) ``` -------------------------------- ### Install GOMCP from Source Source: https://github.com/localrivet/gomcp/blob/main/docs/installation/README.md Installs the latest development version of GOMCP by cloning the repository and using `go install`. This method is useful for contributors or when needing the absolute latest code directly from the repository. ```bash git clone https://github.com/localrivet/gomcp.git cd gomcp go install ./... ``` -------------------------------- ### Add Transport Configuration to Go Quickstart Example Source: https://github.com/localrivet/gomcp/blob/main/examples/quickstart_test/README.md This snippet shows the corrected Go code for the README quickstart example. It includes the addition of `client.WithStdio()` to properly configure the transport layer, resolving the 'no transport configured' error encountered previously. This ensures the client can be created successfully. ```go c, err := client.NewClient("stdio:///", ``` ```go client.WithStdio(), // ← Added transport configuration ``` ```go client.WithProtocolVersion("2025-03-26"), ``` ```go client.WithProtocolNegotiation(true), ``` ```go ) ``` -------------------------------- ### Integrate Server Management into Applications Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/server-config.md Provides an example of integrating server management into a larger application structure. It covers starting MCP servers based on application configuration, obtaining clients for services, and ensuring clean shutdown. ```go type AppConfig struct { // Application configuration Port int LogLevel string // MCP server configuration MCPServers client.ServerConfig } func NewApplication(config AppConfig) *Application { app := &Application{ port: config.Port, logLevel: config.LogLevel, } // Start MCP servers based on configuration registry := client.NewServerRegistry() if err := registry.ApplyConfig(config.MCPServers); err != nil { log.Fatalf("Failed to start MCP servers: %v", err) } app.serverRegistry = registry // Get specific clients needed by the application aiClient, _ := registry.GetClient("ai-service") dbClient, _ := registry.GetClient("database-service") // Initialize application services with these clients app.aiService = NewAIService(aiClient) app.dbService = NewDatabaseService(dbClient) return app } func (a *Application) Shutdown() { // Shutdown MCP servers cleanly a.serverRegistry.StopAll() } ``` -------------------------------- ### Running GOMCP Examples with Go Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/README.md Demonstrates how to clone the GOMCP repository, navigate to the examples directory, and run specific Go examples. It also provides instructions for setting up necessary brokers like MQTT and NATS. ```bash # Clone the repository git clone https://github.com/localrivet/gomcp.git cd gomcp/examples # Run a specific example (e.g., HTTP example) go run http/http_example.go # For examples that require a broker (MQTT, NATS) # Make sure you have the broker running first: # docker run -d -p 1883:1883 eclipse-mosquitto # For MQTT # docker run -d -p 4222:4222 nats # For NATS ``` -------------------------------- ### Run MQTT Broker Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/mqtt-example.md Starts a Mosquitto MQTT broker using Docker. This is a prerequisite for running the MQTT transport example. ```bash docker run -d -p 1883:1883 eclipse-mosquitto ``` -------------------------------- ### Bash: Run HTTP Example Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/http-example.md Provides the command to execute the Go example demonstrating the HTTP transport. This allows users to run the server and client setup locally to test the communication. ```bash # Run the example directly go run examples/http/http_example.go ``` -------------------------------- ### Verify GOMCP Installation Source: https://github.com/localrivet/gomcp/blob/main/docs/installation/README.md A simple Go program to verify that GOMCP has been installed correctly by printing its version. This confirms that the library is accessible and functional in your environment. ```go package main import ( "fmt" "github.com/localrivet/gomcp" ) func main() { fmt.Printf("GOMCP Version: %s\n", gomcp.Version) } ``` -------------------------------- ### Bash: Run NATS Transport Example Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/nats-example.md Provides instructions on how to run the NATS transport example. It includes starting a NATS broker using Docker and executing the Go application. ```bash # Ensure a NATS broker is running docker run -d -p 4222:4222 nats # Run the example directly go run examples/nats/nats_example.go ``` -------------------------------- ### Install and Run godoc Source: https://github.com/localrivet/gomcp/blob/main/docs/api-reference/README.md Installs the `godoc` tool from the Go tools repository and starts a local HTTP server on port 6060. This allows you to view generated API documentation locally by navigating to `http://localhost:6060/pkg/github.com/localrivet/gomcp/`. ```bash go install golang.org/x/tools/cmd/godoc@latest godoc -http=:6060 ``` -------------------------------- ### Run MCP Sampling Client Source: https://github.com/localrivet/gomcp/blob/main/examples/sampling/README.md Starts the MCP sampling client. This client connects to a running server, sets up a sampling handler, and demonstrates various sampling scenarios. ```Bash cd client go run main.go ``` -------------------------------- ### Running the gRPC Example Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/grpc-example.md Provides instructions on how to navigate to the gRPC example directory and run the complete example, which includes the server, client, and automatic shutdown. ```bash # Navigate to the gRPC example directory cd examples/grpc # Run the complete gRPC example (server + client + automatic shutdown) go run . # Output shows: # - Server starting on :50051 # - Client connecting successfully # - Tool call execution with proper results # - Tools list with schema information # - Automatic graceful shutdown ``` -------------------------------- ### Configure MCP Server with MQTT Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/mqtt-example.md Sets up an MCP server and configures it to use the MQTT transport. It includes registering an echo tool and starting the server. ```go srv := server.NewServer("mqtt-example-server") srv.AsMQTT(brokerURL, mqtt.WithClientID("mcp-example-server"), mqtt.WithQoS(1), mqtt.WithTopicPrefix("mcp-example"), ) srv.Tool("echo", "Echo the message back", func(ctx *server.Context, args struct { Message string `json:"message"` }) (map[string]interface{}, error) { fmt.Printf("Server received: %s\n", args.Message) return map[string]interface{}{ "message": args.Message, }, nil }) if err := srv.Run(); err != nil { log.Fatalf("Server error: %v", err) } ``` -------------------------------- ### Build and Run Stdio Transport Example Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/stdio-example.md Provides the necessary bash commands to build the Go server executable and then run the client application, which in turn starts the server as a child process for stdio communication. ```bash # Build the server go build -o stdio-server examples/stdio/server/main.go # Run the client (which starts the server as a child process) go run examples/stdio/client/main.go ``` -------------------------------- ### Build and Run MCP Tool Discovery Example Source: https://github.com/localrivet/gomcp/blob/main/examples/list_tools/README.md Commands to build and execute the MCP tool discovery example from the command line. ```bash # Build the example go build ./examples/list_tools # Run it ./list_tools ``` -------------------------------- ### Running the Unix Socket Example (Bash) Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/unix-example.md Provides the necessary bash commands to execute the Unix Socket transport example. It outlines the steps to start the server in one terminal and the client in another. ```bash # First terminal: Run the server go run examples/unix/unix_example.go server # Second terminal: Run the client go run examples/unix/unix_example.go client ``` -------------------------------- ### Running the Example Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/udp-example.md Instructions on how to run the UDP transport example from the command line. ```bash # First terminal: Run the server go run examples/udp/udp_example.go server # Second terminal: Run the client go run examples/udp/udp_example.go client ``` -------------------------------- ### Go gRPC Server Setup and Tool Registration Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/grpc-example.md Demonstrates setting up an MCP gRPC server in Go. Shows how to configure the server with the gRPC transport and register a simple 'echo' tool. ```go // Create a new server srv := server.NewServer("grpc-example-server") // Configure the server with gRPC transport srv.AsGRPC(":50051") // Register a simple echo tool srv.Tool("echo", "Echo the message back", func(ctx *server.Context, args struct { Message string `json:"message"` }) (map[string]interface{}, error) { fmt.Printf("Server received: %s\n", args.Message) return map[string]interface{}{ "echoed": args.Message, }, nil }) // Start the server if err := srv.Run(); err != nil { log.Fatalf("Server error: %v", err) } ``` -------------------------------- ### Run Example Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/mqtt-example.md Commands to ensure the MQTT broker is running and then execute the Go example program. ```bash # Ensure an MQTT broker is running docker run -d -p 1883:1883 eclipse-mosquitto # Run the example directly go run examples/mqtt/mqtt_example.go ``` -------------------------------- ### Run MCP Sampling Server Source: https://github.com/localrivet/gomcp/blob/main/examples/sampling/README.md Starts the MCP sampling server. This command is used to initiate the server process, which then listens for incoming sampling requests from clients. ```Bash cd server go run main.go ``` -------------------------------- ### Manage MCP Server Process with Client Configuration in Go Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/stdio-example.md Illustrates robust server management for stdio transport using client configuration. This approach automatically starts the server process, handles environment variables, and ensures proper cleanup on client close, which is crucial for production applications. ```go config := client.ServerConfig{ MCPServers: map[string]client.ServerDefinition{ "stdio-server": { Command: "./stdio-server", Args: []string{"-config", "server.json"}, Env: map[string]string{"DEBUG": "true"}, }, }, } client, err := client.NewClient("stdio-client", client.WithServers(config, "stdio-server"), ) ``` -------------------------------- ### GoMCP Client Server Management Usage Source: https://github.com/localrivet/gomcp/blob/main/README.md Demonstrates how to define server configurations, create a GoMCP client, manage server lifecycles (start, stop, health monitoring), and interact with managed servers using the client API. Includes examples for programmatic configuration and loading from files. ```go // Define server configuration config := client.ServerConfig{ MCPServers: map[string]client.ServerDefinition{ "file-server": { Command: "python", Args: []string{"-m", "mcp_server_files"}, Env: map[string]string{ "FILES_ROOT": "/workspace", "LOG_LEVEL": "info", }, }, "database-server": { Command: "./db-mcp-server", Args: []string{"--config", "config.json"}, Env: map[string]string{ "DATABASE_URL": "${DATABASE_URL}", "API_KEY": "${DB_API_KEY}", }, WorkingDirectory: "/opt/db-server", }, "ai-tools": { Command: "ai-mcp-tools", Args: []string{"--model", "gpt-4"}, Env: map[string]string{ "OPENAI_API_KEY": "${OPENAI_API_KEY}", "ANTHROPIC_API_KEY": "${ANTHROPIC_API_KEY}", }, }, }, } // Create client with automatic server management client, err := client.NewClient("orchestrator", client.WithServers(config, "file-server"), // Start file-server ) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer client.Close() // Automatically stops managed servers // Start additional servers on demand err = client.StartServer("database-server") if err != nil { log.Fatalf("Failed to start database server: %v", err) } // Use multiple servers fileResult, err := client.CallTool("list_files", map[string]interface{}{ "path": "/workspace/src", }) // Switch to database server context or use a different client instance dbClient, err := client.NewClient("db-client", client.WithServers(config, "database-server"), ) defer dbClient.Close() queryResult, err := dbClient.CallTool("execute_query", map[string]interface{}{ "sql": "SELECT * FROM users LIMIT 10", }) // Load configuration from file configFromFile, err := client.LoadServerConfig("mcp-servers.json") if err != nil { log.Fatalf("Failed to load config: %v", err) } // Create client with all servers from config multiClient, err := client.NewClient("multi-server", client.WithServersFromConfig(configFromFile, "file-server", "ai-tools"), ) defer multiClient.Close() // Health monitoring status := client.GetServerStatus("file-server") if !status.Running { log.Printf("File server is not running: %v", status.Error) err := client.RestartServer("file-server") if err != nil { log.Fatalf("Failed to restart server: %v", err) } } ``` -------------------------------- ### Run Full ServerRegistry Demonstration Source: https://github.com/localrivet/gomcp/blob/main/examples/server_registry/README.md Executes a comprehensive 7-phase demonstration of the ServerRegistry, covering server startup, readiness checks, capability discovery, operation testing, management operations, error handling, and concurrent access. ```bash go run main.go demo ``` -------------------------------- ### Go MCP Server Setup with Unix Socket Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/unix-example.md Configures and runs an MCP server using the Unix Socket transport. It demonstrates setting socket permissions, buffer sizes, registering an echo tool, and starting the server process. ```go import ( "fmt" "log" "time" "github.com/localrivet/gomcp/client" "github.com/localrivet/gomcp/server" "github.com/localrivet/gomcp/unix" ) // ... inside main function or similar context ... // Create a new server srv := server.NewServer("unix-example-server") // Configure the server with Unix Socket transport // Options allow customizing socket permissions and buffer sizes srv.AsUnixSocket("/tmp/mcp-example.sock", unix.WithPermissions(0600), unix.WithBufferSize(4096), ) // Register a simple echo tool srv.Tool("echo", "Echo the message back", func(ctx *server.Context, args struct { Message string `json:"message"` }) (map[string]interface{}, error) { fmt.Printf("Server received: %s\n", args.Message) return map[string]interface{}{ "message": args.Message, }, nil }) // Start the server if err := srv.Run(); err != nil { log.Fatalf("Server error: %v", err) } ``` -------------------------------- ### Configure GOMCP Server with SSE Transport Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/sse-example.md Sets up a GOMCP server, configures it to use the SSE transport on a specified address, registers a simple echo tool, and starts the server. This code snippet illustrates the server-side setup for SSE communication. ```go srv := server.NewServer("sse-example-server") // Configure the server with SSE transportsrv.AsSSE("localhost:8083") // Register a simple echo toolsrv.Tool("echo", "Echo the message back", func(ctx *server.Context, args struct { Message string `json:"message"` }) (map[string]interface{}, error) { fmt.Printf("Server received: %s\n", args.Message) return map[string]interface{}{ "message": args.Message, }, nil }) // Start the server if err := srv.Run(); err != nil { log.Fatalf("Server error: %v", err) } ``` -------------------------------- ### Run GoMCP Events Integration Example Source: https://github.com/localrivet/gomcp/blob/main/docs/tutorials/events.md Command to navigate to the example directory and run the complete GoMCP events integration example, showcasing event subscription and processing. ```bash cd examples/events_integration go run main.go ``` -------------------------------- ### Create and Run Basic GOMCP Server Source: https://github.com/localrivet/gomcp/blob/main/docs/tutorials/server/01-creating-a-server.md Demonstrates the fundamental steps to create a new GOMCP server instance, configure it to use standard input/output for transport, and then run it. This is the starting point for most GOMCP server applications. ```go package main import ( "log" "github.com/localrivet/gomcp/server" ) func main() { // Create a server with a name s := server.NewServer("example-server") // Configure the transport (stdio in this case) s = s.AsStdio() // Start the server (this blocks until the server exits) if err := s.Run(); err != nil { log.Fatalf("Server error: %v", err) } } ``` -------------------------------- ### Discover Servers and List Tools using ServerRegistry Source: https://github.com/localrivet/gomcp/blob/main/examples/server_registry/README.md Illustrates the service discovery pattern using the ServerRegistry. It shows how to retrieve a list of available server names and obtain client instances to query their capabilities, such as listing available tools. ```go serverNames, _ := registry.GetServerNames() for _, name := range serverNames { client, _ := registry.GetClient(name) tools, _ := client.ListTools() // Build service catalog } ``` -------------------------------- ### Health Checking and Readiness Source: https://github.com/localrivet/gomcp/blob/main/examples/server_registry/README.md Demonstrates how to obtain a client for a registered server and use `WaitForReady()` to ensure the server is fully operational before attempting operations. It also shows how to list available tools on a ready server. ```go client, _ := registry.GetClient("math-server") // Wait for server to be fully ready if err := client.WaitForReady(10 * time.Second); err != nil { log.Printf("Server not ready: %v", err) } // Server is now ready for operations tools, _ := client.ListTools() ``` -------------------------------- ### Go Server Example with Tool Registration Source: https://github.com/localrivet/gomcp/blob/main/README.md This Go code demonstrates setting up a LocalRivet gomcp server. It includes initializing a logger, configuring the server, registering a tool named 'say_hello' with an inline struct for arguments, and running the server. The tool expects a 'Name' argument and returns a greeting message. ```go package main import ( "fmt" "log/slog" "os" "github.com/localrivet/gomcp/server" ) func main() { // Create a logger logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelInfo, })) // Create a new server srv := server.NewServer("example-server", server.WithLogger(logger), ).AsStdio() // Register a tool with inline struct srv.Tool("say_hello", "Greet someone", func(ctx *server.Context, args struct { Name string `json:"name"` }) (interface{}, error) { return map[string]interface{}{ "message": fmt.Sprintf("Hello, %s!", args.Name), }, nil }) // Start the server if err := srv.Run(); err != nil { log.Fatalf("Failed to run server: %v", err) } } ``` -------------------------------- ### GoMCP Server JSON-RPC: Get Hello Resource Source: https://github.com/localrivet/gomcp/blob/main/examples/README.md An example JSON-RPC message to read from the '/hello' resource exposed by the GoMCP server. This demonstrates accessing server-defined resources. ```json { "jsonrpc": "2.0", "id": 3, "method": "resources/read", "params": { "uri": "/hello" } } ``` -------------------------------- ### Load Server Configuration from JSON Source: https://github.com/localrivet/gomcp/blob/main/examples/server_registry/README.md Demonstrates how to initialize a ServerRegistry and load server definitions from a JSON configuration file. This method is essential for setting up the registry with predefined server configurations. ```go registry := client.NewServerRegistry() err := registry.LoadConfig("servers.json") ``` -------------------------------- ### GoMCP Server JSON-RPC: Render Greeting Prompt Source: https://github.com/localrivet/gomcp/blob/main/examples/README.md An example JSON-RPC message to get a response from the 'greeting' prompt. This shows how to use prompts with arguments to generate dynamic output. ```json { "jsonrpc": "2.0", "id": 4, "method": "prompts/get", "params": { "name": "greeting", "arguments": { "name": "Example User" } } } ``` -------------------------------- ### GoMCP Server Build Example Source: https://github.com/localrivet/gomcp/blob/main/proposals/GODXT_PROPOSAL.md Demonstrates building a Go MCP server using the standard Go toolchain, preparing it for packaging into a DXT file. ```go go build -o my-server cmd/server/main.go ``` -------------------------------- ### GoMCP Server Initialization Source: https://github.com/localrivet/gomcp/blob/main/server/README.md Shows how to create a new instance of the GoMCP server with a specified server name. ```go srv := server.NewServer("my-server") ``` -------------------------------- ### Configure MCP Server with Stdio Transport in Go Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/stdio-example.md Demonstrates setting up an MCP server using the standard I/O transport. It covers server initialization, configuring stdio with a log file, and registering a simple echo tool. This is essential for command-line tools and child process communication. ```go srv := server.NewServer("stdio-example-server") // Configure the server with stdio transport // Provide a log file path to avoid logging to stdout/stderrsrv.AsStdio("logs/mcp-server.log") // Register a simple echo toolsrv.Tool("echo", "Echo the message back", func(ctx *server.Context, args struct { Message string `json:"message"` }) (map[string]interface{}, error) { // Log to the server's logger (goes to the log file) ctx.Logger().Info("Echo tool called", "message", args.Message) return map[string]interface{}{ "message": args.Message, }, nil }) // Start the server - this will block until the server exits if err := srv.Run(); err != nil { log.Fatalf("Server error: %v", err) } ``` -------------------------------- ### Run gomcp Stdio Server Source: https://github.com/localrivet/gomcp/blob/main/examples/stdio/README.md Starts the gomcp server using the stdio transport. The server listens on stdin/stdout for MCP protocol messages. ```bash go run stdio_example.go ``` -------------------------------- ### Gomcp Advanced Server Setup and Functionality (Go) Source: https://github.com/localrivet/gomcp/blob/main/README.md This Go code demonstrates the setup of an advanced server using the gomcp library. It includes registering tools with structured arguments, defining resources with path parameters, and setting up prompt templates for various use cases. The server is configured with logging and runs via standard I/O. ```go package main import ( "fmt" "log/slog" "os" "path/filepath" "strings" "github.com/localrivet/gomcp/server" "github.com/localrivet/gomcp/transport/sse" ) func main() { // Create a logger logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelInfo, })) // Create a new server with comprehensive functionality srv := server.NewServer("advanced-server", server.WithLogger(logger), ).AsStdio() // Register multiple tools with different parameter types srv.Tool("calculator", "Perform mathematical calculations", func(ctx *server.Context, args struct { Operation string `json:"operation"` A float64 `json:"a"` B float64 `json:"b"` }) (interface{}, error) { switch args.Operation { case "add": return map[string]interface{}{"result": args.A + args.B}, nil case "multiply": return map[string]interface{}{"result": args.A * args.B}, nil case "divide": if args.B == 0 { return nil, fmt.Errorf("division by zero") } return map[string]interface{}{"result": args.A / args.B}, nil default: return nil, fmt.Errorf("unsupported operation: %s", args.Operation) } }) srv.Tool("create_file", "Create a file with content", func(ctx *server.Context, args struct { Path string `json:"path"` Content string `json:"content"` }) (interface{}, error) { // In a real implementation, you'd validate paths and permissions return map[string]interface{}{ "message": fmt.Sprintf("File created at %s with %d bytes", args.Path, len(args.Content)), "path": args.Path, "size": len(args.Content), }, nil }) // Register resources with different patterns srv.Resource("/config", "Get server configuration", func(ctx *server.Context, args *struct{}) (interface{}, error) { return map[string]interface{}{ "version": "1.0.0", "environment": "development", "features": []string{"tools", "resources", "prompts"}, }, nil }) // Templated resource for file access srv.Resource("/files/{path*}", "Access file system resources", func(ctx *server.Context, args *struct { Path string `path:"path"` }) (interface{}, error) { // Extract file extension for content type detection ext := strings.ToLower(filepath.Ext(args.Path)) return map[string]interface{}{ "path": args.Path, "extension": ext, "type": getFileType(ext), "content": fmt.Sprintf("Mock content for file: %s", args.Path), }, nil }) // User profile resource with parameters srv.Resource("/users/{id}", "Get user profile information", func(ctx *server.Context, args *struct { ID string `path:"id"` IncludePosts bool `json:"include_posts"` }) (interface{}, error) { user := map[string]interface{}{ "id": args.ID, "name": fmt.Sprintf("User %s", args.ID), "email": fmt.Sprintf("user%s@example.com", args.ID), "active": true, } if args.IncludePosts { user["posts"] = []map[string]interface{}{ {"id": 1, "title": "Hello World", "content": "First post"}, {"id": 2, "title": "Second Post", "content": "Another post"}, } } return user, nil }) // Register prompts for different use cases srv.Prompt("code_review", "Provide code review assistance", server.User("Please review this {{language}} code for best practices, potential bugs, and improvements:\n\n```{{language}}\n{{code}}\n```"), server.Assistant("I'll analyze your {{language}} code and provide detailed feedback on best practices, potential issues, and suggested improvements."), ) srv.Prompt("email_template", "Generate professional email content", server.Assistant("I'll help you create a professional email."), server.User("Write a {{tone}} email to {{recipient}} about {{subject}}. Include these key points: {{key_points}}"), ) srv.Prompt("documentation", "Generate technical documentation", server.User("Create documentation for this {{type}} with the following details:\n\nName: {{name}}\nPurpose: {{purpose}}\nParameters: {{parameters}}\nExample: {{example}}"), server.Assistant("I'll create comprehensive technical documentation following best practices for clarity and completeness."), ) // Start the server if err := srv.Run(); err != nil { logger.Error("Failed to run server", "error", err) os.Exit(1) } } // Helper function to determine file type from extension func getFileType(ext string) string { switch ext { case ".go": return "go_source" case ".js", ".ts": return "javascript" case ".py": return "python" case ".md": return "markdown" case ".json": return "json" case ".yaml", ".yml": return "yaml" default: return "text" } } ``` -------------------------------- ### MCP Sampling Start Request Source: https://github.com/localrivet/gomcp/blob/main/docs/spec-reference/README.md Example of a JSON-RPC 2.0 request for real-time content generation. It includes the method, content type, and the initial prompt. ```json { "jsonrpc": "2.0", "method": "sampling/start", "params": { "contentType": "text", "prompt": "Hello, how can I help you?" }, "id": 4 } ``` -------------------------------- ### Connect to Task Master Server Source: https://github.com/localrivet/gomcp/blob/main/docs/examples/server-config.md Demonstrates how to create a client and connect to a specific server like 'task-master-ai' using a configuration file. It also shows how to call tools provided by the server. ```go client, err := client.NewClient("", client.WithServerConfig("config.json", "task-master-ai"), ) if err != nil { log.Fatalf("Failed to create client: %v", err) } // Call Task Master tools result, err := client.CallTool("add_task", map[string]interface{}{ "prompt": "Implement user authentication using JWT", }) ``` ```json { "mcpServers": { "task-master-ai": { "command": "npx", "args": ["-y", "--package=task-master-ai", "task-master-ai"], "env": { "ANTHROPIC_API_KEY": "${ANTHROPIC_API_KEY}", "OPENAI_API_KEY": "${OPENAI_API_KEY}", "PROJECT_ROOT": "${PWD}" } } } } ``` -------------------------------- ### Client-Side Sampling Handler Setup Source: https://github.com/localrivet/gomcp/blob/main/examples/sampling/README.md Shows how to configure a client to respond to sampling requests by providing a handler function. This function processes incoming messages and returns a response. ```go // Set up sampling handler client := client.NewClient("my-app").WithSamplingHandler( func(params client.SamplingCreateMessageParams) (client.SamplingResponse, error) { // Call your AI model here result := callYourAIModel(params.Messages, params.SystemPrompt) return client.SamplingResponse{ Role: "assistant", Content: client.SamplingMessageContent{ Type: "text", Text: result, }, Model: "your-model-name", StopReason: "endTurn", }, nil }, ) ``` -------------------------------- ### Specify GOMCP Version in go.mod Source: https://github.com/localrivet/gomcp/blob/main/docs/installation/README.md Demonstrates how to specify a particular version of GOMCP in your `go.mod` file to manage dependencies and ensure reproducible builds. This follows semantic versioning principles. ```go require github.com/localrivet/gomcp v1.0.0 ``` -------------------------------- ### Error Handling for Invalid Server Configuration Source: https://github.com/localrivet/gomcp/blob/main/examples/server_registry/README.md Illustrates how the ServerRegistry gracefully handles errors when attempting to start a server with an invalid or non-existent command. The registry catches and reports these expected errors. ```go // Test invalid server configuration badDef := client.ServerDefinition{ Command: "/nonexistent/command", Args: []string{}, } // Registry handles errors gracefully if err := registry.StartServer("bad-server", badDef); err != nil { fmt.Printf("Expected error: %v\n", err) } ```