Skip to content

Feature/mcp capabilities sync - #245

Merged
iFurySt merged 6 commits into
AmoyLab:mainfrom
x22x22:feat/mcp-capabilities-sync
Sep 11, 2025
Merged

iFurySt merged 6 commits into
AmoyLab:mainfrom
x22x22:feat/mcp-capabilities-sync

Conversation

@x22x22

@x22x22 x22x22 commented Sep 9, 2025 •

Copy link
Copy Markdown
Contributor

Add MCP capability button on Gateway page, supporting automatic discovery of MCP service capabilities:

  • Frontend: Add MCP capability management interface on Gateway page
  • Backend: Implement GET /api/mcp/capabilities/:tenant/:name interface
  • Support viewing tools, resources, and prompts detail information
  • Support enabling and disabling discovered tool functions
  • Add fields compatible with all supported database types
  • Maintain original functionality integrity, without affecting existing MCP server management

Main functional modules:

  • MCP capability automatic discovery and caching mechanism
  • Capability detail display components (tools/resources/prompts)
  • Tool status management (enable/disable)
  • Capability statistics information interface
  • Permission control and multi-tenant support

Interface effects:

image image image

Summary by Sourcery

Add full-stack support for MCP capabilities synchronization and management, including a new API, caching and background refresh on the backend, and an interactive viewer UI in the gateway frontend that allows browsing, filtering, exporting, and toggling MCP service capabilities.

New Features:

  • Introduce MCP capability management API endpoint to fetch and display service capabilities
  • Add gateway UI button and dedicated page to view and export MCP tools, prompts, resources, and templates
  • Implement automatic discovery of MCP capabilities with background sync, caching, and TTL
  • Enable enabling/disabling of discovered tool functions from the UI

Enhancements:

  • Extend MCP config handlers to clear and refresh capability cache on create, update, delete, and sync events
  • Add new CapabilitiesInfo types and data models for tools, prompts, resources, and templates
  • Integrate background goroutine to periodically refresh capabilities across all MCP backends

…盖旧数据(stale-while-revalidate)\n- 新增能力查看页面与前端接口集成\n- 扩展MCP能力结构体定义与服务端聚合逻辑\n- 增强配置管理接口(列表/版本/激活)\n\nBREAKING CHANGE: 取消了通过访问页面才触发能力拉取的设计,改为后端后台任务定时刷新。

Signed-off-by: x22x22 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Sep 9, 2025 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

This PR adds end-to-end support for automatic discovery, caching, and management of MCP service capabilities by introducing a background refresher and cache with TTL, a new GET endpoint to retrieve capabilities, enhanced data models, and a full-featured frontend interface for viewing, searching, and exporting capabilities.

Sequence diagram for MCP capabilities discovery and caching

sequenceDiagram
    participant GatewayUser as actor Gateway User
    participant Frontend as Frontend (Gateway Page)
    participant Backend as Backend (API Server)
    participant MCP as MCP Handler
    participant MCPServer as MCP Service
    Note over Frontend,Backend: User requests capabilities for a server
    GatewayUser->>Frontend: Clicks 'View Capabilities' button
    Frontend->>Backend: GET /api/mcp/capabilities/:tenant/:name
    Backend->>MCP: HandleGetCapabilities(tenant, name)
    alt Cache hit and not expired
        MCP->>Backend: Return cached capabilities
    else Cache miss or expired
        MCP->>MCPServer: Fetch capabilities (tools, prompts, resources, templates)
        MCPServer-->>MCP: Capabilities data
        MCP->>MCP: Update cache
        MCP->>Backend: Return fresh capabilities
    end
    Backend->>Frontend: Capabilities data
    Frontend->>GatewayUser: Display capabilities viewer
Loading

ER diagram for new MCP capabilities data types

