docs: add feature and troubleshooting documentation (#463)
Add a framework for feature documentation, and start populating it with our SDK documentation. This framework is as follows: - internal/docs/**.src.md is the markdown source for the docs/ directory. - The x/example/internal/cmd/weave tool is used to compile these docs to the top-level docs, supporting both linked code samples and generated tables of contents. - The readme-check workflow is updated to check these docs as well. - The structure of these docs follows the MCP spec. - Wherever possible, example code is linked from actual Go documentation examples, so that it is testable. Some minor modifications to the weave tool were made to support this framework. Additionally, partially fill out this documentation with content on base protocol and client features, as well as troubleshooting help. Along the way, a bug was encountered that our LoggingTransport was not concurrency safe. This is fixed with a mutex. Fixes https://github.com/modelcontextprotocol/go-sdk/issues/466 Fixes https://github.com/modelcontextprotocol/go-sdk/issues/409 Updates https://github.com/modelcontextprotocol/go-sdk/issues/442
This commit is contained in:
parent
ab4d6218c6
commit
ac2f175214
9 changed files with 1566 additions and 30 deletions
|
|
@ -55,11 +55,15 @@ func NewClient(impl *Implementation, opts *ClientOptions) *Client {
|
|||
|
||||
// ClientOptions configures the behavior of the client.
|
||||
type ClientOptions struct {
|
||||
// Handler for sampling.
|
||||
// Called when a server calls CreateMessage.
|
||||
// CreateMessageHandler handles incoming requests for sampling/createMessage.
|
||||
//
|
||||
// Setting CreateMessageHandler to a non-nil value causes the client to
|
||||
// advertise the sampling capability.
|
||||
CreateMessageHandler func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error)
|
||||
// Handler for elicitation.
|
||||
// Called when a server requests user input via Elicit.
|
||||
// ElicitationHandler handles incoming requests for elicitation/create.
|
||||
//
|
||||
// Setting ElicitationHandler to a non-nil value causes the client to
|
||||
// advertise the elicitation capability.
|
||||
ElicitationHandler func(context.Context, *ElicitRequest) (*ElicitResult, error)
|
||||
// Handlers for notifications from the server.
|
||||
ToolListChangedHandler func(context.Context, *ToolListChangedRequest)
|
||||
|
|
@ -123,7 +127,7 @@ func (c *Client) capabilities() *ClientCapabilities {
|
|||
}
|
||||
|
||||
// Connect begins an MCP session by connecting to a server over the given
|
||||
// transport, and initializing the session.
|
||||
// transport. The resulting session is initialized, and ready to use.
|
||||
//
|
||||
// Typically, it is the responsibility of the client to close the connection
|
||||
// when it is no longer needed. However, if the connection is closed by the
|
||||
|
|
@ -302,6 +306,9 @@ func (c *Client) elicit(ctx context.Context, req *ElicitRequest) (*ElicitResult,
|
|||
|
||||
// Validate elicitation result content against requested schema
|
||||
if req.Params.RequestedSchema != nil && res.Content != nil {
|
||||
// TODO: is this the correct behavior if validation fails?
|
||||
// It isn't the *server's* params that are invalid, so why would we return
|
||||
// this code to the server?
|
||||
resolved, err := req.Params.RequestedSchema.Resolve(nil)
|
||||
if err != nil {
|
||||
return nil, jsonrpc2.NewError(CodeInvalidParams, fmt.Sprintf("failed to resolve requested schema: %v", err))
|
||||
|
|
|
|||
136
mcp/client_example_test.go
Normal file
136
mcp/client_example_test.go
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mcp_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
// !+roots
|
||||
|
||||
func Example_roots() {
|
||||
ctx := context.Background()
|
||||
|
||||
// Create a client with a single root.
|
||||
c := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
|
||||
c.AddRoots(&mcp.Root{URI: "file://a"})
|
||||
|
||||
// Now create a server with a handler to receive notifications about roots.
|
||||
rootsChanged := make(chan struct{})
|
||||
handleRootsChanged := func(ctx context.Context, req *mcp.RootsListChangedRequest) {
|
||||
rootList, err := req.Session.ListRoots(ctx, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var roots []string
|
||||
for _, root := range rootList.Roots {
|
||||
roots = append(roots, root.URI)
|
||||
}
|
||||
fmt.Println(roots)
|
||||
close(rootsChanged)
|
||||
}
|
||||
s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, &mcp.ServerOptions{
|
||||
RootsListChangedHandler: handleRootsChanged,
|
||||
})
|
||||
|
||||
// Connect the server and client...
|
||||
t1, t2 := mcp.NewInMemoryTransports()
|
||||
if _, err := s.Connect(ctx, t1, nil); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if _, err := c.Connect(ctx, t2, nil); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// ...and add a root. The server is notified about the change.
|
||||
c.AddRoots(&mcp.Root{URI: "file://b"})
|
||||
<-rootsChanged
|
||||
// Output: [file://a file://b]
|
||||
}
|
||||
|
||||
// !-roots
|
||||
|
||||
// !+sampling
|
||||
|
||||
func Example_sampling() {
|
||||
ctx := context.Background()
|
||||
|
||||
// Create a client with a sampling handler.
|
||||
c := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, &mcp.ClientOptions{
|
||||
CreateMessageHandler: func(_ context.Context, req *mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error) {
|
||||
return &mcp.CreateMessageResult{
|
||||
Content: &mcp.TextContent{
|
||||
Text: "would have created a message",
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
})
|
||||
|
||||
// Connect the server and client...
|
||||
ct, st := mcp.NewInMemoryTransports()
|
||||
s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
|
||||
session, err := s.Connect(ctx, st, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer session.Close()
|
||||
|
||||
if _, err := c.Connect(ctx, ct, nil); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
msg, err := session.CreateMessage(ctx, &mcp.CreateMessageParams{})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(msg.Content.(*mcp.TextContent).Text)
|
||||
// Output: would have created a message
|
||||
}
|
||||
|
||||
// !-sampling
|
||||
|
||||
// !+elicitation
|
||||
|
||||
func Example_elicitation() {
|
||||
ctx := context.Background()
|
||||
ct, st := mcp.NewInMemoryTransports()
|
||||
|
||||
s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
|
||||
ss, err := s.Connect(ctx, st, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer ss.Close()
|
||||
|
||||
c := mcp.NewClient(testImpl, &mcp.ClientOptions{
|
||||
ElicitationHandler: func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error) {
|
||||
return &mcp.ElicitResult{Action: "accept", Content: map[string]any{"test": "value"}}, nil
|
||||
},
|
||||
})
|
||||
if _, err := c.Connect(ctx, ct, nil); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
res, err := ss.Elicit(ctx, &mcp.ElicitParams{
|
||||
Message: "This should fail",
|
||||
RequestedSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"test": {Type: "string"},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(res.Content["test"])
|
||||
// Output: value
|
||||
}
|
||||
|
||||
// !-elicitation
|
||||
166
mcp/mcp_example_test.go
Normal file
166
mcp/mcp_example_test.go
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mcp_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
// !+lifecycle
|
||||
|
||||
func Example_lifecycle() {
|
||||
ctx := context.Background()
|
||||
|
||||
// Create a client and server.
|
||||
// Wait for the client to initialize the session.
|
||||
client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, &mcp.ServerOptions{
|
||||
InitializedHandler: func(context.Context, *mcp.InitializedRequest) {
|
||||
fmt.Println("initialized!")
|
||||
},
|
||||
})
|
||||
|
||||
// Connect the server and client using in-memory transports.
|
||||
//
|
||||
// Connect the server first so that it's ready to receive initialization
|
||||
// messages from the client.
|
||||
t1, t2 := mcp.NewInMemoryTransports()
|
||||
serverSession, err := server.Connect(ctx, t1, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
clientSession, err := client.Connect(ctx, t2, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Now shut down the session by closing the client, and waiting for the
|
||||
// server session to end.
|
||||
if err := clientSession.Close(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := serverSession.Wait(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
// Output: initialized!
|
||||
}
|
||||
|
||||
// !-lifecycle
|
||||
|
||||
// !+progress
|
||||
|
||||
func Example_progress() {
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
|
||||
mcp.AddTool(server, &mcp.Tool{Name: "makeProgress"}, func(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
|
||||
if token := req.Params.GetProgressToken(); token != nil {
|
||||
for i := range 3 {
|
||||
params := &mcp.ProgressNotificationParams{
|
||||
Message: "frobbing widgets",
|
||||
ProgressToken: token,
|
||||
Progress: float64(i),
|
||||
Total: 2,
|
||||
}
|
||||
req.Session.NotifyProgress(ctx, params) // ignore error
|
||||
}
|
||||
}
|
||||
return &mcp.CallToolResult{}, nil, nil
|
||||
})
|
||||
client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, &mcp.ClientOptions{
|
||||
ProgressNotificationHandler: func(_ context.Context, req *mcp.ProgressNotificationClientRequest) {
|
||||
fmt.Printf("%s %.0f/%.0f\n", req.Params.Message, req.Params.Progress, req.Params.Total)
|
||||
},
|
||||
})
|
||||
ctx := context.Background()
|
||||
t1, t2 := mcp.NewInMemoryTransports()
|
||||
if _, err := server.Connect(ctx, t1, nil); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
session, err := client.Connect(ctx, t2, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer session.Close()
|
||||
if _, err := session.CallTool(ctx, &mcp.CallToolParams{
|
||||
Name: "makeProgress",
|
||||
Meta: mcp.Meta{"progressToken": "abc123"},
|
||||
}); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
// Output:
|
||||
// frobbing widgets 0/2
|
||||
// frobbing widgets 1/2
|
||||
// frobbing widgets 2/2
|
||||
}
|
||||
|
||||
// !-progress
|
||||
|
||||
// !+cancellation
|
||||
|
||||
func Example_cancellation() {
|
||||
// For this example, we're going to be collecting observations from the
|
||||
// server and client.
|
||||
var clientResult, serverResult string
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
|
||||
// Create a server with a single slow tool.
|
||||
// When the client cancels its request, the server should observe
|
||||
// cancellation.
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
|
||||
started := make(chan struct{}, 1) // signals that the server started handling the tool call
|
||||
mcp.AddTool(server, &mcp.Tool{Name: "slow"}, func(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
|
||||
started <- struct{}{}
|
||||
defer wg.Done()
|
||||
select {
|
||||
case <-time.After(5 * time.Second):
|
||||
serverResult = "tool done"
|
||||
case <-ctx.Done():
|
||||
serverResult = "tool canceled"
|
||||
}
|
||||
return &mcp.CallToolResult{}, nil, nil
|
||||
})
|
||||
|
||||
// Connect a client to the server.
|
||||
client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
|
||||
ctx := context.Background()
|
||||
t1, t2 := mcp.NewInMemoryTransports()
|
||||
if _, err := server.Connect(ctx, t1, nil); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
session, err := client.Connect(ctx, t2, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer session.Close()
|
||||
|
||||
// Make a tool call, asynchronously.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "slow"})
|
||||
clientResult = fmt.Sprintf("%v", err)
|
||||
}()
|
||||
|
||||
// As soon as the server has started handling the call, cancel it from the
|
||||
// client side.
|
||||
<-started
|
||||
cancel()
|
||||
wg.Wait()
|
||||
|
||||
fmt.Println(clientResult)
|
||||
fmt.Println(serverResult)
|
||||
// Output:
|
||||
// context canceled
|
||||
// tool canceled
|
||||
}
|
||||
|
||||
// !-cancellation
|
||||
|
|
@ -705,7 +705,7 @@ func TestCancellation(t *testing.T) {
|
|||
start = make(chan struct{})
|
||||
cancelled = make(chan struct{}, 1) // don't block the request
|
||||
)
|
||||
slowRequest := func(ctx context.Context, req *CallToolRequest, args any) (*CallToolResult, any, error) {
|
||||
slowTool := func(ctx context.Context, req *CallToolRequest, args any) (*CallToolResult, any, error) {
|
||||
start <- struct{}{}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
|
|
@ -716,7 +716,7 @@ func TestCancellation(t *testing.T) {
|
|||
return nil, nil, nil
|
||||
}
|
||||
cs, _ := basicConnection(t, func(s *Server) {
|
||||
AddTool(s, &Tool{Name: "slow", InputSchema: &jsonschema.Schema{Type: "object"}}, slowRequest)
|
||||
AddTool(s, &Tool{Name: "slow", InputSchema: &jsonschema.Schema{Type: "object"}}, slowTool)
|
||||
})
|
||||
defer cs.Close()
|
||||
|
||||
|
|
@ -1109,7 +1109,7 @@ func TestElicitationSchemaValidation(t *testing.T) {
|
|||
"low",
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"enumNames": []interface{}{"High Priority", "Medium Priority", "Low Priority"},
|
||||
"enumNames": []any{"High Priority", "Medium Priority", "Low Priority"},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
@ -1270,7 +1270,7 @@ func TestElicitationSchemaValidation(t *testing.T) {
|
|||
"low",
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"enumNames": []interface{}{"High Priority", "Medium Priority"}, // Only 2 names for 3 values
|
||||
"enumNames": []any{"High Priority", "Medium Priority"}, // Only 2 names for 3 values
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,5 +0,0 @@
|
|||
// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mcp
|
||||
|
|
@ -70,9 +70,12 @@ type StreamableHTTPOptions struct {
|
|||
// documentation for [StreamableServerTransport].
|
||||
Stateless bool
|
||||
|
||||
// TODO: support session retention (?)
|
||||
// TODO(#148): support session retention (?)
|
||||
|
||||
// JSONResponse is forwarded to StreamableServerTransport.jsonResponse.
|
||||
// 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
|
||||
}
|
||||
|
||||
|
|
@ -181,7 +184,7 @@ func (h *StreamableHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Reque
|
|||
return
|
||||
}
|
||||
|
||||
// Section 2.7 of the spec (2025-06-18) states:
|
||||
// [§2.7] of the spec (2025-06-18) states:
|
||||
//
|
||||
// "If using HTTP, the client MUST include the MCP-Protocol-Version:
|
||||
// <protocol-version> HTTP header on all subsequent requests to the MCP
|
||||
|
|
@ -209,6 +212,8 @@ func (h *StreamableHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Reque
|
|||
// assume 2025-03-26 if the client doesn't say anything).
|
||||
//
|
||||
// This logic matches the typescript SDK.
|
||||
//
|
||||
// [§2.7]: https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#protocol-version-header
|
||||
protocolVersion := req.Header.Get(protocolVersionHeader)
|
||||
if protocolVersion == "" {
|
||||
protocolVersion = protocolVersion20250326
|
||||
|
|
@ -370,6 +375,9 @@ type StreamableServerTransport struct {
|
|||
// request contain only a single message. In this case, notifications or
|
||||
// requests made within the context of a server request will be sent to the
|
||||
// hanging GET request, if any.
|
||||
//
|
||||
// TODO(rfindley): jsonResponse should be exported, since
|
||||
// StreamableHTTPOptions.JSONResponse is exported.
|
||||
jsonResponse bool
|
||||
|
||||
// connection is non-nil if and only if the transport has been connected.
|
||||
|
|
@ -1188,7 +1196,7 @@ func (c *streamableClientConn) Write(ctx context.Context, msg jsonrpc.Message) e
|
|||
return fmt.Errorf("%s: %v", requestSummary, err)
|
||||
}
|
||||
|
||||
// Section 2.5.3: "The server MAY terminate the session at any time, after
|
||||
// §2.5.3: "The server MAY terminate the session at any time, after
|
||||
// which it MUST respond to requests containing that session ID with HTTP
|
||||
// 404 Not Found."
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
|
|
|
|||
86
mcp/streamable_example_test.go
Normal file
86
mcp/streamable_example_test.go
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mcp_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
// !+streamablehandler
|
||||
|
||||
func ExampleStreamableHTTPHandler() {
|
||||
// Create a new streamable handler, using the same MCP server for every request.
|
||||
//
|
||||
// Here, we configure it to serves application/json responses rather than
|
||||
// text/event-stream, just so the output below doesn't use random event ids.
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.1.0"}, nil)
|
||||
handler := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
|
||||
return server
|
||||
}, &mcp.StreamableHTTPOptions{JSONResponse: true})
|
||||
httpServer := httptest.NewServer(handler)
|
||||
defer httpServer.Close()
|
||||
|
||||
// The SDK is currently permissive of some missing keys in "params".
|
||||
resp := mustPostMessage(`{"jsonrpc": "2.0", "id": 1, "method":"initialize", "params": {}}`, httpServer.URL)
|
||||
fmt.Println(resp)
|
||||
// Output:
|
||||
// {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"logging":{}},"protocolVersion":"2025-06-18","serverInfo":{"name":"server","version":"v0.1.0"}}}
|
||||
}
|
||||
|
||||
// !-streamablehandler
|
||||
|
||||
// !+httpmiddleware
|
||||
|
||||
func ExampleStreamableHTTPHandler_middleware() {
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.1.0"}, nil)
|
||||
handler := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
|
||||
return server
|
||||
}, nil)
|
||||
loggingHandler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
// Example debugging; you could also capture the response.
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
req.Body.Close() // ignore error
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
fmt.Println(req.Method, string(body))
|
||||
handler.ServeHTTP(w, req)
|
||||
})
|
||||
httpServer := httptest.NewServer(loggingHandler)
|
||||
defer httpServer.Close()
|
||||
|
||||
// The SDK is currently permissive of some missing keys in "params".
|
||||
mustPostMessage(`{"jsonrpc": "2.0", "id": 1, "method":"initialize", "params": {}}`, httpServer.URL)
|
||||
// Output:
|
||||
// POST {"jsonrpc": "2.0", "id": 1, "method":"initialize", "params": {}}
|
||||
}
|
||||
|
||||
// !-httpmiddleware
|
||||
|
||||
func mustPostMessage(msg, url string) string {
|
||||
req := orFatal(http.NewRequest("POST", url, strings.NewReader(msg)))
|
||||
req.Header["Content-Type"] = []string{"application/json"}
|
||||
req.Header["Accept"] = []string{"application/json", "text/event-stream"}
|
||||
resp := orFatal(http.DefaultClient.Do(req))
|
||||
defer resp.Body.Close()
|
||||
body := orFatal(io.ReadAll(resp.Body))
|
||||
return string(body)
|
||||
}
|
||||
|
||||
func orFatal[T any](t T, err error) T {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
|
@ -212,12 +212,14 @@ func (t *LoggingTransport) Connect(ctx context.Context) (Connection, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &loggingConn{delegate, t.Writer}, nil
|
||||
return &loggingConn{delegate: delegate, w: t.Writer}, nil
|
||||
}
|
||||
|
||||
type loggingConn struct {
|
||||
delegate Connection
|
||||
w io.Writer
|
||||
|
||||
mu sync.Mutex
|
||||
w io.Writer
|
||||
}
|
||||
|
||||
func (c *loggingConn) SessionID() string { return c.delegate.SessionID() }
|
||||
|
|
@ -225,15 +227,21 @@ func (c *loggingConn) SessionID() string { return c.delegate.SessionID() }
|
|||
// Read is a stream middleware that logs incoming messages.
|
||||
func (s *loggingConn) Read(ctx context.Context) (jsonrpc.Message, error) {
|
||||
msg, err := s.delegate.Read(ctx)
|
||||
|
||||
if err != nil {
|
||||
s.mu.Lock()
|
||||
fmt.Fprintf(s.w, "read error: %v", err)
|
||||
s.mu.Unlock()
|
||||
} else {
|
||||
data, err := jsonrpc2.EncodeMessage(msg)
|
||||
s.mu.Lock()
|
||||
if err != nil {
|
||||
fmt.Fprintf(s.w, "LoggingTransport: failed to marshal: %v", err)
|
||||
}
|
||||
fmt.Fprintf(s.w, "read: %s\n", string(data))
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
return msg, err
|
||||
}
|
||||
|
||||
|
|
@ -241,13 +249,17 @@ func (s *loggingConn) Read(ctx context.Context) (jsonrpc.Message, error) {
|
|||
func (s *loggingConn) Write(ctx context.Context, msg jsonrpc.Message) error {
|
||||
err := s.delegate.Write(ctx, msg)
|
||||
if err != nil {
|
||||
s.mu.Lock()
|
||||
fmt.Fprintf(s.w, "write error: %v", err)
|
||||
s.mu.Unlock()
|
||||
} else {
|
||||
data, err := jsonrpc2.EncodeMessage(msg)
|
||||
s.mu.Lock()
|
||||
if err != nil {
|
||||
fmt.Fprintf(s.w, "LoggingTransport: failed to marshal: %v", err)
|
||||
}
|
||||
fmt.Fprintf(s.w, "write: %s\n", string(data))
|
||||
s.mu.Unlock()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
|
|
|||
40
mcp/transport_example_test.go
Normal file
40
mcp/transport_example_test.go
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mcp_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
// !+loggingtransport
|
||||
|
||||
func ExampleLoggingTransport() {
|
||||
ctx := context.Background()
|
||||
t1, t2 := mcp.NewInMemoryTransports()
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
|
||||
if _, err := server.Connect(ctx, t1, nil); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
|
||||
var b bytes.Buffer
|
||||
logTransport := &mcp.LoggingTransport{Transport: t2, Writer: &b}
|
||||
if _, err := client.Connect(ctx, logTransport, nil); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(b.String())
|
||||
// Output:
|
||||
// write: {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{"roots":{"listChanged":true}},"clientInfo":{"name":"client","version":"v0.0.1"},"protocolVersion":"2025-06-18"}}
|
||||
// read: {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"logging":{}},"protocolVersion":"2025-06-18","serverInfo":{"name":"server","version":"v0.0.1"}}}
|
||||
// write: {"jsonrpc":"2.0","method":"notifications/initialized","params":{}}
|
||||
|
||||
}
|
||||
|
||||
// !-loggingtransport
|
||||
Loading…
Reference in a new issue