refactor: migrate MCP SDK to main repo (#3516)

This commit is contained in:
澄潭
2026-02-16 23:39:18 +08:00
committed by GitHub
parent 87c6cc9c9f
commit 9346f1340b
75 changed files with 10117 additions and 3392 deletions

View File

@@ -0,0 +1,209 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"fmt"
"strconv"
"github.com/higress-group/proxy-wasm-go-sdk/proxywasm"
"github.com/higress-group/proxy-wasm-go-sdk/proxywasm/types"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"google.golang.org/protobuf/proto"
"github.com/higress-group/wasm-go/pkg/iface"
"github.com/higress-group/wasm-go/pkg/log"
pb "github.com/higress-group/wasm-go/pkg/protos"
"github.com/higress-group/wasm-go/pkg/wrapper"
)
const (
CtxJsonRpcID = "jsonRpcID"
CtxNeedPause = "needPause" // Context key to signal if the handler needs to pause
JError = "error"
JCode = "code"
JMessage = "message"
JResult = "result"
ErrParseError = -32700
ErrInvalidRequest = -32600
ErrMethodNotFound = -32601
ErrInvalidParams = -32602
ErrInternalError = -32603
)
// JsonRpcID represents a JSON-RPC ID which can be either a string or a number
type JsonRpcID struct {
StringValue string
IntValue int64
IsString bool
}
// NewJsonRpcIDFromGjson creates a JsonRpcID from a gjson.Result
func NewJsonRpcIDFromGjson(result gjson.Result) JsonRpcID {
if result.Type == gjson.String {
return JsonRpcID{
StringValue: result.String(),
IsString: true,
}
}
return JsonRpcID{
IntValue: result.Int(),
IsString: false,
}
}
type JsonRpcRequestHandler func(context wrapper.HttpContext, id JsonRpcID, method string, params gjson.Result, rawBody []byte) types.Action
type JsonRpcResponseHandler func(context wrapper.HttpContext, id JsonRpcID, result gjson.Result, error gjson.Result, rawBody []byte) types.Action
type JsonRpcMethodHandler func(context wrapper.HttpContext, id JsonRpcID, params gjson.Result) error
type MethodHandlers map[string]JsonRpcMethodHandler
func makeHttpResponse(ctx wrapper.HttpContext, code uint32, debugInfo string, headers [][2]string, body []byte) {
phase := ctx.GetExecutionPhase()
if phase < iface.EncodeHeader {
proxywasm.SendHttpResponseWithDetail(code, debugInfo, headers, body, -1)
return
}
if debugInfo != "" {
log.Infof("response detail info:%s", debugInfo)
}
proxywasm.RemoveHttpResponseHeader("content-length")
proxywasm.ReplaceHttpResponseHeader(":status", strconv.Itoa(int(code)))
for _, kv := range headers {
proxywasm.ReplaceHttpResponseHeader(kv[0], kv[1])
}
if phase == iface.EncodeData {
proxywasm.ReplaceHttpResponseBody(body)
return
}
// EncodeHeader phase
args := &pb.InjectEncodedDataToFilterChainArguments{
Body: string(body),
Endstream: true,
}
argsStr, _ := proto.Marshal(args)
_, err := proxywasm.CallForeignFunction("inject_encoded_data_to_filter_chain_on_header", argsStr)
if err != nil {
log.Warnf("call inject_encoded_data_to_filter_chain_on_header failed, err:%v, fallback to send directly", err)
proxywasm.SendHttpResponseWithDetail(code, debugInfo, headers, body, -1)
return
}
}
func sendJsonRpcResponse(ctx wrapper.HttpContext, id JsonRpcID, extras map[string]any, debugInfo string) {
body := []byte(`{"jsonrpc": "2.0"}`)
if id.IsString {
body, _ = sjson.SetBytes(body, "id", id.StringValue)
} else {
body, _ = sjson.SetBytes(body, "id", id.IntValue)
}
for key, value := range extras {
body, _ = sjson.SetBytes(body, key, value)
}
makeHttpResponse(ctx, 200, debugInfo, [][2]string{{"Content-Type", "application/json; charset=utf-8"}}, body)
}
func OnJsonRpcResponseSuccess(ctx wrapper.HttpContext, result map[string]any, debugInfo ...string) {
var (
id JsonRpcID
ok bool
)
idRaw := ctx.GetContext(CtxJsonRpcID)
if id, ok = idRaw.(JsonRpcID); !ok {
makeHttpResponse(ctx, 500, "not_found_json_rpc_id", nil, []byte("not found json rpc id"))
return
}
responseDebugInfo := "json_rpc_success"
if len(debugInfo) > 0 {
responseDebugInfo = debugInfo[0]
}
sendJsonRpcResponse(ctx, id, map[string]any{JResult: result}, responseDebugInfo)
}
func OnJsonRpcResponseError(ctx wrapper.HttpContext, err error, errorCode int, debugInfo ...string) {
var (
id JsonRpcID
ok bool
)
idRaw := ctx.GetContext(CtxJsonRpcID)
if id, ok = idRaw.(JsonRpcID); !ok {
makeHttpResponse(ctx, 500, "not_found_json_rpc_id", nil, []byte("not found json rpc id"))
return
}
responseDebugInfo := fmt.Sprintf("json_rpc_error(%s)", err)
if len(debugInfo) > 0 {
responseDebugInfo = debugInfo[0]
}
sendJsonRpcResponse(ctx, id, map[string]any{JError: map[string]any{
JMessage: err.Error(),
JCode: errorCode,
}}, responseDebugInfo)
}
func HandleJsonRpcMethod(ctx wrapper.HttpContext, body []byte, handles MethodHandlers) types.Action {
idResult := gjson.GetBytes(body, "id")
id := NewJsonRpcIDFromGjson(idResult)
ctx.SetContext(CtxJsonRpcID, id)
method := gjson.GetBytes(body, "method").String()
params := gjson.GetBytes(body, "params")
if method != "" {
if handle, ok := handles[method]; ok {
log.Debugf("json rpc call method[%s] with params[%s]", method, params.Raw)
// Clear pause flag before calling handler
ctx.SetContext(CtxNeedPause, false)
err := handle(ctx, id, params)
if err != nil {
OnJsonRpcResponseError(ctx, err, ErrInvalidRequest)
return types.ActionContinue
}
// Check if the handler set the pause flag
if needPause := ctx.GetContext(CtxNeedPause); needPause != nil && needPause.(bool) {
return types.ActionPause
}
return types.ActionContinue
}
OnJsonRpcResponseError(ctx, fmt.Errorf("method not found:%s", method), ErrMethodNotFound)
} else {
proxywasm.SendHttpResponseWithDetail(202, "json_rpc_ack", nil, nil, -1)
}
return types.ActionContinue
}
func HandleJsonRpcRequest(ctx wrapper.HttpContext, body []byte, handle JsonRpcRequestHandler) types.Action {
idResult := gjson.GetBytes(body, "id")
id := NewJsonRpcIDFromGjson(idResult)
ctx.SetContext(CtxJsonRpcID, id)
method := gjson.GetBytes(body, "method").String()
params := gjson.GetBytes(body, "params")
log.Debugf("json rpc call method[%s] with params[%s]", method, params.Raw)
return handle(ctx, id, method, params, body)
}
func HandleJsonRpcResponse(ctx wrapper.HttpContext, body []byte, handle JsonRpcResponseHandler) types.Action {
idResult := gjson.GetBytes(body, "id")
id := NewJsonRpcIDFromGjson(idResult)
error := gjson.GetBytes(body, "error")
result := gjson.GetBytes(body, "result")
log.Debugf("json rpc response error[%s] result[%s]", error.Raw, result.Raw)
return handle(ctx, id, result, error, body)
}