erDiagram
    MCPCapabilities {
      Tool[] tools
      Prompt[] prompts
      Resource[] resources
      ResourceTemplate[] resourceTemplates
    }
    Tool {
      string name
      string description
      ToolInputSchema inputSchema
      ToolAnnotations annotations
      bool enabled
      time lastSynced
    }
    Prompt {
      string name
      string description
      PromptArgumentSchema[] arguments
      time lastSynced
    }
    Resource {
      string uri
      string name
      string description
      string mimeType
      time lastSynced
    }
    ResourceTemplate {
      string uriTemplate
      string name
      string description
      string mimeType
      time lastSynced
    }
    MCPCapabilities ||--|{ Tool: "tools"
    MCPCapabilities ||--|{ Prompt: "prompts"
    MCPCapabilities ||--|{ Resource: "resources"
    MCPCapabilities ||--|{ ResourceTemplate: "resourceTemplates"
Loading

Class diagram for MCP capabilities cache and handler

classDiagram
    class MCP {
      +database.Database db
      +storage.Store store
      +notifier.Notifier notifier
      +zap.Logger logger
      +sync.Map capabilitiesCache
      +time.Duration refreshInterval
      +StartCapabilitiesSync(ctx)
      +HandleGetCapabilities(c)
      +refreshAllCapabilities(ctx)
      +refreshCapabilitiesForConfig(ctx, cfg)
      +updateCapabilitiesCache(cacheKey, data)
      +getCapabilitiesFromCache(ctx, cacheKey, cfg)
      +clearCapabilitiesCache(key)
    }
    class cachedCapabilities {
      +mcp.CapabilitiesInfo data
      +time.Time timestamp
      +time.Duration ttl
      +isExpired()
    }
    MCP "1" o-- "*" cachedCapabilities
    class CapabilitiesInfo {
      +Tool[] Tools
      +Prompt[] Prompts
      +Resource[] Resources
      +ResourceTemplate[] ResourceTemplates
      +time.Time LastSynced
      +ImplementationSchema ServerInfo
    }
    class Tool {
      +string Name
      +string Description
      +ToolInputSchema InputSchema
      +ToolAnnotations Annotations
      +bool Enabled
      +time.Time LastSynced
    }
    class Prompt {
      +string Name
      +string Description
      +PromptArgumentSchema[] Arguments
      +time.Time LastSynced
    }
    class Resource {
      +string Uri
      +string Name
      +string Description
      +string MimeType
      +time.Time LastSynced
    }
    class ResourceTemplate {
      +string UriTemplate
      +string Name
      +string Description
      +string MimeType
      +time.Time LastSynced
    }
    CapabilitiesInfo "1" o-- "*" Tool
    CapabilitiesInfo "1" o-- "*" Prompt
    CapabilitiesInfo "1" o-- "*" Resource
    CapabilitiesInfo "1" o-- "*" ResourceTemplate
Loading

File-Level Changes

Change Details Files
Backend support for automatic MCP capabilities discovery, caching and retrieval via API
  • Add sync.Map-based cache with TTL and methods to refresh all or individual server configurations
  • Launch background goroutine at startup to periodically fetch and update capabilities
  • Clear cache on server create/update/delete/sync and serve stale data on refresh failures
internal/apiserver/handler/mcp.go
cmd/apiserver/main.go
Implement GET /api/mcp/capabilities/:tenant/:name endpoint with permission checks
  • Add HandleGetCapabilities handler to load config, verify tenant permissions, and retrieve from cache or fetch fresh
  • Factor fetchCapabilities and getCapabilitiesFromCache to handle stale-on-failure policy and in-place cache updates
  • Register new route and trigger immediate fetch for newly created servers
internal/apiserver/handler/mcp.go
cmd/apiserver/main.go
Extend core data models for capabilities information
  • Define CapabilitiesInfo, MCPTool, MCPPrompt, MCPResource, and MCPResourceTemplate structs with LastSynced fields
  • Ensure JSON/YAML tags and add time.Time for metadata
pkg/mcp/server_types.go
Add TypeScript schemas and types for MCP capabilities on frontend
  • Create Zod schemas and TypeScript interfaces for prompts, resources, templates, and capabilities state
  • Include CapabilityItem, CapabilityType, and CapabilitiesState definitions
web/src/types/mcp.ts
Frontend UI for viewing and managing MCP capabilities
  • Build CapabilitiesViewer component with search, filtering, tabs, detail modal, and export functionality
  • Add CapabilitiesPage with routing, breadcrumbs, and back navigation
  • Insert capability view buttons in GatewayManager and update App.tsx routing
  • Implement getMCPServerCapabilities API call and handle loading/errors
web/src/pages/gateway/components/CapabilitiesViewer.tsx
web/src/pages/gateway/capabilities.tsx
web/src/pages/gateway/gateway-manager.tsx
web/src/App.tsx
web/src/services/api.ts
Add i18n support for capabilities operations
  • Introduce SuccessMCPCapabilities constant for successful capability fetch
  • Prepare translation entries for new UI labels and messages
internal/i18n/const.go

Possibly linked issues

  • openapi swagger 支持 #1: The PR adds core functionality for MCP capability discovery and management within the gateway, directly addressing the issue where an external tool fails to recognize gateway-forwarded MCP service capabilities.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • Extract the cache-key construction (tenant + ':' + name) into a single helper method to eliminate repeated string concatenations and potential typos.
  • Avoid using context.WithoutCancel for your background refresh goroutines so that they properly stop when the parent context is canceled instead of leaking.
  • Make the hardcoded refreshInterval (120s) and cache TTL (5m) configurable via flags or config rather than fixed constants to give operators more control.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Extract the cache-key construction (tenant + ':' + name) into a single helper method to eliminate repeated string concatenations and potential typos.
- Avoid using context.WithoutCancel for your background refresh goroutines so that they properly stop when the parent context is canceled instead of leaking.
- Make the hardcoded refreshInterval (120s) and cache TTL (5m) configurable via flags or config rather than fixed constants to give operators more control.

## Individual Comments

### Comment 1
<location> `internal/apiserver/handler/mcp.go:124` </location>
<code_context>
+// It will not overwrite existing cache with empty/failed data.
+func (h *MCP) refreshCapabilitiesForConfig(ctx context.Context, cfg *config.MCPConfig) {
+    cacheKey := cfg.Tenant + ":" + cfg.Name
+    capabilities, err := h.fetchCapabilities(ctx, cfg)
+    if err != nil {
+        // Do not remove previous cache on error
</code_context>

<issue_to_address>
fetchCapabilities does not implement resource/resourceTemplate fetching.

Add a clear error or warning for unimplemented resource/resourceTemplate fetching to prevent silent failures, or document this limitation for users.
</issue_to_address>

### Comment 2
<location> `web/src/pages/gateway/components/CapabilitiesViewer.tsx:756` </location>
<code_context>
+    selectedType: CapabilityType | 'all',
+    advancedFilters: typeof advancedSearch
+  ): MCPCapabilities => {
+    const filtered: MCPCapabilities = {};
+
+    const matchesSearch = (item: {name: string, description?: string}) => {
</code_context>

<issue_to_address>
filterCapabilities may return undefined arrays.

Initialize all capability type arrays to empty to prevent undefined values and simplify downstream usage.

Suggested implementation:

```typescript
    // Initialize all capability type arrays to empty arrays
    const filtered: MCPCapabilities = {
      source: [],
      sink: [],
      processor: [],
      // Add other capability types here if they exist in MCPCapabilities
    };

```

If MCPCapabilities includes more capability types than 'source', 'sink', and 'processor', you should add those as well to the initialization block.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread internal/apiserver/handler/mcp.go Resolved

@iFurySt iFurySt left a comment

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.

LGTM! Thanks!

h.logger.Warn("tenant parameter required but missing")
i18n.RespondWithError(c, i18n.ErrorTenantRequired)
return
}

Check failure

Code scanning / CodeQL

Size computation for allocation may overflow

This operation, which is used in an [allocation](1), involves a [potentially large value](2) and might overflow.
@iFurySt
iFurySt merged commit b4cacb3 into AmoyLab:main Sep 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants