Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,10 @@ type NotificationHandlerFunc func(ctx context.Context, notification mcp.JSONRPCN
type MCPServer struct {
// Separate mutexes for different resource types
resourcesMu sync.RWMutex
resourceMiddlewareMu sync.RWMutex
promptsMu sync.RWMutex
toolsMu sync.RWMutex
middlewareMu sync.RWMutex
toolMiddlewareMu sync.RWMutex
notificationHandlersMu sync.RWMutex
capabilitiesMu sync.RWMutex
toolFiltersMu sync.RWMutex
Expand Down Expand Up @@ -221,9 +222,9 @@ func WithToolHandlerMiddleware(
toolHandlerMiddleware ToolHandlerMiddleware,
) ServerOption {
return func(s *MCPServer) {
s.middlewareMu.Lock()
s.toolMiddlewareMu.Lock()
s.toolHandlerMiddlewares = append(s.toolHandlerMiddlewares, toolHandlerMiddleware)
s.middlewareMu.Unlock()
s.toolMiddlewareMu.Unlock()
}
}

Expand All @@ -233,9 +234,9 @@ func WithResourceHandlerMiddleware(
resourceHandlerMiddleware ResourceHandlerMiddleware,
) ServerOption {
return func(s *MCPServer) {
s.middlewareMu.Lock()
s.resourceMiddlewareMu.Lock()
s.resourceHandlerMiddlewares = append(s.resourceHandlerMiddlewares, resourceHandlerMiddleware)
s.middlewareMu.Unlock()
s.resourceMiddlewareMu.Unlock()
}
}

Expand Down Expand Up @@ -876,13 +877,13 @@ func (s *MCPServer) handleReadResource(
s.resourcesMu.RUnlock()

finalHandler := handler
s.middlewareMu.RLock()
s.resourceMiddlewareMu.RLock()
mw := s.resourceHandlerMiddlewares
// Apply middlewares in reverse order
for i := len(mw) - 1; i >= 0; i-- {
finalHandler = mw[i](finalHandler)
}
s.middlewareMu.RUnlock()
s.resourceMiddlewareMu.RUnlock()

contents, err := finalHandler(ctx, request)
if err != nil {
Expand Down Expand Up @@ -1138,14 +1139,14 @@ func (s *MCPServer) handleToolCall(

finalHandler := tool.Handler

s.middlewareMu.RLock()
s.toolMiddlewareMu.RLock()
mw := s.toolHandlerMiddlewares

// Apply middlewares in reverse order
for i := len(mw) - 1; i >= 0; i-- {
finalHandler = mw[i](finalHandler)
}
s.middlewareMu.RUnlock()
s.toolMiddlewareMu.RUnlock()

result, err := finalHandler(ctx, request)
if err != nil {
Expand Down