View File

@@ -0,0 +1,160 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"encoding/json"
"strings"
"testing"
"github.com/tidwall/gjson"
)
func TestJsonRpcIDFromGjson(t *testing.T) {
tests := []struct {
name string
jsonData string
expected JsonRpcID
}{
{
name: "integer id",
jsonData: `{"id": 123}`,
expected: JsonRpcID{
IntValue: 123,
IsString: false,
},
},
{
name: "string id",
jsonData: `{"id": "abc-123"}`,
expected: JsonRpcID{
StringValue: "abc-123",
IsString: true,
},
},
{
name: "float id treated as int",
jsonData: `{"id": 123.45}`,
expected: JsonRpcID{
IntValue: 123,
IsString: false,
},
},
{
name: "boolean id treated as int",
jsonData: `{"id": true}`,
expected: JsonRpcID{
IntValue: 1,
IsString: false,
},
},
{
name: "null id treated as int zero",
jsonData: `{"id": null}`,
expected: JsonRpcID{
IntValue: 0,
IsString: false,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
idResult := gjson.Get(tt.jsonData, "id")
result := NewJsonRpcIDFromGjson(idResult)
if result.IsString != tt.expected.IsString {
t.Errorf("IsString = %v, want %v", result.IsString, tt.expected.IsString)
}
if result.IsString {
if result.StringValue != tt.expected.StringValue {
t.Errorf("StringValue = %v, want %v", result.StringValue, tt.expected.StringValue)
}
} else {
if result.IntValue != tt.expected.IntValue {
t.Errorf("IntValue = %v, want %v", result.IntValue, tt.expected.IntValue)
}
}
})
}
}
// Skip TestSendJsonRpcResponse because it requires proxywasm which is not available in the test environment
// This function would normally test that sendJsonRpcResponse correctly handles different ID types
func TestSendJsonRpcResponse(t *testing.T) {
t.Skip("Skipping test that requires proxywasm")
}
func TestJsonRpcIDMarshaling(t *testing.T) {
// Test that JsonRpcID is correctly marshaled in a JSON response
tests := []struct {
name string
id JsonRpcID
expected string
}{
{
name: "integer id",
id: JsonRpcID{
IntValue: 123,
IsString: false,
},
expected: `"id":123`,
},
{
name: "string id",
id: JsonRpcID{
StringValue: "abc-123",
IsString: true,
},
expected: `"id":"abc-123"`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a JSON object with the ID
var jsonObj map[string]interface{}
if tt.id.IsString {
jsonObj = map[string]interface{}{
"jsonrpc": "2.0",
"id": tt.id.StringValue,
}
} else {
jsonObj = map[string]interface{}{
"jsonrpc": "2.0",
"id": tt.id.IntValue,
}
}
// Marshal to JSON
body, err := json.Marshal(jsonObj)
if err != nil {
t.Errorf("Failed to marshal JSON: %v", err)
}
// Check that the ID is correctly marshaled
if !json.Valid(body) {
t.Errorf("Invalid JSON: %s", string(body))
}
// Check that the ID is correctly formatted
if !strings.Contains(string(body), tt.expected) {
t.Errorf("ID not correctly formatted. Expected to contain %s, got %s", tt.expected, string(body))
}
})
}
}

