{"id":23686205,"url":"https://github.com/megagrindstone/go-mcp","last_synced_at":"2025-08-10T08:12:05.168Z","repository":{"id":269239132,"uuid":"906758443","full_name":"MegaGrindStone/go-mcp","owner":"MegaGrindStone","description":"A Go implementation of the Model Context Protocol (MCP) - an open protocol that enables seamless integration between LLM applications and external data sources and tools.","archived":false,"fork":false,"pushed_at":"2025-05-04T19:12:08.000Z","size":589,"stargazers_count":45,"open_issues_count":2,"forks_count":8,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-08-02T09:33:29.497Z","etag":null,"topics":["ai","go","go-library","golang-library","llm","mcp","modelcontextprotocol"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MegaGrindStone.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-12-21T20:21:15.000Z","updated_at":"2025-06-26T13:51:00.000Z","dependencies_parsed_at":"2025-01-21T16:26:52.619Z","dependency_job_id":"dde4d6a9-7c2b-4428-967f-a1b22a9cb4f0","html_url":"https://github.com/MegaGrindStone/go-mcp","commit_stats":null,"previous_names":["megagrindstone/go-mcp"],"tags_count":12,"template":false,"template_full_name":null,"purl":"pkg:github/MegaGrindStone/go-mcp","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MegaGrindStone%2Fgo-mcp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MegaGrindStone%2Fgo-mcp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MegaGrindStone%2Fgo-mcp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MegaGrindStone%2Fgo-mcp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MegaGrindStone","download_url":"https://codeload.github.com/MegaGrindStone/go-mcp/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MegaGrindStone%2Fgo-mcp/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":269693593,"owners_count":24460248,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-10T02:00:08.965Z","response_time":71,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","go","go-library","golang-library","llm","mcp","modelcontextprotocol"],"created_at":"2024-12-29T21:18:13.706Z","updated_at":"2025-08-10T08:12:05.159Z","avatar_url":"https://github.com/MegaGrindStone.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# go-mcp\n\n[![Go Reference](https://pkg.go.dev/badge/github.com/MegaGrindStone/go-mcp.svg)](https://pkg.go.dev/github.com/MegaGrindStone/go-mcp)\n![CI](https://github.com/MegaGrindStone/go-mcp/actions/workflows/ci.yml/badge.svg)\n[![Go Report Card](https://goreportcard.com/badge/github.com/MegaGrindStone/go-mcp)](https://goreportcard.com/report/github.com/MegaGrindStone/go-mcp)\n[![codecov](https://codecov.io/gh/MegaGrindStone/go-mcp/branch/main/graph/badge.svg)](https://codecov.io/gh/MegaGrindStone/go-mcp)\n\nA Go implementation of the Model Context Protocol (MCP) - an open protocol that enables seamless integration between LLM applications and external data sources and tools.\n\n\u003e ⚠️ **Warning**: The main branch contains unreleased changes and may be unstable. We recommend using the latest tagged release for stability. This library follows semantic versioning - breaking changes may be introduced with minor version bumps (0.x.0) until v1.0.0 is released. After v1.0.0, the API will be stable and breaking changes will only occur in major version updates. We recommend pinning your dependency to a specific version and reviewing the changelog before upgrading.\n\n## Overview\n\nThis repository provides a Go library implementing the Model Context Protocol (MCP) following the [official specification](https://spec.modelcontextprotocol.io/specification/).\n\n## Features\n\n### Core Protocol\n- Complete MCP protocol implementation with JSON-RPC 2.0 messaging\n- Pluggable transport system supporting SSE and Standard IO\n- Session-based client-server communication\n- Comprehensive error handling and progress tracking\n\n### Server Features\n- Modular server implementation with optional capabilities\n- Support for prompts, resources, and tools\n- Real-time notifications and updates\n- Built-in logging system\n- Resource subscription management\n\n### Client Features\n- Flexible client configuration with optional capabilities\n- Automatic session management and health monitoring\n- Support for streaming and pagination\n- Progress tracking and cancellation support\n- Configurable timeouts and retry logic\n\n### Transport Options\n- Server-Sent Events (SSE) for web-based real-time updates\n- Standard IO for command-line tool integration\n\n## Installation\n\n```bash\ngo get github.com/MegaGrindStone/go-mcp\n```\n\n## Usage\n\n### Server Implementation\n\nThere are two main steps to implementing an MCP server:\n\n#### 1. Create a Server Implementation\n\nCreate a server implementation that provides the capabilities you need:\n\n```go\n// Example implementing a server with tool support\ntype MyToolServer struct{}\n\nfunc (s *MyToolServer) ListTools(ctx context.Context, params mcp.ListToolsParams, \n    progress mcp.ProgressReporter, requestClient mcp.RequestClientFunc) (mcp.ListToolsResult, error) {\n    // Return available tools\n    return mcp.ListToolsResult{\n        Tools: []mcp.Tool{\n            {\n                Name: \"example-tool\",\n                Description: \"An example tool\",\n                // Additional tool properties...\n            },\n        },\n    }, nil\n}\n\nfunc (s *MyToolServer) CallTool(ctx context.Context, params mcp.CallToolParams, \n    progress mcp.ProgressReporter, requestClient mcp.RequestClientFunc) (mcp.CallToolResult, error) {\n    // Implement tool functionality\n    return mcp.CallToolResult{\n        Content: []mcp.Content{\n            {\n                Type: mcp.ContentTypeText,\n                Text: \"Tool result\",\n            },\n        },\n    }, nil\n}\n```\n\n#### 2. Initialize and Serve\n\nCreate and configure the server with your implementation and chosen transport:\n\n```go\n// Create server with your implementation\ntoolServer := \u0026MyToolServer{}\n\n// Choose a transport method\n// Option 1: Server-Sent Events (SSE)\nsseSrv := mcp.NewSSEServer(\"/message\")\nsrv := mcp.NewServer(mcp.Info{\n    Name:    \"my-mcp-server\",\n    Version: \"1.0\",\n}, sseSrv, \n    mcp.WithToolServer(toolServer),\n    mcp.WithServerPingInterval(30*time.Second),\n    // Add other capabilities as needed\n)\n\n// Set up HTTP handlers for SSE\nhttp.Handle(\"/sse\", sseSrv.HandleSSE())\nhttp.Handle(\"/message\", sseSrv.HandleMessage())\ngo http.ListenAndServe(\":8080\", nil)\n\n// Option 2: Standard IO\nsrvIO := mcp.NewStdIO(os.Stdin, os.Stdout)\nsrv := mcp.NewServer(mcp.Info{\n    Name:    \"my-mcp-server\", \n    Version: \"1.0\",\n}, srvIO,\n    mcp.WithToolServer(toolServer),\n    // Add other capabilities as needed\n)\n\n// Start the server - this blocks until shutdown\ngo srv.Serve()\n\n// To shutdown gracefully\nctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\ndefer cancel()\nsrv.Shutdown(ctx)\n```\n\n#### Available Server Options\n\nConfigure your server with additional capabilities:\n\n```go\n// Prompt capabilities\nmcp.WithPromptServer(promptServer)\nmcp.WithPromptListUpdater(promptListUpdater)\n\n// Resource capabilities\nmcp.WithResourceServer(resourceServer)\nmcp.WithResourceListUpdater(resourceListUpdater)\nmcp.WithResourceSubscriptionHandler(subscriptionHandler)\n\n// Tool capabilities\nmcp.WithToolServer(toolServer)\nmcp.WithToolListUpdater(toolListUpdater)\n\n// Roots and logging capabilities\nmcp.WithRootsListWatcher(rootsListWatcher)\nmcp.WithLogHandler(logHandler)\n\n// Server behavior configuration\nmcp.WithServerPingInterval(interval)\nmcp.WithServerPingTimeout(timeout)\nmcp.WithServerPingTimeoutThreshold(threshold)\nmcp.WithServerSendTimeout(timeout)\nmcp.WithInstructions(instructions)\n\n// Event callbacks\nmcp.WithServerOnClientConnected(func(id string, info mcp.Info) {\n    fmt.Printf(\"Client connected: %s\\n\", id)\n})\nmcp.WithServerOnClientDisconnected(func(id string) {\n    fmt.Printf(\"Client disconnected: %s\\n\", id)\n})\n```\n\n### Client Implementation\n\nThe client implementation involves creating a client with transport options and capabilities, connecting to a server, and executing MCP operations.\n\n#### Creating and Connecting a Client\n\n```go\n// Create client info\ninfo := mcp.Info{\n    Name:    \"my-mcp-client\",\n    Version: \"1.0\",\n}\n\n// Create a context for connection and operations\nctx, cancel := context.WithCancel(context.Background())\ndefer cancel()\n\n// Choose transport layer - SSE or Standard IO\n// Option 1: Server-Sent Events (SSE)\nsseClient := mcp.NewSSEClient(\"http://localhost:8080/sse\", http.DefaultClient)\ncli := mcp.NewClient(info, sseClient,\n    // Optional client configurations\n    mcp.WithClientPingInterval(30*time.Second),\n    mcp.WithProgressListener(progressListener),\n    mcp.WithLogReceiver(logReceiver),\n)\n\n// Option 2: Standard IO\nsrvReader, srvWriter := io.Pipe()\ncliReader, cliWriter := io.Pipe()\ncliIO := mcp.NewStdIO(cliReader, srvWriter)\nsrvIO := mcp.NewStdIO(srvReader, cliWriter)\ncli := mcp.NewClient(info, cliIO)\n\n// Connect client (requires context)\nif err := cli.Connect(ctx); err != nil {\n    log.Fatal(err)\n}\n// Ensure proper cleanup\ndefer func() {\n    disconnectCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n    defer cancel()\n    cli.Disconnect(disconnectCtx)\n}()\n```\n\n#### Making Requests\n\n```go\n// List available tools\ntools, err := cli.ListTools(ctx, mcp.ListToolsParams{})\nif err != nil {\n    log.Fatal(err)\n}\n\n// Call a tool (with proper argument structure)\nargs := map[string]string{\"message\": \"Hello MCP!\"}\nargsBs, _ := json.Marshal(args)\n\nresult, err := cli.CallTool(ctx, mcp.CallToolParams{\n    Name:      \"echo\",\n    Arguments: argsBs,\n})\nif err != nil {\n    log.Fatal(err)\n}\n\n// Work with resources\nresources, err := cli.ListResources(ctx, mcp.ListResourcesParams{})\nif err != nil {\n    log.Fatal(err)\n}\n\n// Subscribe to resource updates\nerr = cli.SubscribeResource(ctx, mcp.SubscribeResourceParams{\n    URI: \"resource-uri\",\n})\nif err != nil {\n    log.Fatal(err)\n}\n\n// Work with prompts\nprompts, err := cli.ListPrompts(ctx, mcp.ListPromptsParams{})\nif err != nil {\n    log.Fatal(err)\n}\n\nprompt, err := cli.GetPrompt(ctx, mcp.GetPromptParams{\n    Name: \"my-prompt\",\n})\nif err != nil {\n    log.Fatal(err)\n}\n```\n\n#### Implementing Handlers for Client Capabilities\n\n```go\n// Implement required interfaces for client capabilities\ntype myClient struct {\n    // ...client fields\n}\n\n// For sampling capability\nfunc (c *myClient) CreateSampleMessage(ctx context.Context, params mcp.SamplingParams) (mcp.SamplingResult, error) {\n    // Generate sample LLM output\n    return mcp.SamplingResult{\n        Role: mcp.RoleAssistant,\n        Content: mcp.SamplingContent{\n            Type: mcp.ContentTypeText,\n            Text: \"Sample response text\",\n        },\n        Model: \"my-llm-model\",\n    }, nil\n}\n\n// For resource subscription notifications\nfunc (c *myClient) OnResourceSubscribedChanged(uri string) {\n    fmt.Printf(\"Resource %s was updated\\n\", uri)\n}\n\n// For progress tracking\nfunc (c *myClient) OnProgress(params mcp.ProgressParams) {\n    fmt.Printf(\"Progress: %.2f/%.2f\\n\", params.Progress, params.Total)\n}\n\n// Pass these handlers when creating the client\ncli := mcp.NewClient(info, transport,\n    mcp.WithSamplingHandler(client),\n    mcp.WithResourceSubscribedWatcher(client),\n    mcp.WithProgressListener(client),\n)\n```\n\n### Complete Examples\n\nFor complete working examples:\n\n- See `example/everything/` for a comprehensive server and client implementation with all features\n- See `example/filesystem/` for a focused example of file operations using Standard IO transport\n\nThese examples demonstrate:\n- Server and client lifecycle management\n- Transport layer setup\n- Error handling\n- Tool implementation\n- Resource management\n- Progress tracking\n- Logging integration\n\nFor more details, check the [example directory](example/) in the repository.\n\n## Server Packages\n\nThe `servers` directory contains reference server implementations that mirror those found in the official [modelcontextprotocol/servers](https://github.com/modelcontextprotocol/servers) repository.\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmegagrindstone%2Fgo-mcp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmegagrindstone%2Fgo-mcp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmegagrindstone%2Fgo-mcp/lists"}