|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package ebpfcommon // import "go.opentelemetry.io/obi/pkg/ebpf/common/http" |
| 5 | + |
| 6 | +import ( |
| 7 | + "bytes" |
| 8 | + "encoding/json" |
| 9 | + "io" |
| 10 | + "log/slog" |
| 11 | + "net/http" |
| 12 | + |
| 13 | + "go.opentelemetry.io/obi/pkg/appolly/app/request" |
| 14 | +) |
| 15 | + |
| 16 | +// mcpMethods enumerates known MCP JSON-RPC method names. |
| 17 | +var mcpMethods = map[string]bool{ |
| 18 | + "initialize": true, |
| 19 | + "notifications/initialized": true, |
| 20 | + "tools/call": true, |
| 21 | + "tools/list": true, |
| 22 | + "resources/read": true, |
| 23 | + "resources/list": true, |
| 24 | + "resources/subscribe": true, |
| 25 | + "resources/unsubscribe": true, |
| 26 | + "resources/templates/list": true, |
| 27 | + "prompts/get": true, |
| 28 | + "prompts/list": true, |
| 29 | + "completion/complete": true, |
| 30 | + "logging/setLevel": true, |
| 31 | + "notifications/cancelled": true, |
| 32 | + "notifications/resources/updated": true, |
| 33 | + "notifications/tools/list_changed": true, |
| 34 | + "notifications/prompts/list_changed": true, |
| 35 | + "ping": true, |
| 36 | +} |
| 37 | + |
| 38 | +// mcpSessionHeader is the HTTP header that carries the MCP session identifier. |
| 39 | +const mcpSessionHeader = "Mcp-Session-Id" |
| 40 | + |
| 41 | +// mcpRequest is the JSON-RPC 2.0 request envelope used by MCP. |
| 42 | +type mcpRequest struct { |
| 43 | + JSONRPC string `json:"jsonrpc"` |
| 44 | + Method string `json:"method"` |
| 45 | + ID json.RawMessage `json:"id,omitempty"` |
| 46 | + Params json.RawMessage `json:"params,omitempty"` |
| 47 | +} |
| 48 | + |
| 49 | +// mcpResponse is the JSON-RPC 2.0 response envelope used by MCP. |
| 50 | +type mcpResponse struct { |
| 51 | + JSONRPC string `json:"jsonrpc"` |
| 52 | + ID json.RawMessage `json:"id,omitempty"` |
| 53 | + Result json.RawMessage `json:"result,omitempty"` |
| 54 | + Error *mcpError `json:"error,omitempty"` |
| 55 | +} |
| 56 | + |
| 57 | +type mcpError struct { |
| 58 | + Code int `json:"code"` |
| 59 | + Message string `json:"message"` |
| 60 | +} |
| 61 | + |
| 62 | +// Param structures for extracting method-specific fields. |
| 63 | + |
| 64 | +type mcpToolCallParams struct { |
| 65 | + Name string `json:"name"` |
| 66 | +} |
| 67 | + |
| 68 | +type mcpResourceParams struct { |
| 69 | + URI string `json:"uri"` |
| 70 | +} |
| 71 | + |
| 72 | +type mcpPromptParams struct { |
| 73 | + Name string `json:"name"` |
| 74 | +} |
| 75 | + |
| 76 | +type mcpInitializeParams struct { |
| 77 | + ProtocolVersion string `json:"protocolVersion"` |
| 78 | +} |
| 79 | + |
| 80 | +type mcpInitializeResult struct { |
| 81 | + ProtocolVersion string `json:"protocolVersion"` |
| 82 | +} |
| 83 | + |
| 84 | +// MCPSpan detects and parses an MCP JSON-RPC request/response pair. |
| 85 | +// It returns the enriched span and true when the request is a valid MCP call, |
| 86 | +// or the original span and false otherwise. |
| 87 | +func MCPSpan(baseSpan *request.Span, req *http.Request, resp *http.Response) (request.Span, bool) { |
| 88 | + if req.Method != http.MethodPost { |
| 89 | + return *baseSpan, false |
| 90 | + } |
| 91 | + |
| 92 | + sessionID := req.Header.Get(mcpSessionHeader) |
| 93 | + |
| 94 | + reqB, err := io.ReadAll(req.Body) |
| 95 | + if err != nil { |
| 96 | + return *baseSpan, false |
| 97 | + } |
| 98 | + req.Body = io.NopCloser(bytes.NewBuffer(reqB)) |
| 99 | + |
| 100 | + reqB = bytes.TrimSpace(reqB) |
| 101 | + if len(reqB) == 0 || reqB[0] != '{' { |
| 102 | + return *baseSpan, false |
| 103 | + } |
| 104 | + |
| 105 | + var rpcReq mcpRequest |
| 106 | + if err := json.Unmarshal(reqB, &rpcReq); err != nil { |
| 107 | + return *baseSpan, false |
| 108 | + } |
| 109 | + |
| 110 | + if !mcpMethods[rpcReq.Method] { |
| 111 | + // Not a recognized MCP method. Check whether the session header |
| 112 | + // was present — that still qualifies the request as MCP even if |
| 113 | + // the method is unknown (e.g. a custom extension method). |
| 114 | + if sessionID == "" { |
| 115 | + return *baseSpan, false |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + slog.Debug("MCP", "method", rpcReq.Method, "request", string(reqB)) |
| 120 | + |
| 121 | + result := &request.MCPCall{ |
| 122 | + Method: rpcReq.Method, |
| 123 | + SessionID: sessionID, |
| 124 | + } |
| 125 | + |
| 126 | + if len(rpcReq.ID) > 0 && string(rpcReq.ID) != "null" { |
| 127 | + result.RequestID = rawIDString(rpcReq.ID) |
| 128 | + } |
| 129 | + |
| 130 | + parseMCPParams(rpcReq, result) |
| 131 | + |
| 132 | + // Parse response for error and protocol version. |
| 133 | + if resp != nil && resp.Body != nil { |
| 134 | + respB, err := getResponseBody(resp) |
| 135 | + if err == nil && len(respB) > 0 { |
| 136 | + parseMCPResponse(respB, result) |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + baseSpan.SubType = request.HTTPSubtypeMCP |
| 141 | + baseSpan.GenAI = &request.GenAI{ |
| 142 | + MCP: result, |
| 143 | + } |
| 144 | + |
| 145 | + return *baseSpan, true |
| 146 | +} |
| 147 | + |
| 148 | +// parseMCPParams extracts method-specific fields from the request params. |
| 149 | +func parseMCPParams(rpcReq mcpRequest, result *request.MCPCall) { |
| 150 | + if len(rpcReq.Params) == 0 { |
| 151 | + return |
| 152 | + } |
| 153 | + |
| 154 | + switch rpcReq.Method { |
| 155 | + case "tools/call": |
| 156 | + var p mcpToolCallParams |
| 157 | + if json.Unmarshal(rpcReq.Params, &p) == nil { |
| 158 | + result.ToolName = p.Name |
| 159 | + } |
| 160 | + case "resources/read", "resources/subscribe", "resources/unsubscribe": |
| 161 | + var p mcpResourceParams |
| 162 | + if json.Unmarshal(rpcReq.Params, &p) == nil { |
| 163 | + result.ResourceURI = p.URI |
| 164 | + } |
| 165 | + case "prompts/get": |
| 166 | + var p mcpPromptParams |
| 167 | + if json.Unmarshal(rpcReq.Params, &p) == nil { |
| 168 | + result.PromptName = p.Name |
| 169 | + } |
| 170 | + case "initialize": |
| 171 | + var p mcpInitializeParams |
| 172 | + if json.Unmarshal(rpcReq.Params, &p) == nil { |
| 173 | + result.ProtocolVer = p.ProtocolVersion |
| 174 | + } |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +// parseMCPResponse extracts error information and protocol version from the response. |
| 179 | +func parseMCPResponse(data []byte, result *request.MCPCall) { |
| 180 | + data = bytes.TrimSpace(data) |
| 181 | + if len(data) == 0 || data[0] != '{' { |
| 182 | + return |
| 183 | + } |
| 184 | + |
| 185 | + var resp mcpResponse |
| 186 | + if err := json.Unmarshal(data, &resp); err != nil { |
| 187 | + return |
| 188 | + } |
| 189 | + |
| 190 | + if resp.Error != nil { |
| 191 | + result.ErrorCode = resp.Error.Code |
| 192 | + result.ErrorMessage = resp.Error.Message |
| 193 | + } |
| 194 | + |
| 195 | + // For initialize responses, extract the negotiated protocol version. |
| 196 | + if result.Method == "initialize" && len(resp.Result) > 0 { |
| 197 | + var initResult mcpInitializeResult |
| 198 | + if json.Unmarshal(resp.Result, &initResult) == nil && initResult.ProtocolVersion != "" { |
| 199 | + result.ProtocolVer = initResult.ProtocolVersion |
| 200 | + } |
| 201 | + } |
| 202 | +} |
0 commit comments