mcp-golang

repository·main·Indexed 22 days ago

https://github.com/metoro-io/mcp-golang

An unofficial implementation of the Model Context Protocol (MCP) in Go. It enables developers to build type-safe MCP servers and clients with minimal boilerplate, utilizing native Go structs for tool arguments and automatic schema generation. The library supports stdio and HTTP transports, including a specialized GinTransport for integration with the Gin web framework, and provides features for tool and prompt discovery, cursor-based pagination, and Claude Desktop configuration.

Tokens
19.9K
Snippets
56
Records
110
Agent score
79%

What's inside mcp-golang

  1. Demonstrated MCP Client Features

    main

    The client example showcases the following core Model Context Protocol (MCP) capabilities:

    Tools

    • Listing Tools: Discovering available tools provided by the server.
    • Calling Tools: Executing server-side functions. The example demonstrates:
      • hello: Basic greeting.
      • calculate: Arithmetic operations.
      • time: Current time formatting.

    Prompts

    • Listing Prompts: Discovering available prompt templates.
    • Using Prompts: Executing server-side prompt logic. The example demonstrates:
      • uppercase: Text conversion to uppercase.
      • reverse: Text reversal.
  2. Create nested navigation groups

    main

    To create nested navigation, include an object containing a group and a pages array inside the pages array of a parent group. You do not need to include the .mdx extension in page names.

    "navigation": [
        {
            "group": "Getting Started",
            "pages": [
                "quickstart",
                {
                    "group": "Nested Reference Pages",
                    "pages": ["nested-reference-page"]
                }
            ]
        }
    ]
  3. How pagination works in MCP-Golang

    main

    MCP-Golang implements cursor-based pagination for list operations involving tools, prompts, and resources. This allows servers to return data in manageable chunks.

    When pagination is enabled, the server follows this lifecycle:

    1. It limits the number of items returned in a single response to a specified limit.
    2. If more items exist beyond the current page, the server includes a nextCursor in the response.
    3. The client can then pass this cursor value as a parameter in subsequent requests to retrieve the next page of results.

    Note: The cursor is an opaque string; clients should treat it as a black box and not attempt to parse or manipulate it.

  4. Generate tool schemas automatically

    main

    You do not need to manually maintain JSON schemas for your tools. mcp-golang uses reflection to inspect your handler's argument struct and automatically generates the appropriate MCP inputSchema.

    To control the schema, use jsonschema tags on your argument struct fields:

    • Required fields: Use jsonschema:"required".
    • Optional fields: Omit the required tag (fields are optional by default).
    • Descriptions: Use jsonschema:"description=..." to provide metadata that helps the LLM understand the argument.
  5. Understand the mcp-golang project structure

    main

    The repository is organized into the following key packages:

    • server/: Core server implementation
    • transport/: Transport layer implementations (e.g., stdio, SSE)
    • protocol/: MCP protocol implementation
    • examples/: Example implementations
    • internal/: Internal utilities and helpers
  6. How change notifications work in mcp-golang

    main

    In mcp-golang, the server automatically sends notifications to the client whenever the server's capabilities or available assets change. This allows clients (like LLM interfaces) to refresh their context or toolsets dynamically without needing a restart.

    Notifications are triggered by the following registration and deregistration events:

    • Tools: Using RegisterTool or DeregisterTool.
    • Prompts: Using RegisterPrompt or DeregisterPrompt.
    • Resources: Using RegisterResource or DeregisterResource.
  7. How GinTransport works with Gin

    main
    The GinTransport is a specialized transport implementation designed to work with the Gin web framework. It provides a Handler() method which returns a standard Gin handler function. This allows the MCP server to receive and process MCP requests through the Gin router's middleware and routing logic, enabling MCP capabilities to coexist with other RESTful endpoints in the same application.
  8. Key features of mcp-golang

    main

    mcp-golang provides several core capabilities for developers building MCP integrations:

    • Batteries Included: Rapidly set up servers with support for tools, resources, and prompts.
    • Type Safety: Leverages Go's type system with automatic JSON schema generation derived from Go structs.
    • Composable Architecture: Allows developers to use only the necessary components: transport, protocol, or server.
    • Flexible Transports: Includes built-in support for stdio and sse (Server-Sent Events) transports, while allowing developers to implement custom transports using the rest of the library.
  9. Use HTTP transport for MCP servers and clients

    main

    The SDK supports HTTP transport, allowing MCP tools to communicate over HTTP/HTTPS endpoints.

    Warning: HTTP transport implementations are stateless. They do not support bidirectional communication features like notifications. If you require persistent connections or notifications, use stdio transport instead.

  10. How the mcp-golang architecture works

    main

    The mcp-golang library is organized into three functional layers that mirror the Model Context Protocol (MCP) specification. Understanding these layers helps in determining where to implement custom logic versus where to configure communication:

    1. Transport Layer: Manages the raw communication medium (e.g., TCP, HTTP, WebSockets). It is responsible for the bidirectional conversion between underlying transport messages and JSON-RPC messages.
    2. Protocol Layer: Defines the MCP protocol logic. It consumes JSON-RPC messages and transforms them into structured requests, notifications, and responses. This layer handles JSON-RPC method routing, error handling, and maintains a list of handlers.
    3. Server Layer: The high-level API used by developers. It integrates the transport and protocol layers to provide a functional server. This layer allows you to register handlers for core MCP features like tools, resources, prompts, and completions.

    User Code: Your implementation resides in the handlers passed to the Server Layer. These handlers contain the actual business logic for the tools or resources you expose.

  11. Handle pagination in List methods

    main

    Methods like ListTools and ListPrompts support pagination. To iterate through all results, use a loop that checks NextCursor and passes it back into the next call.

    var cursor *string
    for {
        tools, err := client.ListTools(context.Background(), cursor)
        if err != nil {
            log.Fatalf("Failed to list tools: %v", err)
        }
    
        // Process tools...
    
        if tools.NextCursor == nil {
            break // No more pages
        }
        cursor = tools.NextCursor
    }