You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by "CodePrometheus (via GitHub)" <gi...@apache.org> on 2025/06/22 10:30:58 UTC

[PR] feat: add treamable-http server and more tools [skywalking-mcp]

CodePrometheus opened a new pull request, #7:
URL: https://github.com/apache/skywalking-mcp/pull/7

   (no comment)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: add treamable-http server and more tools [skywalking-mcp]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #7:
URL: https://github.com/apache/skywalking-mcp/pull/7#discussion_r2162727358


##########
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)

Review Comment:
   The log message hardcodes "/mcp" and prepends a colon before `cfg.Address`. It should interpolate the configured `EndpointPath` and avoid duplicating the colon, e.g.: `log.Infof("streamable HTTP server listening on %s%s\n", cfg.Address, cfg.EndpointPath)`.
   ```suggestion
   	log.Infof("streamable HTTP server listening on %s%s\n", cfg.Address, cfg.EndpointPath)
   ```



##########
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
+

Review Comment:
   [nitpick] Fields like `URL`, `ReadOnly`, `LogFilePath`, and `LogCommands` are defined but never set by `NewStreamable`. Consider adding corresponding flags/bindings or removing unused fields to avoid confusion.
   ```suggestion
   
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: add streamable-http server and more tools [skywalking-mcp]

Posted by "wu-sheng (via GitHub)" <gi...@apache.org>.
wu-sheng commented on PR #7:
URL: https://github.com/apache/skywalking-mcp/pull/7#issuecomment-3025783092

   > This PR includes the following changes:
   > 
   > 
   > 
   > - Log Analysis Tool: query_logs
   > 
   > - Metrics Analysis Tools: query_single_metrics, query_top_n_metrics
   > 
   > - Trace Analysis Tools: get_cold_trace_details, query_traces and polish the get_trace_details tool
   > 
   > - Adds streamable HTTP server support
   
   A suggestion, MQE support may provide more flexibility for users. Of course, it will be more complex to define that in MCP.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: add streamable-http server and more tools [skywalking-mcp]

Posted by "wu-sheng (via GitHub)" <gi...@apache.org>.
wu-sheng merged PR #7:
URL: https://github.com/apache/skywalking-mcp/pull/7


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: add streamable-http server and more tools [skywalking-mcp]

Posted by "kezhenxu94 (via GitHub)" <gi...@apache.org>.
kezhenxu94 commented on code in PR #7:
URL: https://github.com/apache/skywalking-mcp/pull/7#discussion_r2176242572


##########
internal/tools/trace.go:
##########
@@ -19,35 +19,836 @@ package tools
 
 import (
 	"context"
+	"encoding/json"
+	"errors"
 	"fmt"
+	"sort"
+	"strings"
+	"time"
 
-	"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"
+)
+
+// AddTraceTools registers trace-related tools with the MCP server
+func AddTraceTools(mcp *server.MCPServer) {
+	SearchTraceTool.Register(mcp)
+	ColdTraceTool.Register(mcp)
+	TracesQueryTool.Register(mcp)
+}
+
+// View constants
+const (
+	ViewFull       = "full"
+	ViewSummary    = "summary"
+	ViewErrorsOnly = "errors_only"
+)
+
+// Query order constants
+const (
+	QueryOrderStartTime = "start_time"
+	QueryOrderDuration  = "duration"
+)
+
+// Trace state constants
+const (
+	TraceStateSuccess = "success"
+	TraceStateError   = "error"
+	TraceStateAll     = "all"
+)
+
+// Error constants
+const (
+	ErrMissingTraceID         = "missing required parameter: trace_id"
+	ErrFailedToQueryTrace     = "failed to query trace '%s': %v"
+	ErrFailedToQueryColdTrace = "failed to query cold trace '%s': %v"
+	ErrFailedToQueryTraces    = "failed to query traces: %v"
+	ErrNoFilterCondition      = "at least one filter condition must be provided"
+	ErrInvalidDurationRange   = "invalid duration range: min_duration (%d) > max_duration (%d)"
+	ErrNegativePageSize       = "page_size cannot be negative"
+	ErrNegativePageNum        = "page_num cannot be negative"
+	ErrInvalidTraceState      = "invalid trace_state '%s', available states: %s, %s, %s"
+	ErrInvalidQueryOrder      = "invalid query_order '%s', available orders: %s, %s"
+	ErrTraceNotFound          = "trace with ID '%s' not found"
+	ErrInvalidView            = "invalid view '%s', available views: %s, %s, %s"
+	ErrNoTracesFound          = "no traces found matching the query criteria"
+)
+
+const TimeFormatFull = "2006-01-02 15:04:05"
+
+// Trace-specific constants
+const (
+	DefaultTracePageSize = 20
+	DefaultTraceDuration = "1h"
 )
 
+// TraceRequest defines the parameters for the trace tool
 type TraceRequest struct {
 	TraceID string `json:"trace_id"`
+	View    string `json:"view,omitempty"`
+}
+
+// ColdTraceRequest defines the parameters for the cold trace tool
+type ColdTraceRequest struct {
+	TraceID  string `json:"trace_id"`
+	Duration string `json:"duration"`
+	View     string `json:"view,omitempty"`
+}
+
+// SpanTag represents a span tag for filtering traces
+type SpanTag struct {
+	Key   string `json:"key"`
+	Value string `json:"value"`
+}
+
+// TracesQueryRequest defines the parameters for the traces query tool
+type TracesQueryRequest struct {
+	ServiceID          string    `json:"service_id,omitempty"`
+	ServiceInstanceID  string    `json:"service_instance_id,omitempty"`
+	TraceID            string    `json:"trace_id,omitempty"`
+	EndpointID         string    `json:"endpoint_id,omitempty"`
+	Duration           string    `json:"duration,omitempty"`
+	MinTraceDuration   int64     `json:"min_trace_duration,omitempty"`
+	MaxTraceDuration   int64     `json:"max_trace_duration,omitempty"`
+	TraceState         string    `json:"trace_state,omitempty"`
+	QueryOrder         string    `json:"query_order,omitempty"`
+	PageSize           int       `json:"page_size,omitempty"`
+	PageNum            int       `json:"page_num,omitempty"`
+	View               string    `json:"view,omitempty"`
+	SlowTraceThreshold int64     `json:"slow_trace_threshold,omitempty"`
+	Tags               []SpanTag `json:"tags,omitempty"`
+	Cold               bool      `json:"cold,omitempty"`
 }
 
-func searchTrace(ctx context.Context, req TraceRequest) (*api.Trace, error) {
+// 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"`
+}
+
+// TracesSummary provides a high-level overview of multiple traces
+type TracesSummary struct {
+	TotalTraces  int                 `json:"total_traces"`
+	SuccessCount int                 `json:"success_count"`
+	ErrorCount   int                 `json:"error_count"`
+	Services     []string            `json:"services"`
+	Endpoints    []string            `json:"endpoints"`
+	AvgDuration  float64             `json:"avg_duration_ms"`
+	MinDuration  int64               `json:"min_duration_ms"`
+	MaxDuration  int64               `json:"max_duration_ms"`
+	TimeRange    TimeRange           `json:"time_range"`
+	ErrorTraces  []BasicTraceSummary `json:"error_traces,omitempty"`
+	SlowTraces   []BasicTraceSummary `json:"slow_traces,omitempty"`
+}
+
+// BasicTraceSummary provides essential information about a single trace
+type BasicTraceSummary struct {
+	TraceID      string `json:"trace_id"`
+	ServiceName  string `json:"service_name"`
+	EndpointName string `json:"endpoint_name"`
+	StartTime    int64  `json:"start_time_ms"`
+	Duration     int64  `json:"duration_ms"`
+	IsError      bool   `json:"is_error"`
+	SpanCount    int    `json:"span_count"`
+}
+
+// TimeRange represents the time span of the traces
+type TimeRange struct {
+	StartTime int64 `json:"start_time_ms"`
+	EndTime   int64 `json:"end_time_ms"`
+	Duration  int64 `json:"duration_ms"`
+}
+
+// createBasicTraceSummary creates a BasicTraceSummary from trace item data
+func createBasicTraceSummary(traceItem *api.BasicTrace, startTimeMs, duration int64, isError bool) BasicTraceSummary {
+	return BasicTraceSummary{
+		TraceID:      traceItem.TraceIds[0], // Use first trace ID
+		ServiceName:  traceItem.SegmentID,   // Use segment ID as service name
+		EndpointName: strings.Join(traceItem.EndpointNames, ", "),
+		StartTime:    startTimeMs,
+		Duration:     duration,
+		IsError:      isError,
+		SpanCount:    0, // BasicTrace doesn't have span count
+	}
+}
+
+// processTraceResult handles the common logic for processing trace results
+func processTraceResult(traceID string, traceData *api.Trace, view string) (*mcp.CallToolResult, error) {
+	if len(traceData.Spans) == 0 {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrTraceNotFound, traceID)), nil
+	}
+
+	var result interface{}
+	switch view {
+	case ViewSummary:
+		result = generateTraceSummary(traceID, traceData)
+	case ViewErrorsOnly:
+		result = filterErrorSpans(traceData)
+	case ViewFull:
+		result = traceData
+	default:
+		return mcp.NewToolResultError(fmt.Sprintf(ErrInvalidView, view, ViewFull, ViewSummary, ViewErrorsOnly)), nil
+	}
+
+	jsonBytes, err := json.Marshal(result)
+	if err != nil {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrMarshalFailed, err)), nil
+	}
+	return mcp.NewToolResultText(string(jsonBytes)), nil
+}
+
+// validateTraceRequest validates trace request parameters
+func validateTraceRequest(req TraceRequest) error {
+	if req.TraceID == "" {
+		return errors.New(ErrMissingTraceID)
+	}
+	return nil
+}
+
+// validateColdTraceRequest validates cold trace request parameters
+func validateColdTraceRequest(req ColdTraceRequest) error {
+	if req.TraceID == "" {
+		return errors.New(ErrMissingTraceID)
+	}
+	if req.Duration == "" {
+		return errors.New(ErrMissingDuration)
+	}
+	return nil
+}
+
+// searchTrace fetches the trace data and processes it based on the requested view
+func searchTrace(ctx context.Context, req *TraceRequest) (*mcp.CallToolResult, error) {
+	if err := validateTraceRequest(*req); err != nil {
+		return mcp.NewToolResultError(err.Error()), nil
+	}
+	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 mcp.NewToolResultError(fmt.Sprintf(ErrFailedToQueryTrace, req.TraceID, err)), nil
 	}
