-
Notifications
You must be signed in to change notification settings - Fork 428
mcp: Allow registration of custom JSON-RPC methods #956
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
guglielmo-san
wants to merge
5
commits into
main
Choose a base branch
from
guglielmoc/SEP-2133_extensions_framework
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+302
−3
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
370304a
feat: add support for registering and calling custom JSON-RPC methods…
guglielmo-san c4b8630
feat: add support for registering and calling type-safe custom MCP me…
guglielmo-san 7edd01c
refactor: remove unused custom MCP implementation files
guglielmo-san 51f3a2b
refactor: consolidate custom method tests into mcp_test.go
guglielmo-san e5748ee
refactor: remove trailing whitespace and empty lines from client and …
guglielmo-san File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| // Copyright 2025 The Go MCP SDK Authors. All rights reserved. | ||
| // Use of this source code is governed by the license | ||
| // that can be found in the LICENSE file. | ||
|
|
||
| // The custom-method example demonstrates registering and calling a custom | ||
| // JSON-RPC method that is not part of the standard MCP spec. | ||
| // | ||
| // The server registers a "latin/translate" method that translates simple | ||
| // English phrases into Latin. A client connects over an in-memory transport, | ||
| // calls the custom method, and prints the result. | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "log" | ||
| "strings" | ||
|
|
||
| "github.com/modelcontextprotocol/go-sdk/mcp" | ||
| ) | ||
|
|
||
| type TranslateParams struct { | ||
| mcp.ParamsBase | ||
| Text string `json:"text"` | ||
| } | ||
|
|
||
| type TranslateResult struct { | ||
| mcp.ResultBase | ||
| Latin string `json:"latin"` | ||
| } | ||
|
|
||
| var translations = map[string]string{ | ||
| "hello": "salve", | ||
| "goodbye": "vale", | ||
| "thank you": "gratias tibi ago", | ||
| "how are you": "quid agis", | ||
| "good morning": "bonum mane", | ||
| "good night": "bonam noctem", | ||
| "friend": "amicus", | ||
| "water": "aqua", | ||
| "love": "amor", | ||
| "war": "bellum", | ||
| "peace": "pax", | ||
| "truth": "veritas", | ||
| "light": "lux", | ||
| "time": "tempus", | ||
| "life": "vita", | ||
| "death": "mors", | ||
| "star": "stella", | ||
| "earth": "terra", | ||
| "sea": "mare", | ||
| "the die is cast": "alea iacta est", | ||
| "i came i saw i conquered": "veni vidi vici", | ||
| "seize the day": "carpe diem", | ||
| } | ||
|
|
||
| func main() { | ||
| ctx := context.Background() | ||
|
|
||
| server := mcp.NewServer(&mcp.Implementation{Name: "latin-server", Version: "v1.0.0"}, nil) | ||
|
|
||
| mcp.AddReceivingCustomMethod(server, "latin/translate", | ||
| func(ctx context.Context, ss *mcp.ServerSession, params *TranslateParams) (*TranslateResult, error) { | ||
| key := strings.ToLower(strings.TrimSpace(params.Text)) | ||
| latin, ok := translations[key] | ||
| if !ok { | ||
| latin = fmt.Sprintf("[unknown: %q — try: %s]", params.Text, knownPhrases()) | ||
| } | ||
| return &TranslateResult{Latin: latin}, nil | ||
| }) | ||
|
|
||
| ct, st := mcp.NewInMemoryTransports() | ||
|
|
||
| ss, err := server.Connect(ctx, st, nil) | ||
| if err != nil { | ||
| log.Fatal(err) | ||
| } | ||
| defer ss.Close() | ||
|
|
||
| client := mcp.NewClient(&mcp.Implementation{Name: "latin-client", Version: "v1.0.0"}, nil) | ||
| translate := mcp.AddSendingCustomMethod[*TranslateParams, *TranslateResult](client, "latin/translate") | ||
|
|
||
| cs, err := client.Connect(ctx, ct, nil) | ||
| if err != nil { | ||
| log.Fatal(err) | ||
| } | ||
| defer cs.Close() | ||
|
|
||
| phrases := []string{"Hello", "Seize the day", "Peace", "Truth", "I came I saw I conquered"} | ||
| for _, phrase := range phrases { | ||
| result, err := translate(ctx, cs, &TranslateParams{Text: phrase}) | ||
| if err != nil { | ||
| log.Fatalf("translate %q: %v", phrase, err) | ||
| } | ||
| fmt.Printf("%-35s → %s\n", phrase, result.Latin) | ||
| } | ||
| } | ||
|
|
||
| func knownPhrases() string { | ||
| phrases := make([]string, 0, len(translations)) | ||
| for k := range translations { | ||
| phrases = append(phrases, fmt.Sprintf("%q", k)) | ||
| } | ||
| return strings.Join(phrases, ", ") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,8 @@ import ( | |
| "fmt" | ||
| "iter" | ||
| "log/slog" | ||
| "maps" | ||
| "reflect" | ||
| "slices" | ||
| "strings" | ||
| "sync" | ||
|
|
@@ -32,6 +34,7 @@ type Client struct { | |
| sessions []*ClientSession | ||
| sendingMethodHandler_ MethodHandler | ||
| receivingMethodHandler_ MethodHandler | ||
| customSendMethods map[string]methodInfo | ||
| } | ||
|
|
||
| // NewClient creates a new [Client]. | ||
|
|
@@ -64,6 +67,7 @@ func NewClient(impl *Implementation, options *ClientOptions) *Client { | |
| roots: newFeatureSet(func(r *Root) string { return r.URI }), | ||
| sendingMethodHandler_: defaultSendingMethodHandler, | ||
| receivingMethodHandler_: defaultReceivingMethodHandler[*ClientSession], | ||
| customSendMethods: make(map[string]methodInfo), | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -945,7 +949,13 @@ var clientMethodInfos = map[string]methodInfo{ | |
| } | ||
|
|
||
| func (cs *ClientSession) sendingMethodInfos() map[string]methodInfo { | ||
| return serverMethodInfos | ||
| if len(cs.client.customSendMethods) == 0 { | ||
| return serverMethodInfos | ||
| } | ||
| infos := make(map[string]methodInfo, len(serverMethodInfos)+len(cs.client.customSendMethods)) | ||
| maps.Copy(infos, serverMethodInfos) | ||
| maps.Copy(infos, cs.client.customSendMethods) | ||
| return infos | ||
| } | ||
|
|
||
| func (cs *ClientSession) receivingMethodInfos() map[string]methodInfo { | ||
|
|
@@ -1218,3 +1228,33 @@ func paginate[P listParams, R listResult[T], T any](ctx context.Context, params | |
| } | ||
| } | ||
| } | ||
|
|
||
| // AddSendingCustomMethod registers a custom method that the client can send | ||
| // to the server and returns a typed caller function. | ||
| // | ||
| // The returned function calls the custom method through the client's sending | ||
| // middleware chain, with full type safety on both params and result. | ||
| // | ||
| // callSearch := mcp.AddSendingCustomMethod[*SearchParams, *SearchResult](c, "acme/search") | ||
| // result, err := callSearch(ctx, cs, &SearchParams{Query: "hello"}) | ||
| func AddSendingCustomMethod[P paramsPtr[PT], R Result, PT any]( | ||
| c *Client, | ||
| method string, | ||
| ) func(ctx context.Context, cs *ClientSession, params P) (R, error) { | ||
| mi := methodInfo{ | ||
| newResult: func() Result { | ||
| return reflect.New(reflect.TypeFor[R]().Elem()).Interface().(R) | ||
| }, | ||
| } | ||
|
|
||
| c.mu.Lock() | ||
| defer c.mu.Unlock() | ||
| c.customSendMethods[method] = mi | ||
|
|
||
| return func(ctx context.Context, cs *ClientSession, params P) (R, error) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure exposing this via a return value will cover all the use cases. Most of the users of this will probably be extensions, which will do the registration for the developer. Not sure how easy it will be to propagate this. |
||
| return handleSend[R](ctx, method, &ClientRequest[P]{ | ||
| Session: cs, | ||
| Params: params, | ||
| }) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It feels a bit unnecessary to construct the map on every call. Maybe it's worth moving the source of truth map containing all methods under an appropriate type (
Client?).