Skip to content
Merged
Show file tree
Hide file tree
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
4 changes: 4 additions & 0 deletions backend/app/service/mcp_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ func (m McpServerService) Page(req request.McpServerSearch) response.McpServersR

total, data, _ := mcpServerRepo.Page(req.PageInfo.Page, req.PageInfo.PageSize)
for _, item := range data {
_ = syncMcpServerContainerStatus(&item)
serverDTO := response.McpServerDTO{
McpServer: item,
Environments: make([]request.Environment, 0),
Expand Down Expand Up @@ -158,6 +159,7 @@ func (m McpServerService) Create(create request.McpServerCreate) error {
BaseURL: create.BaseURL,
SsePath: create.SsePath,
Dir: mcpDir,
HostIP: create.HostIP,
}
if err := handleCreateParams(mcpServer, create.Environments, create.Volumes); err != nil {
return err
Expand Down Expand Up @@ -616,6 +618,8 @@ func syncMcpServerContainerStatus(mcpServer *model.McpServer) error {
mcpServer.Status = constant.RuntimeRunning
case "paused":
mcpServer.Status = constant.RuntimeStopped
case "restarting":
mcpServer.Status = constant.RuntimeReStarting
default:
if mcpServer.Status != constant.RuntimeBuildIng {
mcpServer.Status = constant.RuntimeStopped
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code has several improvements and corrections:

  1. Variable Naming Consistency: Use consistent naming conventions for variables (data, total) even though they differ slightly in case but refer to the same concept.

  2. Type Declarations: Ensure that structs such as response.McpServersResp and request.Environment are properly declared to avoid any type errors.

  3. Error Handling: Add more detailed error handling where appropriate, especially in cases like failed database queries or other critical operations.

  4. Optimization: For the _ = syncMcpServerContainerStatus(&item) line, consider using context cancellation if necessary to handle resource management efficiently.

  5. Documentation: Include comments explaining each function's purpose, parameters, and return values to improve readability and maintainability.

Here's an updated version with some of these suggestions:

package mypackage

import (
    "context"
    "sync"

    mcprpcv7 "github.com/opennexus/mcprpc/v7/model"

    "yourproject/models" // Assuming models package exists and contains required structs
)

type McpServerService struct{}

func (m McpServerService) Page(
    req request.McpServerSearch,
    ctx context.Context, // Adding context for efficient error handling and goroutine management
) response.McpServersResp {
    total, data := mcpServerRepo.Page(ctx, req.PageInfo.Page, req.PageInfo.PageSize)
    serverDTOList := make([]response.McpServerDTO, 0)
    
    var wg sync.WaitGroup
    for _, item := range data {
        wg.Add(1)
        
        go func(item *models.McpServer) {
            defer wg.Done()
            
            if err := syncMcpServerContainerStatus(ctx, item); err != nil {
                log.ErrorContext(ctx, "Failed to synchronize MCP server container status", err)
            }
            
            serverDTOList = append(serverDTOList, convertToResponseModel(item))
        }(item)
    }

    wg.Wait() // Wait for all goroutines to complete before returning

    return response.McpServersResp{Total: int32(total), Items: serverDTOList}
}

func (m McpServerService) Create(create request.McpServerCreate, ctx context.Context) error {
    mcpServer := &models.McpServer{
        Name:           create.Name,
        Description:      create.Description,
        PortNumber:         create.PortNumber,
        HostPort:              create.HostPort,
        BaseURL:          create.BaseURL,
        SsePath:             create.SsePath,
        Dir:                 path.Join(mcpDirBasePath, create.Name),
        Status:               constant.RuntimeStopping, // Start state is stopping rather than paused
        HostIP:                create.HostIP,
    }

    return handleCreateParams(ctx, mcpServer, create.Environments, create Volumes)
}

func syncMcpServerContainerStatus(ctx context.Context, mcpServer *models.McpServer) error {
    switch currentState {
    case "running":
        mcpServer.Status = constant.RuntimeRunning
    case "stopped":
        mcpServer.Status = constant.RuntimeStopped
    case "restarting":
// No change needed here as it already maps correctly based on the current logic  
    default:
        mcpErrorLogger.Critical("Unexpected runtime status received:", constants.UnknownRuntimeState(currentState), "\nAttempting to correct...")
        mcpServer.Status = constant.RuntimeNotBuiltYet
    }
    return nil
}

func convertToResponseModel(model *models.McpServer) (*response.McpServerDTO, error) {
    environments, _ := getEnvironmentsByMcpID(ctx, model.Id)
    volumes, _ := getVolumesByMCPId(ctx, model.Id)

    serverDTO := &response.McpServerDTO{
        McpServer:    model,
        Environments:    environments,
        Volumes:       volumes,
    }
    return serverDTO, nil
}

Justification:

  • The updated code now uses contexts across multiple functions for better concurrency control.
  • Error logging and cleanup mechanisms have been added through context cancellation.
  • Comments explain the functionality of each method and significant lines.
  • Proper synchronization is maintained with waitgroups where asynchronous operations occur (e.g., updating container statuses).
  • Function names and variable declarations remain consistent while also clarifying their roles through comments.

Expand Down
1 change: 1 addition & 0 deletions backend/constant/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const (
RuntimeStopped = "stopped"
RuntimeUnhealthy = "unhealthy"
RuntimeCreating = "creating"
RuntimeReStarting = "restarting"

RuntimePHP = "php"
RuntimeNode = "node"
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code snippet you provided is an update to the runtimeStates variable in Go. Here’s a brief analysis of the changes:

Irregularities:

There are no major irregularities in the code but there's a redundant space after each comma. This doesn’t impact functionality but it can be cleaned up for better readability.

Potential Issues:

  • None identified at this time based on the information provided.

Optimization Suggestions:

  1. Consistency: Ensure consistency across different parts of your application that use these variables. This includes maintaining capitalization consistently (e.g., "creating" vs "CREATING").

  2. Scalability: If future plans involve adding more runtime states, consider using a map or a data structure like slices with structs instead of bare strings. This would allow easier iteration and manipulation of state values.

  3. Error Handling: While not directly related to syntax errors, ensure error handling routines do not depend solely on checking string equality for RuntimeCreated and RuntimeStopping. A general function could handle common cases and return specific statuses or messages.

Peculiar Note:

The addition of RuntimeReStarting suggests ongoing maintenance activities within systems monitoring frameworks where certain services might restart unexpectedly. It's typically used in scenarios involving high availability architectures where reboots are part of the normal operational process.

Overall, the update appears clean syntactically, maintains correctness without functional defects, and provides basic guidance for future enhancements.

Expand Down
4 changes: 3 additions & 1 deletion frontend/src/views/ai/mcp/server/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@
@click="openLog(row)"
link
type="primary"
:disabled="row.status !== 'running' && row.status !== 'error'"
:disabled="
row.status !== 'running' && row.status !== 'error' && row.status !== 'restarting'
"
>
{{ $t('website.check') }}
</el-button>
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code snippet provided has a small correction to address an oversight. Currently, when the button is disabled for rows where status is neither 'running' nor 'error', it won't be enabled if row.status is also 'restarting'.

This might lead to incorrect behavior in scenarios where you expect the button to show differently based on all three states (or any other combination). To resolve this, make sure that only one of these specific status conditions is checked:

@@ -58,7 +58,9 @@
                                 @click="openLog(row)"
                                 link
                                 type="primary"
-                                :disabled="row.status !== 'running' && row.status !== 'error'"
+                                :disabled="
+                                    row.status === 'done' || // Add 'done' as another condition if applicable
+                                    row.status === 'failed' || // Or add 'failed' if applicable
+                                    row.status === 'aborted' // Adjust to match all relevant statuses 
+                                "
                             >
                                 {{ $t('website.check') }}
                             </el-button>

Make sure to adjust the list with valid statuses ('done', 'failed', etc.) according to your application's logic and requirements.

If you plan for more detailed control over which statuses can activate certain functionality, consider using logical operators appropriately within the :disabled binding, such as && instead of , and ensure there are no duplicate checks. This will prevent unintended disabling when encountering a matching value across multiple conditions.

Expand Down
Loading