-	return &traces, nil
+	traceData := &traces
+
+	return processTraceResult(req.TraceID, traceData, req.View)
 }
 
-func AddTraceTools(mcp *server.MCPServer) {
-	SearchTraceTool.Register(mcp)
+// searchColdTrace fetches the trace data from cold storage and processes it based on the requested view
+func searchColdTrace(ctx context.Context, req *ColdTraceRequest) (*mcp.CallToolResult, error) {
+	if err := validateColdTraceRequest(*req); err != nil {
+		return mcp.NewToolResultError(err.Error()), nil
+	}
+	if req.View == "" {
+		req.View = ViewFull // Set default value
+	}
+
+	// Parse duration string to api.Duration
+	duration := ParseDuration(req.Duration, true)
+
+	traces, err := trace.ColdTrace(ctx, duration, req.TraceID)
+	if err != nil {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrFailedToQueryColdTrace, req.TraceID, err)), nil
+	}
+	traceData := &traces
+
+	return processTraceResult(req.TraceID, traceData, req.View)
+}
+
+// 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)
+	}
+	sort.Strings(summary.Services) // Ensure deterministic order
+	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
+}
+
+// validateTracesQueryRequest validates traces query request parameters
+func validateTracesQueryRequest(req *TracesQueryRequest) error {
+	// At least one filter should be provided for meaningful results
+	if req.ServiceID == "" && req.ServiceInstanceID == "" && req.TraceID == "" &&
+		req.EndpointID == "" && req.Duration == "" && req.MinTraceDuration == 0 &&
+		req.MaxTraceDuration == 0 {
+		return errors.New(ErrNoFilterCondition)
+	}
+
+	// Validate duration range
+	if req.MinTraceDuration > 0 && req.MaxTraceDuration > 0 && req.MinTraceDuration > req.MaxTraceDuration {
+		return fmt.Errorf(ErrInvalidDurationRange, req.MinTraceDuration, req.MaxTraceDuration)
+	}
+
+	// Validate pagination
+	if req.PageSize < 0 {
+		return errors.New(ErrNegativePageSize)
+	}
+	if req.PageNum < 0 {
+		return errors.New(ErrNegativePageNum)
+	}
+
+	return nil
+}
+
+// setBasicFields sets basic fields in the query condition
+func setBasicFields(req *TracesQueryRequest, condition *api.TraceQueryCondition) {
+	if req.ServiceID != "" {
+		condition.ServiceID = &req.ServiceID
+	}
+	if req.ServiceInstanceID != "" {
+		condition.ServiceInstanceID = &req.ServiceInstanceID
+	}
+	if req.TraceID != "" {
+		condition.TraceID = &req.TraceID
+	}
+	if req.EndpointID != "" {
+		condition.EndpointID = &req.EndpointID
+	}
+	if req.MinTraceDuration > 0 {
+		minDuration := int(req.MinTraceDuration)
+		condition.MinTraceDuration = &minDuration
+	}
+	if req.MaxTraceDuration > 0 {
+		maxDuration := int(req.MaxTraceDuration)
+		condition.MaxTraceDuration = &maxDuration
+	}
+}
+
+// setTags sets tags in the query condition
+func setTags(req *TracesQueryRequest, condition *api.TraceQueryCondition) {
+	if len(req.Tags) > 0 {
+		apiTags := make([]*api.SpanTag, len(req.Tags))
+		for i, tag := range req.Tags {
+			apiTags[i] = &api.SpanTag{
+				Key:   tag.Key,
+				Value: &tag.Value,
+			}
+		}
+		condition.Tags = apiTags
+	}
+}
+
+// setDuration sets duration in the query condition
+func setDuration(req *TracesQueryRequest, condition *api.TraceQueryCondition) {
+	if req.Duration != "" {
+		duration := ParseDuration(req.Duration, req.Cold)
+		condition.QueryDuration = &duration
+	} else if req.TraceID == "" {
+		// If no duration and no traceId provided, set default duration (last 1 hour)
+		// SkyWalking OAP requires either queryDuration or traceId
+		defaultDuration := ParseDuration(DefaultTraceDuration, req.Cold)
+		condition.QueryDuration = &defaultDuration
+	}
+}
+
+// setTraceState sets trace state in the query condition
+func setTraceState(req *TracesQueryRequest, condition *api.TraceQueryCondition) error {
+	switch req.TraceState {
+	case TraceStateSuccess:
+		condition.TraceState = api.TraceStateSuccess
+	case TraceStateError:
+		condition.TraceState = api.TraceStateError
+	case TraceStateAll, "":
+		condition.TraceState = api.TraceStateAll
+	default:
+		return fmt.Errorf(ErrInvalidTraceState,
+			req.TraceState, TraceStateSuccess, TraceStateError, TraceStateAll)
+	}
+	return nil
+}
+
+// setQueryOrder sets query order in the query condition
+func setQueryOrder(req *TracesQueryRequest, condition *api.TraceQueryCondition) error {
+	switch req.QueryOrder {
+	case QueryOrderStartTime, "":
+		condition.QueryOrder = api.QueryOrderByStartTime
+	case QueryOrderDuration:
+		condition.QueryOrder = api.QueryOrderByDuration
+	default:
+		return fmt.Errorf(ErrInvalidQueryOrder,
+			req.QueryOrder, QueryOrderStartTime, QueryOrderDuration)
+	}
+	return nil
+}
+
+// setPagination sets pagination in the query condition
+func setPagination(req *TracesQueryRequest, condition *api.TraceQueryCondition) {
+	pageSize := req.PageSize
+	if pageSize == 0 {
+		pageSize = DefaultTracePageSize
+	}
+	condition.Paging = BuildPagination(req.PageNum, pageSize)
+}
+
+// buildQueryCondition builds the query condition from request parameters
+func buildQueryCondition(req *TracesQueryRequest) (*api.TraceQueryCondition, error) {
+	condition := &api.TraceQueryCondition{
+		TraceState: api.TraceStateAll,         // Default to all traces
+		QueryOrder: api.QueryOrderByStartTime, // Default order
+	}
+
+	// Set basic fields
+	setBasicFields(req, condition)
+
+	// Set tags
+	setTags(req, condition)
+
+	// Set duration
+	setDuration(req, condition)
+
+	// Set trace state
+	if err := setTraceState(req, condition); err != nil {
+		return nil, err
+	}
+
+	// Set query order
+	if err := setQueryOrder(req, condition); err != nil {
+		return nil, err
+	}
+
+	// Set pagination
+	setPagination(req, condition)
+
+	return condition, nil
+}
+
+// searchTraces fetches traces based on query conditions
+func searchTraces(ctx context.Context, req *TracesQueryRequest) (*mcp.CallToolResult, error) {
+	if err := validateTracesQueryRequest(req); err != nil {
+		return mcp.NewToolResultError(err.Error()), nil
+	}
+
+	// Set default view
+	if req.View == "" {
+		req.View = ViewFull // Default to full view
+	}
+
+	// Build query condition
+	condition, err := buildQueryCondition(req)
+	if err != nil {
+		return mcp.NewToolResultError(err.Error()), nil
+	}
+
+	// Execute query
+	traces, err := trace.Traces(ctx, condition)
+	if err != nil {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrFailedToQueryTraces, err)), nil
+	}
+
+	return processTracesResult(&traces, req.View, req.SlowTraceThreshold)
+}
+
+// processTracesResult handles the common logic for processing traces query results
+func processTracesResult(traces *api.TraceBrief, view string, slowTraceThreshold int64) (*mcp.CallToolResult, error) {
+	if traces == nil || len(traces.Traces) == 0 {
+		return mcp.NewToolResultError(ErrNoTracesFound), nil
+	}
+
+	var result interface{}
+	switch view {
+	case ViewSummary:
+		result = generateTracesSummary(traces, slowTraceThreshold)
+	case ViewErrorsOnly:
+		result = filterErrorTraces(traces)
+	case ViewFull:
+		result = traces
+	default:
+		return mcp.NewToolResultError(fmt.Sprintf(ErrInvalidView, view, ViewFull, ViewSummary, ViewErrorsOnly)), nil
+	}
+
+	jsonBytes, err := json.Marshal(result)
+	if err != nil {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrMarshalFailed, err)), nil
+	}
+	return mcp.NewToolResultText(string(jsonBytes)), nil
 }
 
-var SearchTraceTool = NewTool[TraceRequest, *api.Trace](
-	"search_trace_by_trace_id",
-	"Search for traces by a single TraceId",
+// processTraceItem processes a single trace item and updates summary statistics
+func processTraceItem(traceItem *api.BasicTrace, summary *TracesSummary,
+	services, endpoints map[string]struct{}, durations *[]int64,
+	errorTraces, slowTraces *[]BasicTraceSummary, slowTraceThreshold int64,
+	minStartTime, maxEndTime *int64, totalDuration *int64) {
+	if traceItem == nil {
+		return
+	}
+
+	// Parse start time
+	startTime, err := time.Parse(TimeFormatFull, traceItem.Start)
+	if err != nil {
+		return // Skip invalid traces
+	}
+	startTimeMs := startTime.UnixMilli()
+	endTimeMs := startTimeMs + int64(traceItem.Duration)
+
+	// Track time range
+	if *minStartTime == 0 || startTimeMs < *minStartTime {
+		*minStartTime = startTimeMs
+	}
+	if endTimeMs > *maxEndTime {
+		*maxEndTime = endTimeMs
+	}
+
+	// Calculate duration
+	duration := int64(traceItem.Duration)
+	*durations = append(*durations, duration)
+	*totalDuration += duration
+
+	// Count errors
+	isError := traceItem.IsError != nil && *traceItem.IsError
+	if isError {
+		summary.ErrorCount++
+		*errorTraces = append(*errorTraces, createBasicTraceSummary(traceItem, startTimeMs, duration, true))
+	} else {
+		summary.SuccessCount++
+	}
+
+	// Identify slow traces only if threshold is configured
+	if slowTraceThreshold > 0 && duration > slowTraceThreshold {
+		*slowTraces = append(*slowTraces, createBasicTraceSummary(traceItem, startTimeMs, duration, isError))
+	}
+
+	// Collect services and endpoints
+	services[traceItem.SegmentID] = struct{}{}
+	for _, endpoint := range traceItem.EndpointNames {
+		if endpoint != "" {
+			endpoints[endpoint] = struct{}{}
+		}
+	}
+}
+
+// calculateStatistics calculates summary statistics from durations
+func calculateStatistics(durations []int64, totalDuration int64) (avgDuration float64, minDuration, maxDuration int64) {
+	if len(durations) == 0 {
+		return 0, 0, 0
+	}
+
+	sort.Slice(durations, func(i, j int) bool {
+		return durations[i] < durations[j]
+	})
+
+	avgDuration = float64(totalDuration) / float64(len(durations))
+	minDuration = durations[0]
+	maxDuration = durations[len(durations)-1]
+
+	return
+}
+
+// generateTracesSummary creates a comprehensive summary from multiple traces
+func generateTracesSummary(traces *api.TraceBrief, slowTraceThreshold int64) *TracesSummary {
+	if traces == nil || len(traces.Traces) == 0 {
+		return &TracesSummary{}
+	}
+
+	summary := &TracesSummary{
+		TotalTraces: len(traces.Traces),
+	}
+
+	services := make(map[string]struct{})
+	endpoints := make(map[string]struct{})
+	var durations []int64
+	var errorTraces []BasicTraceSummary
+	var slowTraces []BasicTraceSummary
+
+	var minStartTime, maxEndTime int64
+	var totalDuration int64
+
+	// Process each trace item
+	for _, traceItem := range traces.Traces {
+		processTraceItem(traceItem, summary, services, endpoints, &durations,
+			&errorTraces, &slowTraces, slowTraceThreshold, &minStartTime, &maxEndTime, &totalDuration)
+	}
+
+	// Calculate statistics
+	summary.AvgDuration, summary.MinDuration, summary.MaxDuration =
+		calculateStatistics(durations, totalDuration)
+
+	// Set time range
+	summary.TimeRange = TimeRange{
+		StartTime: minStartTime,
+		EndTime:   maxEndTime,
+		Duration:  maxEndTime - minStartTime,
+	}
+
+	// Convert maps to slices
+	for service := range services {
+		summary.Services = append(summary.Services, service)
+	}
+	sort.Strings(summary.Services) // Ensure deterministic order
+	for endpoint := range endpoints {
+		summary.Endpoints = append(summary.Endpoints, endpoint)
+	}
+
+	// Sort error and slow traces by duration (descending)
+	sort.Slice(errorTraces, func(i, j int) bool {
+		return errorTraces[i].Duration > errorTraces[j].Duration
+	})
+	sort.Slice(slowTraces, func(i, j int) bool {
+		return slowTraces[i].Duration > slowTraces[j].Duration
+	})
+
+	summary.ErrorTraces = errorTraces
+	summary.SlowTraces = slowTraces
+
+	return summary
+}
+
+// filterErrorTraces extracts only error traces from the results
+func filterErrorTraces(traces *api.TraceBrief) []BasicTraceSummary {
+	if traces == nil {
+		return nil
+	}
+
+	var errorTraces []BasicTraceSummary
+	for _, traceItem := range traces.Traces {
+		if traceItem != nil && traceItem.IsError != nil && *traceItem.IsError {
+			// Parse start time
+			startTime, err := time.Parse(TimeFormatFull, traceItem.Start)
+			if err != nil {
+				continue
+			}
+			startTimeMs := startTime.UnixMilli()
+
+			errorTraces = append(errorTraces,
+				createBasicTraceSummary(traceItem, startTimeMs, int64(traceItem.Duration), true))
+		}
+	}
+
+	// Sort by duration (descending) to show slowest errors first
+	sort.Slice(errorTraces, func(i, j int) bool {
+		return errorTraces[i].Duration > errorTraces[j].Duration
+	})
+
+	return errorTraces
+}
+
+// SearchTraceTool is a tool for searching traces by trace ID with different views
+var SearchTraceTool = NewTool[TraceRequest, *mcp.CallToolResult](
+	"get_trace_details",
+	"This tool provides detailed information about a distributed trace from SkyWalking OAP.\n\n"+
+		"Workflow:\n"+
+		"1. Use this tool when you need to analyze a specific trace by its trace ID\n"+
+		"2. Choose the appropriate view based on your analysis needs:\n"+
+		"   - 'full': For complete trace analysis with all spans and details\n"+
+		"   - 'summary': For quick overview and performance metrics\n"+
+		"   - 'errors_only': For troubleshooting and error investigation\n\n"+
+		"Best Practices:\n"+
+		"- Use 'summary' view first to get an overview of the trace\n"+
+		"- Switch to 'errors_only' if the summary shows errors\n"+
+		"- Use 'full' view for detailed debugging and span-by-span analysis\n"+
+		"- Trace IDs are typically found in logs, error messages, or monitoring dashboards\n\n"+
+		"Examples:\n"+
+		"- {\"trace_id\": \"abc123...\"}: Get complete trace details for analysis\n"+
+		"- {\"trace_id\": \"abc123...\", \"view\": \"summary\"}: Quick performance overview\n"+
+		"- {\"trace_id\": \"abc123...\", \"view\": \"errors_only\"}: Focus on error spans only",
 	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. "+
+			"Trace IDs are typically 32-character hexadecimal strings found in application logs or monitoring systems."),
+	),
+	mcp.WithString("view",
+		mcp.Enum(ViewFull, ViewSummary, ViewErrorsOnly),
+		mcp.Description("Specifies the level of detail for trace analysis:\n"+
+			"- 'full': (Default) Complete trace with all spans, service calls, and metadata\n"+
+			"- 'summary': High-level overview with services, duration, and error count\n"+
+			"- 'errors_only': Only spans marked as errors for troubleshooting"),
+	),
+)
+
+// ColdTraceTool is a tool for searching traces from cold storage by trace ID with different views
+var ColdTraceTool = NewTool[ColdTraceRequest, *mcp.CallToolResult](
+	"get_cold_trace_details",
+	"This tool queries BanyanDB cold storage for historical trace data that may no longer be available in hot storage.\n\n"+
+		"Important Notes:\n"+
+		"- Only works with BanyanDB storage backend\n"+
+		"- Queries older trace data that has been moved to cold storage\n"+
+		"- May have slower response times compared to hot storage queries\n"+
+		"- Use when trace data is not found in regular trace queries\n\n"+
+		"Duration Format:\n"+
+		"- Standard Go duration: \"7d\", \"1h\", \"-30m\", \"2h30m\"\n"+
+		"- Negative values mean \"ago\": \"-7d\" = 7 days ago to now\n"+
+		"- Positive values mean \"from now\": \"2h\" = now to 2 hours later\n"+
+		"- Legacy format: \"6d\", \"12h\" (backward compatible)\n\n"+
+		"Usage Scenarios:\n"+
+		"- Historical incident investigation\n"+
+		"- Long-term performance analysis\n"+
+		"- Compliance and audit requirements\n"+
+		"- When hot storage queries return no results\n\n"+
+		"Examples:\n"+
+		"- {\"trace_id\": \"abc123...\", \"duration\": \"7d\"}: Search last 7 days of cold storage\n"+
+		"- {\"trace_id\": \"abc123...\", \"duration\": \"-30m\"}: Search from 30 minutes ago to now\n"+
+		"- {\"trace_id\": \"abc123...\", \"duration\": \"1h\", \"view\": \"summary\"}: Quick summary from last hour\n"+
+		"- {\"trace_id\": \"abc123...\", \"duration\": \"2h30m\", \"view\": \"errors_only\"}: "+
+		"Error analysis from last 2.5 hours",
+	searchColdTrace,
+	mcp.WithTitleAnnotation("Search a cold trace by TraceId"),
+	mcp.WithString("trace_id", mcp.Required(),
+		mcp.Description("The unique identifier of the trace to retrieve from cold storage. "+
+			"Use this when regular trace queries return no results."),
+	),
+	mcp.WithString("duration", mcp.Required(),
+		mcp.Description("Time duration for cold storage query. "+
+			"Examples: \"7d\" (last 7 days), \"-30m\" (last 30 minutes), \"2h30m\" (last 2.5 hours)"),
+	),
+	mcp.WithString("view",
+		mcp.Enum(ViewFull, ViewSummary, ViewErrorsOnly),
+		mcp.Description("Specifies the level of detail for cold trace analysis:\n"+
+			"- 'full': (Default) Complete trace with all spans from cold storage\n"+
+			"- 'summary': High-level overview with services, duration, and error count\n"+
+			"- 'errors_only': Only error spans for focused troubleshooting"),
+	),
+)
+
+// TracesQueryTool is a tool for querying traces with various conditions
+var TracesQueryTool = NewTool[TracesQueryRequest, *mcp.CallToolResult](
+	"query_traces",
+	"This tool queries traces from SkyWalking OAP based on various conditions and provides intelligent data processing for LLM analysis.\n\n"+

Review Comment:
   same here



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: add streamable-http server and more tools [skywalking-mcp]

Posted by "kezhenxu94 (via GitHub)" <gi...@apache.org>.
kezhenxu94 commented on code in PR #7:
URL: https://github.com/apache/skywalking-mcp/pull/7#discussion_r2176241597


##########
internal/tools/log.go:
##########
@@ -0,0 +1,125 @@
+// 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 tools
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+
+	"github.com/mark3labs/mcp-go/mcp"
+	"github.com/mark3labs/mcp-go/server"
+	api "skywalking.apache.org/repo/goapi/query"
+
+	swlog "github.com/apache/skywalking-cli/pkg/graphql/log"
+)
+
+// AddLogTools registers log-related tools with the MCP server
+func AddLogTools(mcp *server.MCPServer) {
+	LogQueryTool.Register(mcp)
+}
+
+type LogTag struct {
+	Key   string `json:"key"`
+	Value string `json:"value"`
+}
+
+type LogQueryRequest struct {
+	ServiceID         string   `json:"service_id,omitempty"`
+	ServiceInstanceID string   `json:"service_instance_id,omitempty"`
+	EndpointID        string   `json:"endpoint_id,omitempty"`
+	TraceID           string   `json:"trace_id,omitempty"`
+	Tags              []LogTag `json:"tags,omitempty"`
+	Start             string   `json:"start,omitempty"`
+	End               string   `json:"end,omitempty"`
+	Step              string   `json:"step,omitempty"`
+	Cold              bool     `json:"cold,omitempty"`
+	PageNum           int      `json:"page_num,omitempty"`
+	PageSize          int      `json:"page_size,omitempty"`
+}
+
+// buildLogQueryCondition builds the log query condition from request parameters
+func buildLogQueryCondition(req *LogQueryRequest) *api.LogQueryCondition {
+	duration := BuildDuration(req.Start, req.End, req.Step, req.Cold, DefaultDuration)
+
+	var tags []*api.LogTag
+	for _, t := range req.Tags {
+		v := t.Value
+		tags = append(tags, &api.LogTag{Key: t.Key, Value: &v})
+	}
+
+	paging := BuildPagination(req.PageNum, req.PageSize)
+
+	cond := &api.LogQueryCondition{
+		ServiceID:         &req.ServiceID,
+		ServiceInstanceID: &req.ServiceInstanceID,
+		EndpointID:        &req.EndpointID,
+		RelatedTrace:      &api.TraceScopeCondition{TraceID: req.TraceID},
+		QueryDuration:     &duration,
+		Paging:            paging,
+	}
+
+	if len(tags) > 0 {
+		cond.Tags = tags
+	}
+	return cond
+}
+
+// queryLogs queries logs from SkyWalking OAP
+func queryLogs(ctx context.Context, req *LogQueryRequest) (*mcp.CallToolResult, error) {
+	cond := buildLogQueryCondition(req)
+
+	logs, err := swlog.Logs(ctx, cond)
+	if err != nil {
+		return mcp.NewToolResultError(fmt.Sprintf("failed to query logs: %v", err)), nil
+	}
+
+	jsonBytes, err := json.Marshal(logs)
+	if err != nil {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrMarshalFailed, err)), nil
+	}
+	return mcp.NewToolResultText(string(jsonBytes)), nil
+}
+
+var LogQueryTool = NewTool[LogQueryRequest, *mcp.CallToolResult](
+	"query_logs",
+	"Query logs from SkyWalking OAP with flexible filters.\n\n"+
+		"Workflow:\n"+
+		"1. Use this tool to find logs matching specific criteria\n"+
+		"2. Specify one or more query conditions to narrow down results\n"+
+		"3. Use duration to limit the time range for the search\n"+
+		"4. Supports filtering by service, instance, endpoint, trace, tags, and time\n"+
+		"5. Supports cold storage query and pagination\n\n"+
+		"Examples:\n"+
+		"- {\"service_id\": \"Your_ApplicationName\", \"start\": \"2024-06-01 12:00:00\", "+
+		"\"end\": \"2024-06-01 13:00:00\"}: Query logs for a service in a time range\n"+
+		"- {\"trace_id\": \"abc123...\"}: Query logs related to a specific trace\n"+
+		"- {\"tags\": [{\"key\": \"level\", \"value\": \"ERROR\"}], \"cold\": true}: Query error logs from cold storage\n",

Review Comment:
   consider using backtick string to avoid too many escape characters
   
   https://go.dev/ref/spec#String_literals



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: add streamable-http server and more tools [skywalking-mcp]

Posted by "CodePrometheus (via GitHub)" <gi...@apache.org>.
CodePrometheus commented on PR #7:
URL: https://github.com/apache/skywalking-mcp/pull/7#issuecomment-3024601111

   > Could you update PR descriptions about which new features are added by this?
   
   updated.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: add streamable-http server and more tools [skywalking-mcp]

Posted by "wu-sheng (via GitHub)" <gi...@apache.org>.
wu-sheng commented on PR #7:
URL: https://github.com/apache/skywalking-mcp/pull/7#issuecomment-3024572257

   Could you update PR descriptions about which new features are added by this?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: add treamable-http server and more tools [skywalking-mcp]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #7:
URL: https://github.com/apache/skywalking-mcp/pull/7#discussion_r2175440888


##########
internal/tools/trace.go:
##########
@@ -19,35 +19,843 @@ package tools
 
 import (
 	"context"
+	"encoding/json"
+	"errors"
 	"fmt"
+	"sort"
+	"strings"
+	"time"
 
-	"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"
+)
+
+// AddTraceTools registers trace-related tools with the MCP server
+func AddTraceTools(mcp *server.MCPServer) {
+	SearchTraceTool.Register(mcp)
+	ColdTraceTool.Register(mcp)
+	TracesQueryTool.Register(mcp)
+}
+
+// View constants
+const (
+	ViewFull       = "full"
+	ViewSummary    = "summary"
+	ViewErrorsOnly = "errors_only"
+)
+
+// Query order constants
+const (
+	QueryOrderStartTime     = "start_time"
+	QueryOrderDuration      = "duration"
+	QueryOrderStartTimeDesc = "start_time_desc"
+	QueryOrderDurationDesc  = "duration_desc"
+)
+
+// Trace state constants
+const (
+	TraceStateSuccess = "success"
+	TraceStateError   = "error"
+	TraceStateAll     = "all"
+)
+
+// Error constants
+const (
+	ErrMissingTraceID         = "missing required parameter: trace_id"
+	ErrFailedToQueryTrace     = "failed to query trace '%s': %v"
+	ErrFailedToQueryColdTrace = "failed to query cold trace '%s': %v"
+	ErrFailedToQueryTraces    = "failed to query traces: %v"
+	ErrNoFilterCondition      = "at least one filter condition must be provided"
+	ErrInvalidDurationRange   = "invalid duration range: min_duration (%d) > max_duration (%d)"
+	ErrNegativePageSize       = "page_size cannot be negative"
+	ErrNegativePageNum        = "page_num cannot be negative"
+	ErrInvalidTraceState      = "invalid trace_state '%s', available states: %s, %s, %s"
+	ErrInvalidQueryOrder      = "invalid query_order '%s', available orders: %s, %s, %s, %s"
+	ErrTraceNotFound          = "trace with ID '%s' not found"
+	ErrInvalidView            = "invalid view '%s', available views: %s, %s, %s"
+	ErrNoTracesFound          = "no traces found matching the query criteria"
+)
+
+const TimeFormatFull = "2006-01-02 15:04:05"
+
+// Trace-specific constants
+const (
+	DefaultTracePageSize = 20
+	DefaultTraceDuration = "1h"
 )
 
+// TraceRequest defines the parameters for the trace tool
 type TraceRequest struct {
 	TraceID string `json:"trace_id"`
+	View    string `json:"view,omitempty"`
+}
+
+// ColdTraceRequest defines the parameters for the cold trace tool
+type ColdTraceRequest struct {
+	TraceID  string `json:"trace_id"`
+	Duration string `json:"duration"`
+	View     string `json:"view,omitempty"`
+}
+
+// SpanTag represents a span tag for filtering traces
+type SpanTag struct {
+	Key   string `json:"key"`
+	Value string `json:"value"`
+}
+
+// TracesQueryRequest defines the parameters for the traces query tool
+type TracesQueryRequest struct {
+	ServiceID          string    `json:"service_id,omitempty"`
+	ServiceInstanceID  string    `json:"service_instance_id,omitempty"`
+	TraceID            string    `json:"trace_id,omitempty"`
+	EndpointID         string    `json:"endpoint_id,omitempty"`
+	Duration           string    `json:"duration,omitempty"`
+	MinTraceDuration   int64     `json:"min_trace_duration,omitempty"`
+	MaxTraceDuration   int64     `json:"max_trace_duration,omitempty"`
+	TraceState         string    `json:"trace_state,omitempty"`
+	QueryOrder         string    `json:"query_order,omitempty"`
+	PageSize           int       `json:"page_size,omitempty"`
+	PageNum            int       `json:"page_num,omitempty"`
+	View               string    `json:"view,omitempty"`
+	SlowTraceThreshold int64     `json:"slow_trace_threshold,omitempty"`
+	Tags               []SpanTag `json:"tags,omitempty"`
+	Cold               bool      `json:"cold,omitempty"`
 }
 
-func searchTrace(ctx context.Context, req TraceRequest) (*api.Trace, error) {
+// 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"`
+}
+
+// TracesSummary provides a high-level overview of multiple traces
+type TracesSummary struct {
+	TotalTraces  int                 `json:"total_traces"`
+	SuccessCount int                 `json:"success_count"`
+	ErrorCount   int                 `json:"error_count"`
+	Services     []string            `json:"services"`
+	Endpoints    []string            `json:"endpoints"`
+	AvgDuration  float64             `json:"avg_duration_ms"`
+	MinDuration  int64               `json:"min_duration_ms"`
+	MaxDuration  int64               `json:"max_duration_ms"`
+	TimeRange    TimeRange           `json:"time_range"`
+	ErrorTraces  []BasicTraceSummary `json:"error_traces,omitempty"`
+	SlowTraces   []BasicTraceSummary `json:"slow_traces,omitempty"`
+}
+
+// BasicTraceSummary provides essential information about a single trace
+type BasicTraceSummary struct {
+	TraceID      string `json:"trace_id"`
+	ServiceName  string `json:"service_name"`
+	EndpointName string `json:"endpoint_name"`
+	StartTime    int64  `json:"start_time_ms"`
+	Duration     int64  `json:"duration_ms"`
+	IsError      bool   `json:"is_error"`
+	SpanCount    int    `json:"span_count"`
+}
+
+// TimeRange represents the time span of the traces
+type TimeRange struct {
+	StartTime int64 `json:"start_time_ms"`
+	EndTime   int64 `json:"end_time_ms"`
+	Duration  int64 `json:"duration_ms"`
+}
+
+// createBasicTraceSummary creates a BasicTraceSummary from trace item data
+func createBasicTraceSummary(traceItem *api.BasicTrace, startTimeMs, duration int64, isError bool) BasicTraceSummary {
+	return BasicTraceSummary{
+		TraceID:      traceItem.TraceIds[0], // Use first trace ID
+		ServiceName:  traceItem.SegmentID,   // Use segment ID as service name
+		EndpointName: strings.Join(traceItem.EndpointNames, ", "),
+		StartTime:    startTimeMs,
+		Duration:     duration,
+		IsError:      isError,
+		SpanCount:    0, // BasicTrace doesn't have span count
+	}
+}
+
+// processTraceResult handles the common logic for processing trace results
+func processTraceResult(traceID string, traceData *api.Trace, view string) (*mcp.CallToolResult, error) {
+	if len(traceData.Spans) == 0 {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrTraceNotFound, traceID)), nil
+	}
+
+	var result interface{}
+	switch view {
+	case ViewSummary:
+		result = generateTraceSummary(traceID, traceData)
+	case ViewErrorsOnly:
+		result = filterErrorSpans(traceData)
+	case ViewFull:
+		result = traceData
+	default:
+		return mcp.NewToolResultError(fmt.Sprintf(ErrInvalidView, view, ViewFull, ViewSummary, ViewErrorsOnly)), nil
+	}
+
+	jsonBytes, err := json.Marshal(result)
+	if err != nil {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrMarshalFailed, err)), nil
+	}
+	return mcp.NewToolResultText(string(jsonBytes)), nil
+}
+
+// validateTraceRequest validates trace request parameters
+func validateTraceRequest(req TraceRequest) error {
+	if req.TraceID == "" {
+		return errors.New(ErrMissingTraceID)
+	}
+	return nil
+}
+
+// validateColdTraceRequest validates cold trace request parameters
+func validateColdTraceRequest(req ColdTraceRequest) error {
+	if req.TraceID == "" {
+		return errors.New(ErrMissingTraceID)
+	}
+	if req.Duration == "" {
+		return errors.New(ErrMissingDuration)
+	}
+	return nil
+}
+
+// searchTrace fetches the trace data and processes it based on the requested view
+func searchTrace(ctx context.Context, req *TraceRequest) (*mcp.CallToolResult, error) {
+	if err := validateTraceRequest(*req); err != nil {
+		return mcp.NewToolResultError(err.Error()), nil
+	}
+	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 mcp.NewToolResultError(fmt.Sprintf(ErrFailedToQueryTrace, req.TraceID, err)), nil
 	}
-	return &traces, nil
+	traceData := &traces
+
+	return processTraceResult(req.TraceID, traceData, req.View)
 }
 
-func AddTraceTools(mcp *server.MCPServer) {
-	SearchTraceTool.Register(mcp)
+// searchColdTrace fetches the trace data from cold storage and processes it based on the requested view
+func searchColdTrace(ctx context.Context, req *ColdTraceRequest) (*mcp.CallToolResult, error) {
+	if err := validateColdTraceRequest(*req); err != nil {
+		return mcp.NewToolResultError(err.Error()), nil
+	}
+	if req.View == "" {
+		req.View = ViewFull // Set default value
+	}
+
+	// Parse duration string to api.Duration
+	duration := ParseDuration(req.Duration, true)
+
+	traces, err := trace.ColdTrace(ctx, duration, req.TraceID)
+	if err != nil {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrFailedToQueryColdTrace, req.TraceID, err)), nil
+	}
+	traceData := &traces
+
+	return processTraceResult(req.TraceID, traceData, req.View)
+}
+
+// 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
+}
+
+// validateTracesQueryRequest validates traces query request parameters
+func validateTracesQueryRequest(req *TracesQueryRequest) error {
+	// At least one filter should be provided for meaningful results
+	if req.ServiceID == "" && req.ServiceInstanceID == "" && req.TraceID == "" &&
+		req.EndpointID == "" && req.Duration == "" && req.MinTraceDuration == 0 &&
+		req.MaxTraceDuration == 0 {
+		return errors.New(ErrNoFilterCondition)
+	}
+
+	// Validate duration range
+	if req.MinTraceDuration > 0 && req.MaxTraceDuration > 0 && req.MinTraceDuration > req.MaxTraceDuration {
+		return fmt.Errorf(ErrInvalidDurationRange, req.MinTraceDuration, req.MaxTraceDuration)
+	}
+
+	// Validate pagination
+	if req.PageSize < 0 {
+		return errors.New(ErrNegativePageSize)
+	}
+	if req.PageNum < 0 {
+		return errors.New(ErrNegativePageNum)
+	}
+
+	return nil
+}
+
+// setBasicFields sets basic fields in the query condition
+func setBasicFields(req *TracesQueryRequest, condition *api.TraceQueryCondition) {
+	if req.ServiceID != "" {
+		condition.ServiceID = &req.ServiceID
+	}
+	if req.ServiceInstanceID != "" {
+		condition.ServiceInstanceID = &req.ServiceInstanceID
+	}
+	if req.TraceID != "" {
+		condition.TraceID = &req.TraceID
+	}
+	if req.EndpointID != "" {
+		condition.EndpointID = &req.EndpointID
+	}
+	if req.MinTraceDuration > 0 {
+		minDuration := int(req.MinTraceDuration)
+		condition.MinTraceDuration = &minDuration
+	}
+	if req.MaxTraceDuration > 0 {
+		maxDuration := int(req.MaxTraceDuration)
+		condition.MaxTraceDuration = &maxDuration
+	}
+}
+
+// setTags sets tags in the query condition
+func setTags(req *TracesQueryRequest, condition *api.TraceQueryCondition) {
+	if len(req.Tags) > 0 {
+		apiTags := make([]*api.SpanTag, len(req.Tags))
+		for i, tag := range req.Tags {
+			apiTags[i] = &api.SpanTag{
+				Key:   tag.Key,
+				Value: &tag.Value,
+			}
+		}
+		condition.Tags = apiTags
+	}
+}
+
+// setDuration sets duration in the query condition
+func setDuration(req *TracesQueryRequest, condition *api.TraceQueryCondition) {
+	if req.Duration != "" {
+		duration := ParseDuration(req.Duration, req.Cold)
+		condition.QueryDuration = &duration
+	} else if req.TraceID == "" {
+		// If no duration and no traceId provided, set default duration (last 1 hour)
+		// SkyWalking OAP requires either queryDuration or traceId
+		defaultDuration := ParseDuration(DefaultTraceDuration, req.Cold)
+		condition.QueryDuration = &defaultDuration
+	}
+}
+
+// setTraceState sets trace state in the query condition
+func setTraceState(req *TracesQueryRequest, condition *api.TraceQueryCondition) error {
+	switch req.TraceState {
+	case TraceStateSuccess:
+		condition.TraceState = api.TraceStateSuccess
+	case TraceStateError:
+		condition.TraceState = api.TraceStateError
+	case TraceStateAll, "":
+		condition.TraceState = api.TraceStateAll
+	default:
+		return fmt.Errorf(ErrInvalidTraceState,
+			req.TraceState, TraceStateSuccess, TraceStateError, TraceStateAll)
+	}
+	return nil
+}
+
+// setQueryOrder sets query order in the query condition
+func setQueryOrder(req *TracesQueryRequest, condition *api.TraceQueryCondition) error {
+	switch req.QueryOrder {
+	case QueryOrderStartTime:
+		condition.QueryOrder = api.QueryOrderByStartTime
+	case QueryOrderDuration:
+		condition.QueryOrder = api.QueryOrderByDuration
+	case QueryOrderStartTimeDesc, "":

Review Comment:
   The `start_time_desc` option is mapped to the same ascending order constant as `start_time`. If descending order is intended, update this mapping to the appropriate descending enum or remove the redundant case.
   ```suggestion
   	case QueryOrderStartTimeDesc:
   		condition.QueryOrder = api.QueryOrderByStartTimeDesc
   	case "":
   ```



##########
internal/tools/common.go:
##########
@@ -0,0 +1,170 @@
+// 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 tools
+
+import (
+	"fmt"
+	"time"
+
+	api "skywalking.apache.org/repo/goapi/query"
+)
+
+// Default values
+const (
+	DefaultPageSize = 15
+	DefaultPageNum  = 1
+	DefaultStep     = "MINUTE"
+	DefaultDuration = 30 // minutes
+)
+
+// Error messages
+const (
+	ErrMissingDuration = "missing required parameter: duration"
+	ErrMarshalFailed   = "failed to marshal result: %v"
+)

Review Comment:
   The time format for minute granularity omits a colon between hours and minutes. It should likely be "2006-01-02 15:04" for readability and consistency.



##########
internal/tools/trace.go:
##########
@@ -19,35 +19,843 @@ package tools
 
 import (
 	"context"
+	"encoding/json"
+	"errors"
 	"fmt"
+	"sort"
+	"strings"
+	"time"
 
-	"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"
+)
+
+// AddTraceTools registers trace-related tools with the MCP server
+func AddTraceTools(mcp *server.MCPServer) {
+	SearchTraceTool.Register(mcp)
+	ColdTraceTool.Register(mcp)
+	TracesQueryTool.Register(mcp)
+}
+
+// View constants
+const (
+	ViewFull       = "full"
+	ViewSummary    = "summary"
+	ViewErrorsOnly = "errors_only"
+)
+
+// Query order constants
+const (
+	QueryOrderStartTime     = "start_time"
+	QueryOrderDuration      = "duration"
+	QueryOrderStartTimeDesc = "start_time_desc"
+	QueryOrderDurationDesc  = "duration_desc"
+)
+
+// Trace state constants
+const (
+	TraceStateSuccess = "success"
+	TraceStateError   = "error"
+	TraceStateAll     = "all"
+)
+
+// Error constants
+const (
+	ErrMissingTraceID         = "missing required parameter: trace_id"
+	ErrFailedToQueryTrace     = "failed to query trace '%s': %v"
+	ErrFailedToQueryColdTrace = "failed to query cold trace '%s': %v"
+	ErrFailedToQueryTraces    = "failed to query traces: %v"
+	ErrNoFilterCondition      = "at least one filter condition must be provided"
+	ErrInvalidDurationRange   = "invalid duration range: min_duration (%d) > max_duration (%d)"
+	ErrNegativePageSize       = "page_size cannot be negative"
+	ErrNegativePageNum        = "page_num cannot be negative"
+	ErrInvalidTraceState      = "invalid trace_state '%s', available states: %s, %s, %s"
+	ErrInvalidQueryOrder      = "invalid query_order '%s', available orders: %s, %s, %s, %s"
+	ErrTraceNotFound          = "trace with ID '%s' not found"
+	ErrInvalidView            = "invalid view '%s', available views: %s, %s, %s"
+	ErrNoTracesFound          = "no traces found matching the query criteria"
+)
+
+const TimeFormatFull = "2006-01-02 15:04:05"
+
+// Trace-specific constants
+const (
+	DefaultTracePageSize = 20
+	DefaultTraceDuration = "1h"
 )
 
+// TraceRequest defines the parameters for the trace tool
 type TraceRequest struct {
 	TraceID string `json:"trace_id"`
+	View    string `json:"view,omitempty"`
+}
+
+// ColdTraceRequest defines the parameters for the cold trace tool
+type ColdTraceRequest struct {
+	TraceID  string `json:"trace_id"`
+	Duration string `json:"duration"`
+	View     string `json:"view,omitempty"`
+}
+
+// SpanTag represents a span tag for filtering traces
+type SpanTag struct {
+	Key   string `json:"key"`
+	Value string `json:"value"`
+}
+
+// TracesQueryRequest defines the parameters for the traces query tool
+type TracesQueryRequest struct {
+	ServiceID          string    `json:"service_id,omitempty"`
+	ServiceInstanceID  string    `json:"service_instance_id,omitempty"`
+	TraceID            string    `json:"trace_id,omitempty"`
+	EndpointID         string    `json:"endpoint_id,omitempty"`
+	Duration           string    `json:"duration,omitempty"`
+	MinTraceDuration   int64     `json:"min_trace_duration,omitempty"`
+	MaxTraceDuration   int64     `json:"max_trace_duration,omitempty"`
+	TraceState         string    `json:"trace_state,omitempty"`
+	QueryOrder         string    `json:"query_order,omitempty"`
+	PageSize           int       `json:"page_size,omitempty"`
+	PageNum            int       `json:"page_num,omitempty"`
+	View               string    `json:"view,omitempty"`
+	SlowTraceThreshold int64     `json:"slow_trace_threshold,omitempty"`
+	Tags               []SpanTag `json:"tags,omitempty"`
+	Cold               bool      `json:"cold,omitempty"`
 }
 
-func searchTrace(ctx context.Context, req TraceRequest) (*api.Trace, error) {
+// 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"`
+}
+
+// TracesSummary provides a high-level overview of multiple traces
+type TracesSummary struct {
+	TotalTraces  int                 `json:"total_traces"`
+	SuccessCount int                 `json:"success_count"`
+	ErrorCount   int                 `json:"error_count"`
+	Services     []string            `json:"services"`
+	Endpoints    []string            `json:"endpoints"`
+	AvgDuration  float64             `json:"avg_duration_ms"`
+	MinDuration  int64               `json:"min_duration_ms"`
+	MaxDuration  int64               `json:"max_duration_ms"`
+	TimeRange    TimeRange           `json:"time_range"`
+	ErrorTraces  []BasicTraceSummary `json:"error_traces,omitempty"`
+	SlowTraces   []BasicTraceSummary `json:"slow_traces,omitempty"`
+}
+
+// BasicTraceSummary provides essential information about a single trace
+type BasicTraceSummary struct {
+	TraceID      string `json:"trace_id"`
+	ServiceName  string `json:"service_name"`
+	EndpointName string `json:"endpoint_name"`
+	StartTime    int64  `json:"start_time_ms"`
+	Duration     int64  `json:"duration_ms"`
+	IsError      bool   `json:"is_error"`
+	SpanCount    int    `json:"span_count"`
+}
+
+// TimeRange represents the time span of the traces
+type TimeRange struct {
+	StartTime int64 `json:"start_time_ms"`
+	EndTime   int64 `json:"end_time_ms"`
+	Duration  int64 `json:"duration_ms"`
+}
+
+// createBasicTraceSummary creates a BasicTraceSummary from trace item data
+func createBasicTraceSummary(traceItem *api.BasicTrace, startTimeMs, duration int64, isError bool) BasicTraceSummary {
+	return BasicTraceSummary{
+		TraceID:      traceItem.TraceIds[0], // Use first trace ID
+		ServiceName:  traceItem.SegmentID,   // Use segment ID as service name
+		EndpointName: strings.Join(traceItem.EndpointNames, ", "),
+		StartTime:    startTimeMs,
+		Duration:     duration,
+		IsError:      isError,
+		SpanCount:    0, // BasicTrace doesn't have span count
+	}
+}
+
+// processTraceResult handles the common logic for processing trace results
+func processTraceResult(traceID string, traceData *api.Trace, view string) (*mcp.CallToolResult, error) {
+	if len(traceData.Spans) == 0 {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrTraceNotFound, traceID)), nil
+	}
+
+	var result interface{}
+	switch view {
+	case ViewSummary:
+		result = generateTraceSummary(traceID, traceData)
+	case ViewErrorsOnly:
+		result = filterErrorSpans(traceData)
+	case ViewFull:
+		result = traceData
+	default:
+		return mcp.NewToolResultError(fmt.Sprintf(ErrInvalidView, view, ViewFull, ViewSummary, ViewErrorsOnly)), nil
+	}
+
+	jsonBytes, err := json.Marshal(result)
+	if err != nil {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrMarshalFailed, err)), nil
+	}
+	return mcp.NewToolResultText(string(jsonBytes)), nil
+}
+
+// validateTraceRequest validates trace request parameters
+func validateTraceRequest(req TraceRequest) error {
+	if req.TraceID == "" {
+		return errors.New(ErrMissingTraceID)
+	}
+	return nil
+}
+
+// validateColdTraceRequest validates cold trace request parameters
+func validateColdTraceRequest(req ColdTraceRequest) error {
+	if req.TraceID == "" {
+		return errors.New(ErrMissingTraceID)
+	}
+	if req.Duration == "" {
+		return errors.New(ErrMissingDuration)
+	}
+	return nil
+}
+
+// searchTrace fetches the trace data and processes it based on the requested view
+func searchTrace(ctx context.Context, req *TraceRequest) (*mcp.CallToolResult, error) {
+	if err := validateTraceRequest(*req); err != nil {
+		return mcp.NewToolResultError(err.Error()), nil
+	}
+	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 mcp.NewToolResultError(fmt.Sprintf(ErrFailedToQueryTrace, req.TraceID, err)), nil
 	}
