feat(capability/mcp): MCP 客户端(stdlib JSON-RPC over stdio/SSE)+ Registry 自动注册/Unregister(registry 增 Remove)
This commit is contained in:
1 parent
08223c06a5
commit
488cf9c79c
14 files changed
+2212
No files matched your search
@@ -0,0 +1,50 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// rpcRequest is a JSON-RPC 2.0 request. Notifications omit ID so the field is
|
||||
// tagged omitempty. Params is any so callers pass a struct or a JSON object.
|
||||
type rpcRequest struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID any `json:"id,omitempty"`
|
||||
Method string `json:"method"`
|
||||
Params any `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
// rpcResponse is a JSON-RPC 2.0 response. Result is kept raw until the caller
|
||||
// decodes it into the concrete result type.
|
||||
type rpcResponse struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID any `json:"id,omitempty"`
|
||||
Result json.RawMessage `json:"result,omitempty"`
|
||||
Error *rpcError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// rpcError is a JSON-RPC error object. It satisfies error so it can be wrapped
|
||||
// and surfaced with %w.
|
||||
type rpcError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// Error implements error.
|
||||
func (e *rpcError) Error() string {
|
||||
return fmt.Sprintf("code %d: %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
// encodeRequest marshals a JSON-RPC request. An id of nil produces a
|
||||
// notification (no id field).
|
||||
func encodeRequest(id any, method string, params any) ([]byte, error) {
|
||||
return json.Marshal(rpcRequest{JSONRPC: "2.0", ID: id, Method: method, Params: params})
|
||||
}
|
||||
|
||||
// decodeIDString reports whether res carries the string id expected for a JSON
|
||||
// string id request.
|
||||
func decodeIDString(res rpcResponse, id string) bool {
|
||||
s, ok := res.ID.(string)
|
||||
return ok && s == id
|
||||
}
|
||||
Reference in new issue
Block a user