-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
389 lines (326 loc) · 10.6 KB
/
errors.go
File metadata and controls
389 lines (326 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package mcpp
import (
"errors"
"fmt"
"strings"
"sync"
)
// ErrorType represents different categories of errors that can occur in the MCPP library.
//
// ErrorType provides a standardized way to categorize errors, enabling applications
// to handle different types of failures appropriately. Some error types are considered
// retryable (like connection errors) while others are not (like validation errors).
type ErrorType string
const (
// ErrorTypeConnection indicates network or connection-related errors that may be transient
ErrorTypeConnection ErrorType = "connection"
// ErrorTypeProtocol indicates MCP protocol-related errors such as invalid messages
ErrorTypeProtocol ErrorType = "protocol"
// ErrorTypeConfiguration indicates configuration-related errors such as invalid settings
ErrorTypeConfiguration ErrorType = "configuration"
// ErrorTypeTimeout indicates timeout-related errors that may be retryable
ErrorTypeTimeout ErrorType = "timeout"
// ErrorTypeValidation indicates input validation errors that are not retryable
ErrorTypeValidation ErrorType = "validation"
// ErrorTypeSession indicates session management errors such as session creation failures
ErrorTypeSession ErrorType = "session"
// ErrorTypeTool indicates tool execution errors from the MCP server
ErrorTypeTool ErrorType = "tool"
)
// MCPError represents a structured error with context and categorization.
//
// MCPError provides detailed error information including error type classification,
// specific error codes, human-readable messages, underlying causes, and contextual
// information. This enables better error handling, logging, and debugging.
//
// Example usage:
//
// err := mcpp.NewConnectionError("CONN_FAILED", "Failed to connect to server", cause)
// err.WithContext("server", "my_server").WithContext("attempt", 3)
//
// if mcpp.IsErrorType(err, mcpp.ErrorTypeConnection) {
// // Handle connection error specifically
// }
type MCPError struct {
// Type categorizes the error for handling purposes
Type ErrorType `json:"type"`
// Code provides a specific error identifier for programmatic handling
Code string `json:"code"`
// Message contains a human-readable error description
Message string `json:"message"`
// Cause is the underlying error that caused this error (not serialized)
Cause error `json:"-"`
// Context contains additional information about the error circumstances
Context map[string]any `json:"context,omitempty"`
}
// Error implements the error interface
func (e *MCPError) Error() string {
var parts []string
parts = append(parts, fmt.Sprintf("[%s:%s]", e.Type, e.Code))
parts = append(parts, e.Message)
if e.Cause != nil {
parts = append(parts, fmt.Sprintf("caused by: %v", e.Cause))
}
if len(e.Context) > 0 {
var contextParts []string
for k, v := range e.Context {
contextParts = append(contextParts, fmt.Sprintf("%s=%v", k, v))
}
parts = append(parts, fmt.Sprintf("context: {%s}", strings.Join(contextParts, ", ")))
}
return strings.Join(parts, " ")
}
// Unwrap returns the underlying cause error
func (e *MCPError) Unwrap() error {
return e.Cause
}
// Is checks if the error matches the target error type
func (e *MCPError) Is(target error) bool {
var mcpErr *MCPError
if errors.As(target, &mcpErr) {
return e.Type == mcpErr.Type && e.Code == mcpErr.Code
}
return false
}
// WithContext adds context information to the error
func (e *MCPError) WithContext(key string, value any) *MCPError {
if e.Context == nil {
e.Context = make(map[string]any)
}
e.Context[key] = value
return e
}
// NewMCPError creates a new MCPError with the specified parameters.
//
// This is the primary constructor for creating structured errors in the MCPP library.
// It allows specifying all error components including type, code, message, underlying
// cause, and contextual information.
//
// Parameters:
// - errorType: The category of error (connection, protocol, etc.)
// - code: A specific error code for programmatic handling
// - message: Human-readable error description
// - cause: The underlying error that caused this error (can be nil)
// - context: Additional contextual information (can be nil)
//
// Returns a new MCPError instance.
func NewMCPError(errorType ErrorType, code, message string, cause error, context map[string]any) *MCPError {
return &MCPError{
Type: errorType,
Code: code,
Message: message,
Cause: cause,
Context: context,
}
}
// IsRetryable checks if an error type is generally retryable
func (t ErrorType) IsRetryable() bool {
switch t {
case ErrorTypeConnection, ErrorTypeTimeout:
return true
case ErrorTypeProtocol, ErrorTypeConfiguration, ErrorTypeValidation:
return false
default:
return false
}
}
// Common error constructors for frequently used error scenarios
// NewConnectionError creates a connection-related error.
//
// This is a convenience constructor for creating connection errors, which are
// typically retryable. Connection errors occur when there are issues establishing
// or maintaining connections to MCP servers.
//
// Parameters:
// - code: Specific error code (e.g., "CONN_FAILED", "CONN_TIMEOUT")
// - message: Human-readable error description
// - cause: The underlying error that caused the connection failure
//
// Returns a new MCPError with ErrorTypeConnection.
func NewConnectionError(code, message string, cause error) *MCPError {
return NewMCPError(ErrorTypeConnection, code, message, cause, nil)
}
// NewProtocolError creates a protocol-related error
func NewProtocolError(code, message string, cause error) *MCPError {
return NewMCPError(ErrorTypeProtocol, code, message, cause, nil)
}
// NewConfigurationError creates a configuration-related error
func NewConfigurationError(code, message string, cause error) *MCPError {
return NewMCPError(ErrorTypeConfiguration, code, message, cause, nil)
}
// NewTimeoutError creates a timeout-related error
func NewTimeoutError(code, message string, cause error) *MCPError {
return NewMCPError(ErrorTypeTimeout, code, message, cause, nil)
}
// NewValidationError creates a validation-related error
func NewValidationError(code, message string, cause error) *MCPError {
return NewMCPError(ErrorTypeValidation, code, message, cause, nil)
}
// NewSessionError creates a session-related error
func NewSessionError(code, message string, cause error) *MCPError {
return NewMCPError(ErrorTypeSession, code, message, cause, nil)
}
// NewToolError creates a tool-related error
func NewToolError(code, message string, cause error) *MCPError {
return NewMCPError(ErrorTypeTool, code, message, cause, nil)
}
// WrapError wraps an existing error as an MCPError if it isn't already one
func WrapError(err error, errorType ErrorType, code, message string) *MCPError {
if err == nil {
return nil
}
var mcpErr *MCPError
if errors.As(err, &mcpErr) {
return mcpErr
}
return NewMCPError(errorType, code, message, err, nil)
}
// IsErrorType checks if an error is of a specific type.
//
// This function provides a convenient way to check if an error (which may be
// wrapped or part of an error chain) is of a specific ErrorType. It works
// with both MCPError instances and wrapped errors.
//
// Parameters:
// - err: The error to check
// - errorType: The error type to check for
//
// Returns true if the error is of the specified type, false otherwise.
func IsErrorType(err error, errorType ErrorType) bool {
var mcpErr *MCPError
if errors.As(err, &mcpErr) {
return mcpErr.Type == errorType
}
return false
}
// GetErrorCode extracts the error code from an MCPError, or returns empty string
func GetErrorCode(err error) string {
var mcpErr *MCPError
if errors.As(err, &mcpErr) {
return mcpErr.Code
}
return ""
}
// GetErrorContext extracts the context from an MCPError, or returns nil
func GetErrorContext(err error) map[string]any {
var mcpErr *MCPError
if errors.As(err, &mcpErr) {
return mcpErr.Context
}
return nil
}
// ErrorChain represents a chain of related errors
type ErrorChain struct {
errors []error
}
// NewErrorChain creates a new error chain
func NewErrorChain() *ErrorChain {
return &ErrorChain{
errors: make([]error, 0),
}
}
// Add adds an error to the chain
func (ec *ErrorChain) Add(err error) *ErrorChain {
if err != nil {
ec.errors = append(ec.errors, err)
}
return ec
}
// HasErrors returns true if the chain contains any errors
func (ec *ErrorChain) HasErrors() bool {
return len(ec.errors) > 0
}
// Errors returns all errors in the chain
func (ec *ErrorChain) Errors() []error {
return ec.errors
}
// Error implements the error interface, combining all errors
func (ec *ErrorChain) Error() string {
if len(ec.errors) == 0 {
return ""
}
if len(ec.errors) == 1 {
return ec.errors[0].Error()
}
var parts []string
for i, err := range ec.errors {
parts = append(parts, fmt.Sprintf("%d: %v", i+1, err))
}
return fmt.Sprintf("multiple errors: [%s]", strings.Join(parts, "; "))
}
// First returns the first error in the chain, or nil if empty
func (ec *ErrorChain) First() error {
if len(ec.errors) == 0 {
return nil
}
return ec.errors[0]
}
// Last returns the last error in the chain, or nil if empty
func (ec *ErrorChain) Last() error {
if len(ec.errors) == 0 {
return nil
}
return ec.errors[len(ec.errors)-1]
}
// ErrorCollector helps collect multiple errors during operations
type ErrorCollector struct {
errors []error
mutex sync.RWMutex
}
// NewErrorCollector creates a new error collector
func NewErrorCollector() *ErrorCollector {
return &ErrorCollector{
errors: make([]error, 0),
}
}
// Add adds an error to the collector (thread-safe)
func (ec *ErrorCollector) Add(err error) {
if err == nil {
return
}
ec.mutex.Lock()
defer ec.mutex.Unlock()
ec.errors = append(ec.errors, err)
}
// HasErrors returns true if any errors were collected
func (ec *ErrorCollector) HasErrors() bool {
ec.mutex.RLock()
defer ec.mutex.RUnlock()
return len(ec.errors) > 0
}
// Count returns the number of errors collected
func (ec *ErrorCollector) Count() int {
ec.mutex.RLock()
defer ec.mutex.RUnlock()
return len(ec.errors)
}
// Errors returns all collected errors
func (ec *ErrorCollector) Errors() []error {
ec.mutex.RLock()
defer ec.mutex.RUnlock()
result := make([]error, len(ec.errors))
copy(result, ec.errors)
return result
}
// Error returns a combined error message, or nil if no errors
func (ec *ErrorCollector) Error() error {
ec.mutex.RLock()
defer ec.mutex.RUnlock()
if len(ec.errors) == 0 {
return nil
}
if len(ec.errors) == 1 {
return ec.errors[0]
}
chain := NewErrorChain()
for _, err := range ec.errors {
chain.Add(err)
}
return chain
}
// Clear removes all collected errors
func (ec *ErrorCollector) Clear() {
ec.mutex.Lock()
defer ec.mutex.Unlock()
ec.errors = ec.errors[:0]
}