View File

@@ -0,0 +1,130 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"fmt"
"github.com/higress-group/proxy-wasm-go-sdk/proxywasm"
"github.com/higress-group/wasm-go/pkg/wrapper"
)
type MCPServerLog struct {
}
func setMCPInfo(msg string) string {
requestIDRaw, _ := proxywasm.GetProperty([]string{"x_request_id"})
requestID := string(requestIDRaw)
if requestID == "" {
requestID = "nil"
}
mcpServerNameRaw, _ := proxywasm.GetProperty([]string{"mcp_server_name"})
mcpServerName := string(mcpServerNameRaw)
mcpToolNameRaw, _ := proxywasm.GetProperty([]string{"mcp_tool_name"})
mcpToolName := string(mcpToolNameRaw)
mcpInfo := mcpServerName
if mcpToolName != "" {
mcpInfo = fmt.Sprintf("%s/%s", mcpServerName, mcpToolName)
}
return fmt.Sprintf("[mcp-server] [%s] [%s] %s", mcpInfo, requestID, msg)
}
func (l MCPServerLog) log(level wrapper.LogLevel, msg string) {
msg = setMCPInfo(msg)
switch level {
case wrapper.LogLevelTrace:
proxywasm.LogTrace(msg)
case wrapper.LogLevelDebug:
proxywasm.LogDebug(msg)
case wrapper.LogLevelInfo:
proxywasm.LogInfo(msg)
case wrapper.LogLevelWarn:
proxywasm.LogWarn(msg)
case wrapper.LogLevelError:
proxywasm.LogError(msg)
case wrapper.LogLevelCritical:
proxywasm.LogCritical(msg)
}
}
func (l MCPServerLog) logFormat(level wrapper.LogLevel, format string, args ...interface{}) {
format = setMCPInfo(format)
switch level {
case wrapper.LogLevelTrace:
proxywasm.LogTracef(format, args...)
case wrapper.LogLevelDebug:
proxywasm.LogDebugf(format, args...)
case wrapper.LogLevelInfo:
proxywasm.LogInfof(format, args...)
case wrapper.LogLevelWarn:
proxywasm.LogWarnf(format, args...)
case wrapper.LogLevelError:
proxywasm.LogErrorf(format, args...)
case wrapper.LogLevelCritical:
proxywasm.LogCriticalf(format, args...)
}
}
func (l MCPServerLog) Trace(msg string) {
l.log(wrapper.LogLevelTrace, msg)
}
func (l MCPServerLog) Tracef(format string, args ...interface{}) {
l.logFormat(wrapper.LogLevelTrace, format, args...)
}
func (l MCPServerLog) Debug(msg string) {
l.log(wrapper.LogLevelDebug, msg)
}
func (l MCPServerLog) Debugf(format string, args ...interface{}) {
l.logFormat(wrapper.LogLevelDebug, format, args...)
}
func (l MCPServerLog) Info(msg string) {
l.log(wrapper.LogLevelInfo, msg)
}
func (l MCPServerLog) Infof(format string, args ...interface{}) {
l.logFormat(wrapper.LogLevelInfo, format, args...)
}
func (l MCPServerLog) Warn(msg string) {
l.log(wrapper.LogLevelWarn, msg)
}
func (l MCPServerLog) Warnf(format string, args ...interface{}) {
l.logFormat(wrapper.LogLevelWarn, format, args...)
}
func (l MCPServerLog) Error(msg string) {
l.log(wrapper.LogLevelError, msg)
}
func (l MCPServerLog) Errorf(format string, args ...interface{}) {
l.logFormat(wrapper.LogLevelError, format, args...)
}
func (l MCPServerLog) Critical(msg string) {
l.log(wrapper.LogLevelCritical, msg)
}
func (l MCPServerLog) Criticalf(format string, args ...interface{}) {
l.logFormat(wrapper.LogLevelCritical, format, args...)
}
func (l MCPServerLog) ResetID(pluginID string) {
}

