You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by zh...@apache.org on 2025/06/22 10:30:00 UTC
(skywalking-mcp) 01/01: feat: add treamable-http server and more tools
This is an automated email from the ASF dual-hosted git repository.
zhouzixin pushed a commit to branch polish-stage1
in repository https://gitbox.apache.org/repos/asf/skywalking-mcp.git
commit 9c1802221bbe1b3803c7efca5ef8f4a00bbdc874
Author: Zixin Zhou <zh...@apache.org>
AuthorDate: Sun Jun 22 18:29:38 2025 +0800
feat: add treamable-http server and more tools
---
.github/dependabot.yml | 4 +-
cmd/skywalking-mcp/main.go | 1 +
go.mod | 2 +-
go.sum | 4 +-
internal/config/config.go | 21 +++++++
internal/swmcp/server.go | 81 ++++++++++++++++++++++++++
internal/swmcp/sse.go | 2 +-
internal/swmcp/stdio.go | 67 ----------------------
internal/swmcp/streamable.go | 73 ++++++++++++++++++++++++
internal/tools/trace.go | 131 ++++++++++++++++++++++++++++++++++++++++---
10 files changed, 306 insertions(+), 80 deletions(-)
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index aacd3d1..28875a5 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -22,9 +22,9 @@ updates:
interval: "daily"
assignees:
- "CodePrometheus"
+ ignore:
+ - dependency-name: "github.com/apache/skywalking-cli"
groups:
actions-deps:
patterns:
- "*"
- exclude-patterns:
- - "github.com/apache/skywalking-cli"
diff --git a/cmd/skywalking-mcp/main.go b/cmd/skywalking-mcp/main.go
index 0504f34..8ad4014 100644
--- a/cmd/skywalking-mcp/main.go
+++ b/cmd/skywalking-mcp/main.go
@@ -79,6 +79,7 @@ func init() {
// Add subcommands
rootCmd.AddCommand(swmcp.NewStdioServer())
rootCmd.AddCommand(swmcp.NewSSEServer())
+ rootCmd.AddCommand(swmcp.NewStreamable())
}
func main() {
diff --git a/go.mod b/go.mod
index 3f0da89..9dd78b3 100644
--- a/go.mod
+++ b/go.mod
@@ -4,7 +4,7 @@ go 1.24.3
require (
github.com/apache/skywalking-cli v0.0.0-20250604010708-77b4c49e89c9
- github.com/mark3labs/mcp-go v0.31.0
+ github.com/mark3labs/mcp-go v0.32.0
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.9.1
github.com/spf13/viper v1.20.1
diff --git a/go.sum b/go.sum
index 9126bd8..586d129 100644
--- a/go.sum
+++ b/go.sum
@@ -23,8 +23,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/machinebox/graphql v0.2.2 h1:dWKpJligYKhYKO5A2gvNhkJdQMNZeChZYyBbrZkBZfo=
github.com/machinebox/graphql v0.2.2/go.mod h1:F+kbVMHuwrQ5tYgU9JXlnskM8nOaFxCAEolaQybkjWA=
-github.com/mark3labs/mcp-go v0.31.0 h1:4UxSV8aM770OPmTvaVe/b1rA2oZAjBMhGBfUgOGut+4=
-github.com/mark3labs/mcp-go v0.31.0/go.mod h1:rXqOudj/djTORU/ThxYx8fqEVj/5pvTuuebQ2RC7uk4=
+github.com/mark3labs/mcp-go v0.32.0 h1:fgwmbfL2gbd67obg57OfV2Dnrhs1HtSdlY/i5fn7MU8=
+github.com/mark3labs/mcp-go v0.32.0/go.mod h1:rXqOudj/djTORU/ThxYx8fqEVj/5pvTuuebQ2RC7uk4=
github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE=
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
diff --git a/internal/config/config.go b/internal/config/config.go
index 81a0f57..239b893 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -68,3 +68,24 @@ type SSEServerConfig struct {
// Base path for the sse server
BasePath string
}
+
+type StreamableServerConfig struct {
+ // SkyWalking OAP URL to target for API requests (e.g. localhost:12800)
+ URL string
+
+ // ReadOnly indicates if we should only offer read-only tools
+ ReadOnly bool
+
+ // Path to the log file if not stderr
+ LogFilePath string
+
+ // LogCommands indicates if we should log commands
+ LogCommands bool
+
+ // The host and port to start the Streamable HTTP transport on
+ // e.g. ":8080" and the default streamable http endpoint will be "/mcp"
+ Address string
+
+ // Base path for the Streamable HTTP transport server
+ EndpointPath string
+}
diff --git a/internal/swmcp/server.go b/internal/swmcp/server.go
index 07067cd..7cdcabd 100644
--- a/internal/swmcp/server.go
+++ b/internal/swmcp/server.go
@@ -18,12 +18,18 @@
package swmcp
import (
+ "context"
"fmt"
+ "net/http"
"os"
+ "strings"
"github.com/mark3labs/mcp-go/server"
"github.com/sirupsen/logrus"
+ "github.com/apache/skywalking-cli/pkg/contextkey"
+
+ "github.com/apache/skywalking-mcp/internal/config"
"github.com/apache/skywalking-mcp/internal/tools"
)
@@ -58,3 +64,78 @@ func initLogger(logFilePath string) (*logrus.Logger, error) {
return logrusLogger, nil
}
+
+// WithSkyWalkingURLAndInsecure adds SkyWalking URL and insecure flag to the context
+// This ensures all downstream requests will have contextkey.BaseURL{} and contextkey.Insecure{}
+func WithSkyWalkingURLAndInsecure(ctx context.Context, url string, insecure bool) context.Context {
+ ctx = context.WithValue(ctx, contextkey.BaseURL{}, url)
+ ctx = context.WithValue(ctx, contextkey.Insecure{}, insecure)
+ return ctx
+}
+
+const (
+ skywalkingURLEnvVar = "SW_URL"
+)
+
+// finalizeURL ensures the URL ends with "/graphql".
+func finalizeURL(urlStr string) string {
+ if !strings.HasSuffix(urlStr, "/graphql") {
+ urlStr = strings.TrimRight(urlStr, "/") + "/graphql"
+ }
+ return urlStr
+}
+
+// urlAndInsecureFromEnv extracts URL and insecure flag purely from environment variables.
+func urlAndInsecureFromEnv() (string, bool) {
+ urlStr := os.Getenv(skywalkingURLEnvVar)
+ if urlStr == "" {
+ urlStr = config.DefaultSWURL
+ }
+ return finalizeURL(urlStr), false
+}
+
+// urlAndInsecureFromHeaders extracts URL and insecure flag for a request.
+// URL is sourced from Header > Environment > Default.
+// Insecure flag is now hardcoded to false.
+func urlAndInsecureFromHeaders(req *http.Request) (string, bool) {
+ urlStr := req.Header.Get("SW-URL")
+ if urlStr == "" {
+ urlStr = os.Getenv(skywalkingURLEnvVar)
+ if urlStr == "" {
+ urlStr = config.DefaultSWURL
+ }
+ }
+
+ return finalizeURL(urlStr), false
+}
+
+// WithSkyWalkingContextFromEnv injects the SkyWalking URL and insecure
+// settings from environment variables into the context.
+var WithSkyWalkingContextFromEnv server.StdioContextFunc = func(ctx context.Context) context.Context {
+ urlStr, _ := urlAndInsecureFromEnv()
+ return WithSkyWalkingURLAndInsecure(ctx, urlStr, false)
+}
+
+// withSkyWalkingContextFromRequest is the shared logic for enriching context from an http.Request.
+func withSkyWalkingContextFromRequest(ctx context.Context, req *http.Request) context.Context {
+ urlStr, _ := urlAndInsecureFromHeaders(req)
+ return WithSkyWalkingURLAndInsecure(ctx, urlStr, false)
+}
+
+// EnhanceStdioContextFunc returns a StdioContextFunc that enriches the context
+// with SkyWalking settings from the environment.
+func EnhanceStdioContextFunc() server.StdioContextFunc {
+ return WithSkyWalkingContextFromEnv
+}
+
+// EnhanceSSEContextFunc returns a SSEContextFunc that enriches the context
+// with SkyWalking settings from SSE request headers.
+func EnhanceSSEContextFunc() server.SSEContextFunc {
+ return withSkyWalkingContextFromRequest
+}
+
+// EnhanceHTTPContextFunc returns a HTTPContextFunc that enriches the context
+// with SkyWalking settings from HTTP request headers.
+func EnhanceHTTPContextFunc() server.HTTPContextFunc {
+ return withSkyWalkingContextFromRequest
+}
diff --git a/internal/swmcp/sse.go b/internal/swmcp/sse.go
index 8f184b6..fd3ccd6 100644
--- a/internal/swmcp/sse.go
+++ b/internal/swmcp/sse.go
@@ -74,7 +74,7 @@ func runSSEServer(ctx context.Context, cfg *config.SSEServerConfig) error {
sseServer := server.NewSSEServer(
newMcpServer(),
server.WithStaticBasePath(cfg.BasePath),
- server.WithSSEContextFunc(EnhanceHTTPContextFunc()),
+ server.WithSSEContextFunc(EnhanceSSEContextFunc()),
)
ssePath := sseServer.CompleteSsePath()
log.Printf("Starting SkyWalking MCP server using SSE transport listening on http://%s%s\n ", cfg.Address, ssePath)
diff --git a/internal/swmcp/stdio.go b/internal/swmcp/stdio.go
index 95c59e7..fe7039b 100644
--- a/internal/swmcp/stdio.go
+++ b/internal/swmcp/stdio.go
@@ -24,13 +24,10 @@ import (
"io"
"log"
"log/slog"
- "net/http"
"os"
"os/signal"
- "strings"
"syscall"
- "github.com/apache/skywalking-cli/pkg/contextkey"
"github.com/mark3labs/mcp-go/server"
"github.com/spf13/cobra"
"github.com/spf13/viper"
@@ -108,67 +105,3 @@ func runStdioServer(ctx context.Context, cfg *config.StdioServerConfig) error {
return nil
}
-
-var ExtractSWURLFromCfg server.StdioContextFunc = func(ctx context.Context) context.Context {
- urlStr := viper.GetString("url")
- if urlStr == "" {
- urlStr = config.DefaultSWURL
- }
-
- // we need to ensure the URL ends with "/graphql"
- if !strings.HasSuffix(urlStr, "/graphql") {
- urlStr = strings.TrimRight(urlStr, "/") + "/graphql"
- }
- return WithSkyWalkingURLAndInsecure(ctx, urlStr)
-}
-
-var ExtractSWURLFromHeaders server.SSEContextFunc = func(ctx context.Context, req *http.Request) context.Context {
- urlStr := req.Header.Get("SW-URL")
- if urlStr == "" {
- urlStr = viper.GetString("url")
- if urlStr == "" {
- urlStr = config.DefaultSWURL
- }
- }
-
- // we need to ensure the URL ends with "/graphql"
- if !strings.HasSuffix(urlStr, "/graphql") {
- urlStr = strings.TrimRight(urlStr, "/") + "/graphql"
- }
- return WithSkyWalkingURLAndInsecure(ctx, urlStr)
-}
-
-func EnhanceStdioContextFuncs(funcs ...server.StdioContextFunc) server.StdioContextFunc {
- return func(ctx context.Context) context.Context {
- for _, f := range funcs {
- ctx = f(ctx)
- }
- return ctx
- }
-}
-
-func EnhanceSSEContextFuncs(funcs ...server.SSEContextFunc) server.SSEContextFunc {
- return func(ctx context.Context, r *http.Request) context.Context {
- for _, f := range funcs {
- ctx = f(ctx, r)
- }
- return ctx
- }
-}
-
-// WithSkyWalkingURLAndInsecure adds the SkyWalking URL and Insecure to the context.
-func WithSkyWalkingURLAndInsecure(ctx context.Context, url string) context.Context {
- ctx = context.WithValue(ctx, contextkey.BaseURL{}, url)
- ctx = context.WithValue(ctx, contextkey.Insecure{}, false)
- return ctx
-}
-
-// EnhanceStdioContextFunc returns a StdioContextFunc that composes all the provided StdioContextFuncs.
-func EnhanceStdioContextFunc() server.StdioContextFunc {
- return EnhanceStdioContextFuncs(ExtractSWURLFromCfg)
-}
-
-// EnhanceHTTPContextFunc returns a SSEContextFunc that composes all the provided HTTPContextFuncs.
-func EnhanceHTTPContextFunc() server.SSEContextFunc {
- return EnhanceSSEContextFuncs(ExtractSWURLFromHeaders)
-}
diff --git a/internal/swmcp/streamable.go b/internal/swmcp/streamable.go
new file mode 100644
index 0000000..dc26d7c
--- /dev/null
+++ b/internal/swmcp/streamable.go
@@ -0,0 +1,73 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you 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 swmcp
+
+import (
+ "fmt"
+
+ "github.com/mark3labs/mcp-go/server"
+ log "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+ "github.com/spf13/viper"
+
+ "github.com/apache/skywalking-mcp/internal/config"
+)
+
+func NewStreamable() *cobra.Command {
+ streamableCmd := &cobra.Command{
+ Use: "streamable",
+ Short: "Start Streamable server",
+ Long: `Starting SkyWalking MCP server with Streamable HTTP transport.`,
+ RunE: func(_ *cobra.Command, _ []string) error {
+ streamableConfig := config.StreamableServerConfig{
+ Address: viper.GetString("address"),
+ EndpointPath: viper.GetString("endpoint-path"),
+ }
+
+ return runStreamableServer(&streamableConfig)
+ },
+ }
+
+ // Add Streamable server specific flags
+ streamableCmd.Flags().String("address", "localhost:8000",
+ "The host and port to start the Streamable server on")
+ streamableCmd.Flags().String("endpoint-path", "/mcp",
+ "The path for the streamable-http server")
+ _ = viper.BindPFlag("address", streamableCmd.Flags().Lookup("address"))
+ _ = viper.BindPFlag("endpoint-path", streamableCmd.Flags().Lookup("endpoint-path"))
+
+ return streamableCmd
+}
+
+// runStreamableServer starts the Streamable server with the provided configuration.
+func runStreamableServer(cfg *config.StreamableServerConfig) error {
+ httpServer := server.NewStreamableHTTPServer(
+ newMcpServer(),
+ server.WithStateLess(true),
+ server.WithLogger(log.StandardLogger()),
+ server.WithHTTPContextFunc(EnhanceHTTPContextFunc()),
+ server.WithEndpointPath(viper.GetString("endpoint-path")),
+ )
+ log.Infof("streamable HTTP server listening on :%s/mcp\n", cfg.Address)
+
+ if err := httpServer.Start(cfg.Address); err != nil {
+ return fmt.Errorf("streamable HTTP server error: %v", err)
+ }
+
+ return nil
+}
diff --git a/internal/tools/trace.go b/internal/tools/trace.go
index 5108d95..2a332a8 100644
--- a/internal/tools/trace.go
+++ b/internal/tools/trace.go
@@ -21,33 +21,150 @@ import (
"context"
"fmt"
- "github.com/apache/skywalking-cli/pkg/graphql/trace"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
api "skywalking.apache.org/repo/goapi/query"
+
+ "github.com/apache/skywalking-cli/pkg/graphql/trace"
)
+const (
+ ViewFull = "full"
+ ViewSummary = "summary"
+ ViewErrorsOnly = "errors_only"
+)
+
+// TraceRequest defines the parameters for the trace tool
type TraceRequest struct {
TraceID string `json:"trace_id"`
+ View string `json:"view,omitempty"`
+}
+
+// TraceSummary provides a high-level overview of a trace
+type TraceSummary struct {
+ TraceID string `json:"trace_id"`
+ TotalSpans int `json:"total_spans"`
+ Services []string `json:"services"`
+ TotalDuration int64 `json:"total_duration_ms"`
+ ErrorCount int `json:"error_count"`
+ HasErrors bool `json:"has_errors"`
+ RootEndpoint string `json:"root_endpoint"`
+ StartTime int64 `json:"start_time_ms"`
+ EndTime int64 `json:"end_time_ms"`
}
-func searchTrace(ctx context.Context, req TraceRequest) (*api.Trace, error) {
+// TraceResponse represents the response that can be different types based on view
+type TraceResponse struct {
+ Data interface{} `json:"data"`
+}
+
+// searchTrace fetches the trace data and processes it based on the requested view
+func searchTrace(ctx context.Context, req TraceRequest) (*TraceResponse, error) {
+ if req.TraceID == "" {
+ return nil, fmt.Errorf("missing required parameter 'trace_id'")
+ }
+ if req.View == "" {
+ req.View = ViewFull // Set default value
+ }
+
traces, err := trace.Trace(ctx, req.TraceID)
if err != nil {
return nil, fmt.Errorf("search trace %v failed: %w", req.TraceID, err)
}
- return &traces, nil
+ traceData := &traces
+
+ if len(traceData.Spans) == 0 {
+ return nil, fmt.Errorf("trace with ID '%s' not found", req.TraceID)
+ }
+
+ var result interface{}
+ switch req.View {
+ case ViewSummary:
+ result = generateTraceSummary(req.TraceID, traceData)
+ case ViewErrorsOnly:
+ result = filterErrorSpans(traceData)
+ case ViewFull:
+ result = traceData
+ default:
+ return nil, fmt.Errorf("invalid view '%s'. Available views are: %s, %s, %s",
+ req.View, ViewFull, ViewSummary, ViewErrorsOnly)
+ }
+
+ return &TraceResponse{Data: result}, nil
+}
+
+// generateTraceSummary creates a summary view from full trace data
+func generateTraceSummary(traceID string, traceData *api.Trace) *TraceSummary {
+ summary := &TraceSummary{
+ TraceID: traceID,
+ TotalSpans: len(traceData.Spans),
+ }
+ services := make(map[string]struct{})
+
+ for _, span := range traceData.Spans {
+ if span == nil {
+ continue
+ }
+ services[span.ServiceCode] = struct{}{}
+ if span.IsError != nil && *span.IsError {
+ summary.ErrorCount++
+ }
+ // Heuristic to find the root span: a span with spanId 0 and parentSpanId -1
+ if span.SpanID == 0 && span.ParentSpanID == -1 {
+ if span.EndpointName != nil {
+ summary.RootEndpoint = *span.EndpointName
+ }
+ summary.StartTime = span.StartTime
+ summary.EndTime = span.EndTime
+ if summary.StartTime > 0 && summary.EndTime > 0 {
+ summary.TotalDuration = summary.EndTime - summary.StartTime
+ }
+ }
+ }
+
+ summary.HasErrors = summary.ErrorCount > 0
+ for service := range services {
+ summary.Services = append(summary.Services, service)
+ }
+ return summary
+}
+
+// filterErrorSpans extracts only the spans with errors from full trace data
+func filterErrorSpans(traceData *api.Trace) []*api.Span {
+ var errorSpans []*api.Span
+ for _, span := range traceData.Spans {
+ if span != nil && span.IsError != nil && *span.IsError {
+ errorSpans = append(errorSpans, span)
+ }
+ }
+ return errorSpans
}
+// AddTraceTools registers trace-related tools with the MCP server
func AddTraceTools(mcp *server.MCPServer) {
SearchTraceTool.Register(mcp)
}
-var SearchTraceTool = NewTool[TraceRequest, *api.Trace](
- "search_trace_by_trace_id",
- "Search for traces by a single TraceId",
+// SearchTraceTool is a tool for searching traces by trace ID with different views
+var SearchTraceTool = NewTool[TraceRequest, *TraceResponse](
+ "get_trace_details",
+ "This tool provides detailed information about a distributed trace, including all its spans, "+
+ "service calls, endpoint names, durations, and error status.\n"+
+ "It allows for different views of the trace data to facilitate quick analysis or deep dives.\n\n"+
+ "Examples:\n"+
+ "- {\"trace_id\": \"...\"}: Get the full trace details.\n"+
+ "- {\"trace_id\": \"...\", \"view\": \"summary\"}: Get a high-level summary of the trace.\n"+
+ "- {\"trace_id\": \"...\", \"view\": \"errors_only\"}: Get only the spans that contain errors.",
searchTrace,
mcp.WithTitleAnnotation("Search a trace by TraceId"),
mcp.WithString("trace_id", mcp.Required(),
- mcp.Description("The TraceId to search for")),
+ mcp.Description("The unique identifier of the trace to retrieve."),
+ ),
+ mcp.WithString("view",
+ mcp.Enum(ViewFull, ViewSummary, ViewErrorsOnly),
+ mcp.Description("Specifies the format of the returned trace data:\n"+
+ "- 'full': (Default) Returns the complete trace object with all spans.\n"+
+ "- 'summary': Returns a condensed summary including services, duration, and error count.\n"+
+ "- 'errors_only': Returns only the spans that are marked as errors."),
+ ),
)