### Run Proxy Header Propagation Example Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/examples/server/proxy Execute the example to observe backend and proxy server startup, gateway header reception, and client result processing. ```bash go run main.go ``` -------------------------------- ### Start Fake Authorization Server Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/oauthtest Start begins the HTTP server for the FakeAuthorizationServer. It also registers a cleanup function with the provided testing.TB to ensure the server is closed. ```go func (s *FakeAuthorizationServer) Start(t testing.TB) ``` -------------------------------- ### Start Fake Identity Provider Server Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/oauthtest Start begins the HTTP server for the FakeIdPServer. A cleanup function is registered with the provided testing.TB to ensure the server is properly closed. ```go func (s *FakeIdPServer) Start(t testing.TB) ``` -------------------------------- ### StreamableHTTPHandler Example POST Request Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Example of a POST request sent to initialize a streamable MCP session. ```json POST {"jsonrpc": "2.0", "id": 1, "method":"initialize", "params": {}} ``` -------------------------------- ### Example Output: Logging Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Demonstrates the expected output from logging messages. ```text info shows up 1 warn shows up 3 ``` -------------------------------- ### Example Output: Progress Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Shows the expected output indicating progress updates. ```text frobbing widgets 0/2 frobbing widgets 1/2 frobbing widgets 2/2 ``` -------------------------------- ### StreamableHTTPHandler Example Initialization Output Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Example output for initializing a StreamableHTTPHandler, showing JSON-RPC protocol version and server info. ```json {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"logging":{}},"protocolVersion":"2025-11-25","serverInfo":{"name":"server","version":"v0.1.0"}}} ``` -------------------------------- ### Example Output: Prompts Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Illustrates the output related to prompt interactions. ```text greet user Say hi to Pat ``` -------------------------------- ### Example Output: Lifecycle Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Illustrates the output related to the lifecycle of a component. ```text initialized! ``` -------------------------------- ### Example Output: Roots Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Displays the expected output for listing roots. ```text [file://a file://b] ``` -------------------------------- ### Example Output: Resources Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Shows the expected output when interacting with resources, including a 'Resource not found' error. ```text file:///a file:///dir/{f} a x calling "resources/read": Resource not found ``` -------------------------------- ### Example Output: Elicitation Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Shows the expected output for an elicitation scenario. ```text value ``` -------------------------------- ### CommandTransport.Connect Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Connect starts the command and connects to it over stdin/stdout. ```APIDOC ## Connect ### Description Connect starts the command, and connects to it over stdin/stdout. ### Method func (t *CommandTransport) Connect(ctx context.Context) (Connection, error) ``` -------------------------------- ### Loadtest Command Usage Example Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/examples/client/loadtest Demonstrates how to use the loadtest command to test an MCP server. Specify the tool, arguments, and the server URL. ```bash loadtest -tool=greet -args='{"name": "foo"}' http://localhost:8080 ``` -------------------------------- ### LoggingTransport Example Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Demonstrates the read and write operations of a LoggingTransport, showing JSON-RPC messages. ```text Output: read: {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"logging":{}},"protocolVersion":"2025-11-25","serverInfo":{"name":"server","version":"v0.0.1"}}} write: {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"client","version":"v0.0.1"},"protocolVersion":"2025-11-25","capabilities":{"roots":{"listChanged":true}}}} write: {"jsonrpc":"2.0","method":"notifications/initialized","params":{}} ``` -------------------------------- ### Example Output: Context Canceled Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Demonstrates the expected output when a context cancellation occurs during a tool operation. ```text context canceled tool canceled ``` -------------------------------- ### Run Sequential Thinking Server (HTTP Mode) Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/examples/server/sequentialthinking Start the Model Context Protocol server with HTTP enabled on a specified port. Use this for network-based interactions. ```bash go run . -http :8080 ``` -------------------------------- ### Inferring Complex Schema for Tool Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Example demonstrating the inferred schema for a tool with complex input types. ```text Output: max days: 10 max confidence: 1 weather types: [sun partly_cloudy clouds rain snow] ``` -------------------------------- ### Example Output: Sampling Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Indicates the expected outcome of a sampling operation. ```text would have created a message ``` -------------------------------- ### MCPGODEBUG Environment Variable Example Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/mcpgodebug Illustrates the format for setting compatibility parameters using the MCPGODEBUG environment variable. This variable is a comma-separated list of key=value pairs. ```shell MCPGODEBUG=someoption=1,otheroption=value ``` -------------------------------- ### Server Run Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Starts the MCP server, listening for incoming connections on the specified transport. This is a blocking call. ```APIDOC ## Server Run ### Description Starts the MCP server, listening for incoming connections on the specified transport. This is a blocking call. ### Method Run ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ctx** (context.Context) - The context to control the server's lifecycle. - **t** (Transport) - The transport layer to listen on. ### Request Example ```go // Example usage: // err := server.Run(ctx, transport) ``` ### Response #### Success Response - **error** (error) - An error if the server fails to run or encounters an issue during operation. #### Response Example ```json // No response body on success. ``` ``` -------------------------------- ### Inferring Custom Marshalling Schema for Tool Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Example showing the inferred JSON schema for a tool with custom marshalling. ```text Output: my_tool { "additionalProperties": false, "properties": { "end": { "type": "string" }, "query": { "type": "string" }, "start": { "type": "string" } }, "type": "object" } ``` -------------------------------- ### Start MCP HTTP Server Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/examples/http Launches the MCP server. The default host is localhost and the default port is 8000. You can specify custom host and port values. ```bash go run . server ``` ```bash go run . -host 0.0.0.0 -port 9000 server ``` -------------------------------- ### Run listfeatures with Node.js Server Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/examples/client/listfeatures Use this command to list features when your MCP server is implemented using Node.js and the '@modelcontextprotocol/server-everything' package. Ensure Node.js and npm/npx are installed. ```bash listfeatures npx @modelcontextprotocol/server-everything ``` -------------------------------- ### Create an Alternative Reasoning Branch Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/examples/server/sequentialthinking Start a new, alternative path of reasoning within an existing thinking session. This allows for exploring different approaches to the same problem. ```json { "method": "tools/call", "params": { "name": "continue_thinking", "arguments": { "sessionId": "architecture_design", "thought": "Alternative approach: Start with a monolith-first strategy and extract services gradually.", "createBranch": true } } } ``` -------------------------------- ### Run a Simple MCP Server Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Sets up a basic MCP server with a 'greet' tool and runs it on the StdioTransport. Requires the 'mcp' and 'log' packages. ```go server := mcp.NewServer(&mcp.Implementation{Name: "greeter"}, nil) // Using the generic AddTool automatically populates the the input and output // schema of the tool. type args struct { Name string `json:"name" jsonschema:"the person to greet"` } mcp.AddTool(server, &mcp.Tool{ Name: "greet", Description: "say hi", }, func(ctx context.Context, req *mcp.CallToolRequest, args args) (*mcp.CallToolResult, any, error) { return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: "Hi " + args.Name}, }, }, nil, nil }) // Run the server on the stdio transport. if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil { log.Printf("Server failed: %v", err) } ``` -------------------------------- ### Running the Distributed MCP Server Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/examples/server/distributed This command starts the distributed MCP server, configuring it to listen on localhost:8080 and proxy requests to child processes on ports 8081 and 8082. Ensure the child ports are available. ```bash ./distributed -http=localhost:8080 -child_ports=8081,8082 ``` -------------------------------- ### Create and Run an MCP Server Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk This Go code demonstrates how to create a basic MCP server with a single tool and run it over stdin/stdout. It includes the necessary imports and defines input/output structures for a tool. ```go package main import ( "context" "log" "github.com/modelcontextprotocol/go-sdk/mcp" ) type Input struct { Name string `json:"name" jsonschema:"the name of the person to greet"` } type Output struct { Greeting string `json:"greeting" jsonschema:"the greeting to tell to the user"` } func SayHi(ctx context.Context, req *mcp.CallToolRequest, input Input) ( *mcp.CallToolResult, Output, error, ) { return nil, Output{Greeting: "Hi " + input.Name}, nil } func main() { // Create a server with a single tool. server := mcp.NewServer(&mcp.Implementation{Name: "greeter", Version: "v1.0.0"}, nil) mcp.AddTool(server, &mcp.Tool{Name: "greet", Description: "say hi"}, SayHi) // Run the server over stdin/stdout, until the client disconnects. if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Start a New Thinking Session Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/examples/server/sequentialthinking Initiate a new sequential thinking session for a given problem. Optionally provide a custom session ID and an initial estimate of steps. ```json { "method": "tools/call", "params": { "name": "start_thinking", "arguments": { "problem": "How should I design a scalable microservices architecture?", "sessionId": "architecture_design", "estimatedSteps": 8 } } } ``` -------------------------------- ### Get Protected Resource Metadata Function Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/oauthex Retrieves protected resource metadata from a server using a GET request. It validates the metadataURL, resource field, and authorization servers. ```go func GetProtectedResourceMetadata(ctx context.Context, metadataURL, resourceURL string, c *http.Client) (_ *ProtectedResourceMetadata, err error) ``` -------------------------------- ### ClientRequest.GetParams Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Gets the parameters of the client request. ```APIDOC ## ClientRequest.GetParams ### Description Gets the parameters of the client request. ### Method func (r *ClientRequest[P]) GetParams() Params ### Response #### Success Response (Params) - Returns the Params object. ``` -------------------------------- ### ClientRequest.GetExtra Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Gets the extra request information. ```APIDOC ## ClientRequest.GetExtra ### Description Gets the extra request information. ### Method func (r *ClientRequest[P]) GetExtra() *RequestExtra ### Response #### Success Response (*RequestExtra) - Returns a pointer to the RequestExtra object. ``` -------------------------------- ### ElicitParams.GetProgressToken Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Gets the progress token from the elicit parameters. ```APIDOC ## ElicitParams.GetProgressToken ### Description Gets the progress token from the elicit parameters. ### Method func (x *ElicitParams) GetProgressToken() any ### Response #### Success Response (any) - Returns the progress token. ``` -------------------------------- ### Client Registration Configuration Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/oauthtest Configure client ID metadata document support and pre-registered clients. ```go type RegistrationConfig struct { // Whether the client ID metadata document is supported. ClientIDMetadataDocumentSupported bool // PreregisteredClients is a map of valid ClientIDs to ClientSecrets. PreregisteredClients map[string]ClientInfo // Whether dynamic client registration is enabled. DynamicClientRegistrationEnabled bool } ``` -------------------------------- ### ClientRequest.GetSession Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Gets the session associated with the client request. ```APIDOC ## ClientRequest.GetSession ### Description Gets the session associated with the client request. ### Method func (r *ClientRequest[P]) GetSession() Session ### Response #### Success Response (Session) - Returns the Session object. ``` -------------------------------- ### CancelledParams.GetProgressToken Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Gets the progress token from the cancelled parameters. ```APIDOC ## CancelledParams.GetProgressToken ### Description Gets the progress token from the cancelled parameters. ### Method func (x *CancelledParams) GetProgressToken() any ### Response #### Success Response (any) - Returns the progress token. ``` -------------------------------- ### Run Sequential Thinking Server (Standard I/O) Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/examples/server/sequentialthinking Execute the Model Context Protocol server in standard input/output mode. This is the default mode for running the server. ```bash go run . ``` -------------------------------- ### CreateMessageParams.GetProgressToken Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Gets the progress token from the create message parameters. ```APIDOC ## CreateMessageParams.GetProgressToken ### Description Gets the progress token from the create message parameters. ### Method func (x *CreateMessageParams) GetProgressToken() any ### Response #### Success Response (any) - Returns the progress token. ``` -------------------------------- ### Connect Method Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Initiates an MCP session by connecting to a server over a given transport. The session is initialized and ready for use. The client is typically responsible for closing the connection. ```go func (c *Client) Connect(ctx context.Context, t Transport, opts *ClientSessionOptions) (cs *ClientSession, err error) ``` -------------------------------- ### ListTools Method for ClientSession Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Lists all tools currently available on the MCP server. ```go func (cs *ClientSession) ListTools(ctx context.Context, params *ListToolsParams) (*ListToolsResult, error) ``` -------------------------------- ### ListPrompts Method for ClientSession Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Lists all prompts currently available on the MCP server. ```go func (cs *ClientSession) ListPrompts(ctx context.Context, params *ListPromptsParams) (*ListPromptsResult, error) ``` -------------------------------- ### Dynamic Client Registration Configuration Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth Sets up dynamic client registration with metadata for the registration request, adhering to RFC7591. ```go type DynamicClientRegistrationConfig struct { // Metadata to be used in dynamic client registration request as per // https://datatracker.ietf.org/doc/html/rfc7591#section-2. // // If Metadata.ApplicationType is empty, it will be inferred from // Metadata.RedirectURIs. When set, it will be validated against the inferred type // and an error will be returned if they conflict. Metadata *oauthex.ClientRegistrationMetadata } ``` -------------------------------- ### Connect to MCP Server with CommandTransport Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Creates an MCP client and connects to a server using CommandTransport, executing a 'greet' tool call. Requires 'mcp', 'log', and 'os/exec' packages. ```go client := mcp.NewClient(&mcp.Implementation{Name: "mcp-client", Version: "v1.0.0"}, nil) transport := &mcp.CommandTransport{Command: exec.Command("myserver")} session, err := client.Connect(ctx, transport, nil) if err != nil { log.Fatal(err) } defer session.Close() params := &mcp.CallToolParams{ Name: "greet", Arguments: map[string]any{"name": "you"}, } res, err := session.CallTool(ctx, params) if err != nil { log.Fatalf("CallTool failed: %v", err) } ``` -------------------------------- ### Communicate with an MCP Server using a Client Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk This Go code shows how to create an MCP client, connect to a server running over stdin/stdout, and call a tool. It includes error handling for connection and tool calls. ```go package main import ( "context" "log" "os/exec" "github.com/modelcontextprotocol/go-sdk/mcp" ) func main() { ctx := context.Background() // Create a new client, with no features. client := mcp.NewClient(&mcp.Implementation{Name: "mcp-client", Version: "v1.0.0"}, nil) // Connect to a server over stdin/stdout. transport := &mcp.CommandTransport{Command: exec.Command("myserver")} session, err := client.Connect(ctx, transport, nil) if err != nil { log.Fatal(err) } defer session.Close() // Call a tool on the server. params := &mcp.CallToolParams{ Name: "greet", Arguments: map[string]any{"name": "you"}, } res, err := session.CallTool(ctx, params) if err != nil { log.Fatalf("CallTool failed: %v", err) } if res.IsError { log.Fatal("tool failed") } for _, c := range res.Content { log.Print(c.(*mcp.TextContent).Text) } } ``` -------------------------------- ### CreateMessageWithToolsParams.GetProgressToken Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Gets the progress token from the create message with tools parameters. ```APIDOC ## CreateMessageWithToolsParams.GetProgressToken ### Description Gets the progress token from the create message with tools parameters. ### Method func (x *CreateMessageWithToolsParams) GetProgressToken() any ### Response #### Success Response (any) - Returns the progress token. ``` -------------------------------- ### Initialize Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Initiates a connection with the server, allowing the client to send initialization parameters and receive server capabilities and instructions. ```APIDOC ## POST /initialize ### Description Initiates a connection with the server. The client sends initialization parameters, and the server responds with its capabilities, instructions, and protocol version. ### Method POST ### Endpoint /initialize ### Parameters #### Request Body - **params** (*InitializeParams) - Required - Parameters for initialization. ### Request Example ```json { "params": { "_meta": {}, "progressToken": null } } ``` ### Response #### Success Response (200) - **_meta** (`Meta`) - Optional - Reserved for protocol metadata. - **capabilities** (*ServerCapabilities) - Optional - Describes the server's capabilities. - **instructions** (`string`) - Optional - Instructions for using the server's features. - **protocolVersion** (`string`) - Required - The version of the Model Context Protocol the server wishes to use. - **serverInfo** (*Implementation) - Optional - Information about the server implementation. #### Response Example ```json { "_meta": {}, "capabilities": { ... }, "instructions": "Use the /listPrompts endpoint to see available prompts.", "protocolVersion": "v0.3.0", "serverInfo": { ... } } ``` ``` -------------------------------- ### NewConnection Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2 Creates a new JSON-RPC connection and starts processing incoming messages. ```APIDOC ## NewConnection ### Description NewConnection creates a new Connection object and starts processing incoming messages. ### Signature ``` func NewConnection(ctx context.Context, cfg ConnectionConfig) *Connection ``` ``` -------------------------------- ### CommandTransport.Connect Function Signature Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Signature for connecting a CommandTransport. Starts the command and connects to it over stdin/stdout. ```go func (t *CommandTransport) Connect(ctx context.Context) (Connection, error) ``` -------------------------------- ### Get Server Session ID Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Returns the session ID, or an empty string if there is none. ```go func (ss *ServerSession) ID() string ``` -------------------------------- ### Get Token Source Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth Retrieves a token source for accessing protected resources after a successful authorization. ```go func (h *AuthorizationCodeHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) ``` -------------------------------- ### NewClient Function Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Creates a new Client instance. Use Client.Connect to establish a connection to an MCP server. The implementation argument cannot be nil. ```go func NewClient(impl *Implementation, options *ClientOptions) *Client ``` -------------------------------- ### ListResources Method for ClientSession Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Lists all resources currently available on the MCP server. ```go func (cs *ClientSession) ListResources(ctx context.Context, params *ListResourcesParams) (*ListResourcesResult, error) ``` -------------------------------- ### Run listfeatures with Go SDK Server Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/examples/client/listfeatures Use this command to list features when your MCP server is implemented in Go. Ensure the server is built and executable. ```bash listfeatures go run github.com/modelcontextprotocol/go-sdk/examples/server/hello ``` -------------------------------- ### Client.Connect Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Establishes a connection to the server using the provided transport and options. ```APIDOC ## Client.Connect ### Description Establishes a connection to the server using the provided transport and options. ### Method func (c *Client) Connect(ctx context.Context, t Transport, opts *ClientSessionOptions) (cs *ClientSession, err error) ### Parameters - **ctx** (context.Context) - The context for the connection attempt. - **t** (Transport) - The transport layer to use for the connection. - **opts** (*ClientSessionOptions) - Options for configuring the client session. ### Response #### Success Response (*ClientSession) - Returns a pointer to the established ClientSession. #### Error Response (error) - Returns an error if the connection fails. ``` -------------------------------- ### NewClient Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Creates a new Client instance with the given implementation and options. ```APIDOC ## NewClient ### Description Creates a new Client instance with the given implementation and options. ### Method func NewClient(impl *Implementation, options *ClientOptions) *Client ### Parameters - **impl** (*Implementation) - The implementation to use for the client. - **options** (*ClientOptions) - Options for configuring the client. ### Response #### Success Response (*Client) - Returns a pointer to the newly created Client. ``` -------------------------------- ### Result Interface Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Interface representing the result of an MCP call, providing methods to get and set metadata. ```APIDOC ## Result Interface ### Description Represents the result of an MCP call. This interface provides methods for accessing and modifying metadata associated with the result. ### Methods - **GetMeta()** (`map[string]any`): Returns metadata from a value. - **SetMeta**(map[string]any): Sets the metadata on a value. ``` -------------------------------- ### Result Interface Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Defines the interface for a result of an MCP call, including methods to get and set metadata. ```go type Result interface { // GetMeta returns metadata from a value. GetMeta() map[string]any // SetMeta sets the metadata on a value. SetMeta(map[string]any) // contains filtered or unexported methods } ``` -------------------------------- ### Client ID Metadata Document Configuration Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth Configures client registration using a Client ID Metadata Document, following the specified URL format. ```go type ClientIDMetadataDocumentConfig struct { // URL is the client identifier URL as per // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00#section-3. URL string } ``` -------------------------------- ### NewServer Function Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Creates a new MCP server with optional configuration. Features must be added separately. ```go func NewServer(impl *Implementation, options *ServerOptions) *Server ``` -------------------------------- ### InitializeResult Method for ClientSession Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Initializes the result structure for the client session. ```go func (cs *ClientSession) InitializeResult() *InitializeResult ``` -------------------------------- ### Get Fake Identity Provider Server URL Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/oauthtest URL returns the base URL of the FakeIdPServer, which is its issuer URL. ```go func (s *FakeIdPServer) URL() string ``` -------------------------------- ### Get Fake Authorization Server URL Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/oauthtest URL returns the base URL of the FakeAuthorizationServer, which corresponds to its issuer URL. ```go func (s *FakeAuthorizationServer) URL() string ``` -------------------------------- ### RequestParams Interface Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Defines parameters for an MCP request, including methods to get and set a progress token from the Meta field. ```go type RequestParams interface { Params // GetProgressToken returns the progress token from the params' Meta field, or nil // if there is none. GetProgressToken() any // SetProgressToken sets the given progress token into the params' Meta field. // It panics if its argument is not an int or a string. SetProgressToken(any) } ``` -------------------------------- ### Params Interface Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Defines the Params interface for MCP call or notification parameters, including methods for getting and setting metadata. ```go type Params interface { // GetMeta returns metadata from a value. GetMeta() map[string]any // SetMeta sets the metadata on a value. SetMeta(map[string]any) // contains filtered or unexported methods } ``` -------------------------------- ### MemoryEventStore Open Method Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Implements EventStore.Open by ensuring data structures for the given session are initialized, added in v0.3.1. ```go func (s *MemoryEventStore) Open(_ context.Context, sessionID, streamID string) error ``` -------------------------------- ### NewStreamableHTTPHandler Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Creates a new StreamableHTTPHandler, which serves streamable HTTP requests. It requires a function to get the server and optional options. ```APIDOC ## NewStreamableHTTPHandler ### Description Creates a new StreamableHTTPHandler, which serves streamable HTTP requests. It requires a function to get the server and optional options. ### Method NewStreamableHTTPHandler ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **getServer** (func(*http.Request) *Server) - A function that returns the Server instance for a given request. - **opts** (*StreamableHTTPOptions) - Optional configuration for the handler. ### Request Example ```go // Example usage: // getServer := func(req *http.Request) *Server { /* ... */ } // handler := NewStreamableHTTPHandler(getServer, &StreamableHTTPOptions{}) ``` ### Response #### Success Response - **StreamableHTTPHandler** (*StreamableHTTPHandler) - A pointer to the newly created handler. #### Response Example ```json // No specific JSON example for StreamableHTTPHandler. ``` ``` -------------------------------- ### NewServer Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Creates a new MCP Server instance. It requires an implementation of the server logic and optional server options. ```APIDOC ## NewServer ### Description Creates a new MCP Server instance. It requires an implementation of the server logic and optional server options. ### Method NewServer ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage: // impl := &Implementation{...} // serverOptions := &ServerOptions{...} // server := NewServer(impl, serverOptions) ``` ### Response #### Success Response - **Server** (*Server) - A pointer to the newly created Server instance. #### Response Example ```json // No specific JSON example for Server. ``` ``` -------------------------------- ### Get Compatibility Parameter Value Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/mcpgodebug Retrieves the value of a compatibility parameter by its key. Returns an empty string if the key is not found. ```go func Value(key string) string ``` -------------------------------- ### NewClient Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Creates a new MCP client instance. Use Client.Connect to establish a connection to an MCP server. The implementation argument cannot be nil, and options can be provided to configure the client. ```APIDOC ## NewClient ### Description Creates a new MCP client instance. Use Client.Connect to establish a connection to an MCP server. The implementation argument cannot be nil, and options can be provided to configure the client. ### Signature ```go func NewClient(impl *Implementation, options *ClientOptions) *Client ``` ``` -------------------------------- ### Server Connect Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Establishes a new server session with a client. This method requires a context, a transport, and optional session options. ```APIDOC ## Server Connect ### Description Establishes a new server session with a client. This method requires a context, a transport, and optional session options. ### Method Connect ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ctx** (context.Context) - The context for the connection. - **t** (Transport) - The transport layer to use for the session. - **opts** (*ServerSessionOptions) - Optional settings for the server session. ### Request Example ```go // Example usage: // session, err := server.Connect(ctx, transport, &ServerSessionOptions{...}) ``` ### Response #### Success Response - **ServerSession** (*ServerSession) - A pointer to the newly established server session. - **error** (error) - An error if the session could not be established. #### Response Example ```json // No specific JSON example for ServerSession. ``` ``` -------------------------------- ### List Client Roots Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Lists the client roots. ```go func (ss *ServerSession) ListRoots(ctx context.Context, params *ListRootsParams) (*ListRootsResult, error) ``` -------------------------------- ### Connect Server to Transport Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Connects the MCP server over a given transport and starts message handling. Returns a connection object for managing the session. ```go func (s *Server) Connect(ctx context.Context, t Transport, opts *ServerSessionOptions) (*ServerSession, error) ``` -------------------------------- ### ListResourceTemplates Method for ClientSession Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Lists all resource templates available on the MCP server. ```go func (cs *ClientSession) ListResourceTemplates(ctx context.Context, params *ListResourceTemplatesParams) (*ListResourceTemplatesResult, error) ``` -------------------------------- ### Get JSON-RPC 2.0 Call ID Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2 ID returns the unique identifier for an asynchronous JSON-RPC 2.0 call. This ID can be used to cancel the call. ```go func (ac *AsyncCall) ID() ID ``` -------------------------------- ### AddPrompt Method Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Adds or replaces a Prompt handler on the server. ```go func (s *Server) AddPrompt(p *Prompt, h PromptHandler) ``` -------------------------------- ### Configure Streamable HTTP Options Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Use StreamableHTTPOptions to configure the StreamableHTTPHandler. Options include stateless operation, JSON response format, logger, event store for stream resumption, session timeout, and localhost protection. ```go type StreamableHTTPOptions struct { // Stateless controls whether the session is 'stateless'. // // A stateless server does not validate the Mcp-Session-Id header, and uses a // temporary session with default initialization parameters. Any // server->client request is rejected immediately as there's no way for the // client to respond. Server->Client notifications may reach the client if // they are made in the context of an incoming request, as described in the // documentation for [StreamableServerTransport]. Stateless bool // JSONResponse causes streamable responses to return application/json rather // than text/event-stream ([§2.1.5] of the spec). // // [§2.1.5]: https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#sending-messages-to-the-server JSONResponse bool // Logger specifies the logger to use. // If nil, do not log. Logger *slog.Logger // EventStore enables stream resumption. // // If set, EventStore will be used to persist stream events and replay them // upon stream resumption. EventStore EventStore // SessionTimeout configures a timeout for idle sessions. // // When sessions receive no new HTTP requests from the client for this // duration, they are automatically closed. // // If SessionTimeout is the zero value, idle sessions are never closed. SessionTimeout time.Duration // DisableLocalhostProtection disables automatic DNS rebinding protection. // By default, requests arriving via a localhost address (127.0.0.1, [::1]) // that have a non-localhost Host header are rejected with 403 Forbidden. // This protects against DNS rebinding attacks regardless of whether the // server is listening on localhost specifically or on 0.0.0.0. // // Only disable this if you understand the security implications. // See: https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise DisableLocalhostProtection bool // CrossOriginProtection allows to customize cross-origin protection. // The deny handler set in the CrossOriginProtection through SetDenyHandler // is ignored. // If nil, no cross-origin protection is applied. Use the `enableoriginverification` // MCPGODEBUG compatibility parameter to enable the default protection until v1.8.0. // // Deprecated: wrap the handler with cross-origin protection middleware // instead. For example: // // handler := mcp.NewStreamableHTTPHandler(...) // protection := http.NewCrossOriginProtection() // protectedHandler := protection.Handler(handler) CrossOriginProtection *http.CrossOriginProtection } ``` -------------------------------- ### AddResource Method Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Adds a Resource handler to the server, panicking if the URI is invalid or not absolute. ```go func (s *Server) AddResource(r *Resource, h ResourceHandler) ``` -------------------------------- ### AddReceivingMiddleware Method Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Adds middleware for processing incoming requests, applied from right to left. ```go func (s *Server) AddReceivingMiddleware(middleware ...Middleware) ``` -------------------------------- ### Get Server Sessions Iterator Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Returns an iterator for the current set of server sessions. Note that the iterator may not reflect sessions added or removed during iteration. ```go func (s *Server) Sessions() iter.Seq[*ServerSession] ``` -------------------------------- ### Connect Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Connects the MCP server over the given transport and starts handling messages. It returns a connection object that may be used to terminate the connection or await client termination. ```APIDOC ## Connect ### Description Connects the MCP server over the given transport and starts handling messages. It returns a connection object that may be used to terminate the connection (with [Connection.Close]), or await client termination (with [Connection.Wait]). If opts.State is non-nil, it is the initial state for the server. ### Method func (s *Server) Connect(ctx context.Context, t Transport, opts *ServerSessionOptions) (*ServerSession, error) ### Parameters - **ctx** (context.Context) - The context for the connection. - **t** (Transport) - The transport to use for the connection. - **opts** (*ServerSessionOptions) - Options for the server session. ``` -------------------------------- ### ClientSession.ListPrompts Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Lists available prompts with the provided parameters and returns the results or an error. ```APIDOC ## ClientSession.ListPrompts ### Description Lists available prompts with the provided parameters and returns the results or an error. ### Method func (cs *ClientSession) ListPrompts(ctx context.Context, params *ListPromptsParams) (*ListPromptsResult, error) ### Parameters - **ctx** (context.Context) - The context for the listing operation. - **params** (*ListPromptsParams) - The parameters for listing prompts. ### Response #### Success Response (*ListPromptsResult) - Returns a ListPromptsResult object containing the list of prompts. #### Error Response (error) - Returns an error if the prompts cannot be listed. ``` -------------------------------- ### ClientSession.Tools Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Provides an iterator for all tools available on the server, automatically fetching pages and managing cursors. The params argument can set the initial cursor. Iteration stops at the first encountered error, which will be yielded. ```APIDOC ## Tools ### Description Provides an iterator for all tools available on the server, automatically fetching pages and managing cursors. The params argument can set the initial cursor. Iteration stops at the first encountered error, which will be yielded. ### Method func (cs *ClientSession) Tools(ctx context.Context, params *ListToolsParams) iter.Seq2[*Tool, error] ``` -------------------------------- ### Default Page Size Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Sets the default page size for server options. ```go const DefaultPageSize = 1000 ``` -------------------------------- ### Connection.Close Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2 Stops accepting new requests, waits for in-flight requests to complete, and closes the underlying stream. After Close starts, calls with IDs will receive immediate ErrServerClosing responses, and no new requests will be enqueued. ```APIDOC ## Connection.Close ### Description Close stops accepting new requests, waits for in-flight requests and enqueued Handle calls to complete, and then closes the underlying stream. After the start of a Close, notification requests (that lack IDs and do not receive responses) will continue to be passed to the Preempter, but calls with IDs will receive immediate responses with ErrServerClosing, and no new requests (not even notifications!) will be enqueued to the Handler. ### Signature ``` func (c *Connection) Close() error ``` ``` -------------------------------- ### ClientSession.InitializeResult Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Returns the initialization result for the client session. ```APIDOC ## ClientSession.InitializeResult ### Description Returns the initialization result for the client session. ### Method func (cs *ClientSession) InitializeResult() *InitializeResult ### Response #### Success Response (*InitializeResult) - Returns an InitializeResult object. ``` -------------------------------- ### AddRoots Method Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Adds given roots to the client, replacing any with the same URIs, and notifies connected servers. ```go func (c *Client) AddRoots(roots ...*Root) ``` -------------------------------- ### AuthorizationCodeHandler.TokenSource Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth Provides a TokenSource for obtaining access tokens using the authorization code flow. This method is called to retrieve a source that can be used to get valid access tokens after the authorization code has been successfully exchanged. ```APIDOC ## AuthorizationCodeHandler.TokenSource ### Description Provides a TokenSource for obtaining access tokens using the authorization code flow. This method is called to retrieve a source that can be used to get valid access tokens after the authorization code has been successfully exchanged. ### Method `func (h *AuthorizationCodeHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error)` ``` -------------------------------- ### Complete Method for ClientSession Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Completes a task or process within the client session. ```go func (cs *ClientSession) Complete(ctx context.Context, params *CompleteParams) (*CompleteResult, error) ``` -------------------------------- ### Close JSON-RPC 2.0 Connection Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2 Close stops accepting new requests, completes in-flight operations, and closes the underlying stream. After Close starts, calls with IDs receive ErrServerClosing, and new requests are not enqueued. ```go func (c *Connection) Close() error ``` -------------------------------- ### Get Authorization Server Metadata Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/oauthex Retrieves authorization server metadata from a given URL. Ensures the metadataURL uses HTTPS or is a local address and validates the Issuer field. It also checks for PKCE support and secure URL schemes. ```go func GetAuthServerMeta(ctx context.Context, metadataURL, issuer string, c *http.Client) (*AuthServerMeta, error) ``` -------------------------------- ### ListPrompts Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Requests a list of available prompts from the server, supporting pagination via a cursor. ```APIDOC ## POST /prompts/list ### Description Requests a list of available prompts from the server. Supports pagination using an opaque cursor. ### Method POST ### Endpoint /prompts/list ### Parameters #### Request Body - **params** (*ListPromptsParams) - Required - Parameters for listing prompts, including an optional cursor for pagination. - **_meta** (`Meta`) - Optional - Reserved for protocol metadata. - **cursor** (`string`) - Optional - An opaque token representing the current pagination position. Results will start after this cursor. ### Request Example ```json { "params": { "_meta": {}, "cursor": "some-opaque-cursor-string" } } ``` ### Response #### Success Response (200) - **_meta** (`Meta`) - Optional - Reserved for protocol metadata. - **nextCursor** (`string`) - Optional - An opaque token for the next page of results. Present if more results are available. - **prompts** (`[]*Prompt`) - Required - A list of available prompts. #### Response Example ```json { "_meta": {}, "nextCursor": "another-opaque-cursor-string", "prompts": [ { "id": "prompt-1", "name": "Example Prompt" }, { "id": "prompt-2", "name": "Another Prompt" } ] } ``` ``` -------------------------------- ### CreateMessageWithTools Request Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Sends a sampling request with tools to the client, supporting array content for parallel tool calls. Use this instead of CreateMessage when the request includes tools. ```go func (ss *ServerSession) CreateMessageWithTools(ctx context.Context, params *CreateMessageWithToolsParams) (*CreateMessageWithToolsResult, error) ``` -------------------------------- ### ServerOptions Struct Definition Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Defines the configuration options for a server, including handlers for various notifications, pagination settings, keep-alive intervals, and capability configurations. Use this to customize server behavior and advertised features. ```go type ServerOptions struct { // Optional instructions for connected clients. Instructions string // Logger may be set to a non-nil value to enable logging of server activity. Logger *slog.Logger // If non-nil, called when "notifications/initialized" is received. InitializedHandler func(context.Context, *InitializedRequest) // PageSize is the maximum number of items to return in a single page for // list methods (e.g. ListTools). // // If zero, defaults to [DefaultPageSize]. PageSize int // If non-nil, called when "notifications/roots/list_changed" is received. RootsListChangedHandler func(context.Context, *RootsListChangedRequest) // If non-nil, called when "notifications/progress" is received. ProgressNotificationHandler func(context.Context, *ProgressNotificationServerRequest) // If non-nil, called when "completion/complete" is received. CompletionHandler func(context.Context, *CompleteRequest) (*CompleteResult, error) // If non-zero, defines an interval for regular "ping" requests. // If the peer fails to respond to pings originating from the keepalive check, // the session is automatically closed. KeepAlive time.Duration // Function called when a client session subscribes to a resource. SubscribeHandler func(context.Context, *SubscribeRequest) error // Function called when a client session unsubscribes from a resource. UnsubscribeHandler func(context.Context, *UnsubscribeRequest) error // Capabilities optionally configures the server's default capabilities, // before any capabilities are inferred from other configuration or server // features. // // If Capabilities is nil, the default server capabilities are {"logging":{}}, // for historical reasons. Setting Capabilities to a non-nil value overrides // this default. For example, setting Capabilities to `&ServerCapabilities{}` // disables the logging capability. // // # Interaction with capability inference // // "tools", "prompts", and "resources" capabilities are automatically added when // tools, prompts, or resources are added to the server (for example, via // [Server.AddPrompt]), with default value `{"listChanged":true}`. Similarly, // if the [ClientOptions.SubscribeHandler] or // [ClientOptions.CompletionHandler] are set, the inferred capabilities are // adjusted accordingly. // // Any non-nil field in Capabilities overrides the inferred value. // For example: // // - To advertise the "tools" capability, even if no tools are added, set // Capabilities.Tools to &ToolCapabilities{ListChanged:true}. // - To disable tool list notifications, set Capabilities.Tools to // &ToolCapabilities{}. // // Conversely, if Capabilities does not set a field (for example, if the // Prompts field is nil), the inferred capability will be used. Capabilities *ServerCapabilities // If true, advertises the prompts capability during initialization, // even if no prompts have been registered. // // Deprecated: Use Capabilities instead. HasPrompts bool // If true, advertises the resources capability during initialization, // even if no resources have been registered. // // Deprecated: Use Capabilities instead. HasResources bool // If true, advertises the tools capability during initialization, // even if no tools have been registered. // // Deprecated: Use Capabilities instead. HasTools bool // SchemaCache, if non-nil, caches JSON schemas to avoid repeated // reflection. This is useful for stateless server deployments where // a new [Server] is created for each request. See [SchemaCache] for // trade-offs and usage guidance. SchemaCache *SchemaCache // GetSessionID provides the next session ID to use for an incoming request. // If nil, a default randomly generated ID will be used. // // Session IDs should be globally unique across the scope of the server, // which may span multiple processes in the case of distributed servers. // // As a special case, if GetSessionID returns the empty string, // the Mcp-Session-Id header will not be set. GetSessionID func() string } ``` -------------------------------- ### Define MemoryEventStoreOptions Structure Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Options for configuring a MemoryEventStore, added in v0.3.0. ```go type MemoryEventStoreOptions struct{} ``` -------------------------------- ### Client.Connect Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Establishes an MCP session by connecting to a server using the provided transport. The returned client session is ready for use. The client is responsible for closing the connection; otherwise, errors will be returned if the server closes it. ```APIDOC ## Client.Connect ### Description Establishes an MCP session by connecting to a server using the provided transport. The returned client session is ready for use. The client is responsible for closing the connection; otherwise, errors will be returned if the server closes it. ### Signature ```go func (c *Client) Connect(ctx context.Context, t Transport, opts *ClientSessionOptions) (cs *ClientSession, err error) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Response #### Success Response (200) - **cs** (*ClientSession) - The established client session. - **err** (error) - An error if the connection fails. ### Error Handling - `ErrConnectionClosed` is returned if the connection is closed by the server. ``` -------------------------------- ### AddReceivingMiddleware Method Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Wraps the current receiving method handler with provided middleware. Middleware is applied from right to left. Useful for authentication, request logging, and metrics. ```go func (c *Client) AddReceivingMiddleware(middleware ...Middleware) ``` -------------------------------- ### SamplingToolsCapabilities Structure Source: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp Indicates that the client supports tool use in sampling. ```go type SamplingToolsCapabilities struct{} ```