View File

@@ -0,0 +1,117 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/higress-group/wasm-go/pkg/wrapper"
)
func OnMCPResponseSuccess(ctx wrapper.HttpContext, result map[string]any, debugInfo string) {
OnJsonRpcResponseSuccess(ctx, result, debugInfo)
// TODO: support pub to redis when use POST + SSE
}
func OnMCPResponseError(ctx wrapper.HttpContext, err error, code int, debugInfo string) {
OnJsonRpcResponseError(ctx, err, code, debugInfo)
// TODO: support pub to redis when use POST + SSE
}
func OnMCPToolCallSuccess(ctx wrapper.HttpContext, content []map[string]any, debugInfo string) {
OnMCPResponseSuccess(ctx, map[string]any{
"content": content,
"isError": false,
}, debugInfo)
}
// OnMCPToolCallSuccessWithStructuredContent sends a successful MCP tool response with structured content
// According to MCP spec, structuredContent is a field in tool results, not a capability
func OnMCPToolCallSuccessWithStructuredContent(ctx wrapper.HttpContext, content []map[string]any, structuredContent json.RawMessage, debugInfo string) {
response := map[string]any{
"content": content,
"isError": false,
}
if structuredContent != nil && len(structuredContent) > 0 {
response["structuredContent"] = structuredContent
}
OnMCPResponseSuccess(ctx, response, debugInfo)
}
func OnMCPToolCallError(ctx wrapper.HttpContext, err error, debugInfo ...string) {
responseDebugInfo := fmt.Sprintf("mcp:tools/call:error(%s)", err)
if len(debugInfo) > 0 {
responseDebugInfo = debugInfo[0]
}
OnMCPResponseSuccess(ctx, map[string]any{
"content": []map[string]any{
{
"type": "text",
"text": err.Error(),
},
},
"isError": true,
}, responseDebugInfo)
}
func SendMCPToolTextResult(ctx wrapper.HttpContext, result string, debugInfo ...string) {
responseDebugInfo := "mcp:tools/call::result"
if len(debugInfo) > 0 {
responseDebugInfo = debugInfo[0]
}
OnMCPToolCallSuccess(ctx, []map[string]any{
{
"type": "text",
"text": result,
},
}, responseDebugInfo)
}
func SendMCPToolImageResult(ctx wrapper.HttpContext, image []byte, contentType string, debugInfo ...string) {
responseDebugInfo := "mcp:tools/call::result"
if len(debugInfo) > 0 {
responseDebugInfo = debugInfo[0]
}
content := []map[string]any{
{
"type": "image",
"data": base64.StdEncoding.EncodeToString(image),
"mimeType": contentType,
},
}
// Use traditional response format since no structured data is provided
OnMCPToolCallSuccess(ctx, content, responseDebugInfo)
}
// SendMCPToolTextResultWithStructuredContent sends a tool result with both text content and structured content
// According to MCP spec, for backward compatibility, tools that return structured content
// SHOULD also return the serialized JSON in a TextContent block
func SendMCPToolTextResultWithStructuredContent(ctx wrapper.HttpContext, textResult string, structuredContent json.RawMessage, debugInfo ...string) {
responseDebugInfo := "mcp:tools/call::result"
if len(debugInfo) > 0 {
responseDebugInfo = debugInfo[0]
}
content := []map[string]any{
{
"type": "text",
"text": textResult,
},
}
OnMCPToolCallSuccessWithStructuredContent(ctx, content, structuredContent, responseDebugInfo)
}

View File

@@ -0,0 +1,51 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"net/url"
"github.com/higress-group/proxy-wasm-go-sdk/proxywasm"
"github.com/higress-group/wasm-go/pkg/log"
"github.com/higress-group/wasm-go/pkg/wrapper"
)
func IsStatefulSession(ctx wrapper.HttpContext) bool {
parse, err := url.Parse(ctx.Path())
if err != nil {
log.Errorf("failed to parse request path: %v", err)
return false
}
query, err := url.ParseQuery(parse.RawQuery)
if err != nil {
log.Errorf("failed to parse query params: %v", err)
return false
}
// Protocol version: 2024-11-05
if query.Get("sessionId") != "" {
return true
}
// Protocol version: 2025-03-26
sessionHeader, err := proxywasm.GetHttpRequestHeader("mcp-session-id")
if err != nil {
log.Errorf("failed to get request header: %v", err)
return false
}
if sessionHeader != "" {
return true
}
return false
}