-	return &traces, nil
+	traceData := &traces
+
+	return processTraceResult(req.TraceID, traceData, req.View)
 }
 
-func AddTraceTools(mcp *server.MCPServer) {
-	SearchTraceTool.Register(mcp)
+// searchColdTrace fetches the trace data from cold storage and processes it based on the requested view
+func searchColdTrace(ctx context.Context, req *ColdTraceRequest) (*mcp.CallToolResult, error) {
+	if err := validateColdTraceRequest(*req); err != nil {
+		return mcp.NewToolResultError(err.Error()), nil
+	}
+	if req.View == "" {
+		req.View = ViewFull // Set default value
+	}
+
+	// Parse duration string to api.Duration
+	duration := ParseDuration(req.Duration, true)
+
+	traces, err := trace.ColdTrace(ctx, duration, req.TraceID)
+	if err != nil {
+		return mcp.NewToolResultError(fmt.Sprintf(ErrFailedToQueryColdTrace, req.TraceID, err)), nil
+	}
+	traceData := &traces
+
+	return processTraceResult(req.TraceID, traceData, req.View)
+}
+
+// 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)
+	}

Review Comment:
   Appending services in map iteration order leads to nondeterministic slices. Sort the `summary.Services` slice before returning to guarantee consistent output.
   ```suggestion
   	}
   	sort.Strings(summary.Services) // Ensure deterministic order
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org