REST和GraphQL端点自动发现工具

Spring Boot MCP Server是一个自动发现REST和GraphQL端点并将其作为MCP工具暴露的库,使AI代理能够安全地与应用程序API交互。

  • by girisenji
  • Java
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 girisenji/spring-boot-mcp-server

使用说明

Spring Boot MCP服务器

Spring Boot入门库 自动发现REST和GraphQL端点 并将其暴露为 MCP(模型上下文协议)工具,允许像Claude这样的AI代理安全地与应用程序的API交互。

🚀 特性

  • 自动发现:自动从Spring应用程序中发现REST和GraphQL端点
  • OpenAPI集成:使用OpenAPI/Swagger规范生成工具模式
  • GraphQL支持:将GraphQL查询和突变作为单独的工具进行发现
  • 苏格兰和南方能源公司运输:通过服务器发送的事件实现MCP协议
  • 配置驱动安全:通过版本控制的YAML显式批准工具-默认情况下拒绝
  • HTTP执行:通过向实际端点发出HTTP请求来执行工具
  • 管理API:用于发现和管理工具配置的REST端点
  • 运行时重新加载:无需重新启动即可重新加载批准的工具
  • 自动配置:添加依赖关系,使MCP服务器开箱即用
  • 速率限制:每个工具和每个客户端的IP请求限制
  • 执行超时:可配置的HTTP请求超时
  • 请求大小限制:防止内存耗尽
  • 审计日志:用于合规性和安全性的结构化日志记录(PLAIN/JSON格式)
  • 度量与监控:Prometheus/Grafana可观察性的可选千分尺集成
  • MCP资源:将配置和数据作为可读资源公开
  • MCP提示:为工具使用提供有用的指导提示

📦 安装

梅文

<dependency>
    <groupId>com.girisenji.ai</groupId>
    <artifactId>spring-boot-mcp-server</artifactId>
    <version>1.0.0</version>
</dependency>

Gradle

implementation 'io.github.girisenji.ai:spring-boot-mcp-server:1.0.0'

🎯 快速开始

1.添加依赖关系

添加到Spring Boot 3.2+应用程序:

<dependency>
    <groupId>com.girisenji.ai</groupId>
    <artifactId>spring-boot-mcp-server</artifactId>
    <version>1.0.0</version>
</dependency>

2.创建REST端点

创建标准的Spring REST控制器:

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAll();
    }
    
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.findById(id);
    }
}
    
    Application Properties (Optional)

```yaml
mcp:
  server:
    enabled: true  # Enable/disable MCP server (default: true)
    
    # Server metadata
    server-info:
      name: "My MCP Server"
      version: "1.0.0"
      description: "Custom MCP server"
    
    # Tool approval configuration
    tool-approval:
      approved-tools-config: "classpath:approved-tools.yml"

工具批准(必需)

所有工具必须经过明确批准 通过YAML配置。创建 src/main/resources/approved-tools.yml:

approvedTools:
  - tool_name_1
  - tool_name_2
  - greet

安全模型:

  • ✅ 仅配置驱动:通过版本控制的YAML批准的工具
  • ✅ 默认拒绝:除非明确列出,否则没有批准的工具
  • ✅ 审计跟踪:Git历史记录中跟踪的更改
  • ✅ 运行时重新加载:更新配置并重新加载,无需重新启动

外部配置:

对于生产,使用外部配置文件:

mcp:
  server:
    tool-approval:
      approved-tools-config: "file:/etc/mcp/approved-tools.yml"
# Environment variable
export MCP_SERVER_TOOL_APPROVAL_APPROVED_TOOLS_CONFIG=file:/config/approved-tools.yml
java -jar app.jar
    openapi-enabled: true   # Discover from OpenAPI specs
    rest-enabled: true      # Discover REST endpoints
    graphql-enabled: true   # Discover GraphQL endpoints

工具筛选

auto-mcp-server:
  tools:
    include-patterns:
      - "/api/**"           # Include API endpoints
      - "/v1/**"            # Include v1 endpoints
    exclude-patterns:
      - "/actuator/**"      # Exclude actuator endpoints
      - "/error"            # Exclude error endpoint
      - "/internal/**"      # Exclude internal endpoints
    max-tool-name-length: 100
    use-operation-id-as-tool-name: true

完整示例

auto-mcp-server:
  enabled: true
  endpoint: /mcp
  eager-init: true
  
  discovery:
    openapi-enabled: true
    rest-enabled: true
    graphql-enabled: true
  
  tools:
    # Discovery filtering
    include-patterns: "/**"
    exclude-patterns: 
      - "/actuator/**"
      - "/error"
      - "/swagger-ui/**"
      - "/v3/api-docs/**"
    
    # Tool approval (CONFIG_BASED recommended for production)
    approval-mode: config-based
    approval-config-file: classpath:approved-tools.yml
    
    # Tool naming
    max-tool-name-length: 100
    use-operation-id-as-tool-name: true
  
  # Rate limiting (optional)
  rate-limiting:
    enabled: true
    default-requests-per-hour: 100
  
  # Execution configuration (optional)
  execution:
    default-timeout: PT30S              # 30 seconds read timeout
    default-connect-timeout: PT5S       # 5 seconds connect timeout
    max-request-body-size: 10MB         # Maximum request body size
    max-response-body-size: 10MB        # Maximum response body size
  
  # Audit logging (optional)
  audit:
    enabled: true                       # Enable audit logging (default: true)
    format: PLAIN                       # PLAIN or JSON (default: PLAIN)
    log-tool-executions: true           # Log tool execution events
    log-approval-changes: true          # Log tool approval changes
    log-security-events: true           # Log rate limits, timeouts, size limits

# Optional: Enable metrics (requires spring-boot-starter-actuator)
management:
  endpoints:
    web:
      exposure:
        include: health,metrics,prometheus
  metrics:
    tags:
      application: ${spring.application.name}

启用指标(可选)

要启用生产就绪指标,请添加Spring Boot执行器:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Optional: For Prometheus format -->
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

可用指标:

  • mcp.tool.execution.count -工具执行计数器(标签: tool, status, error)
  • mcp.tool.execution.duration -工具执行延迟直方图(标签: tool)
  • mcp.discovery.refresh.count -发现刷新计数器
  • mcp.sse.connections.active -主动SSE连接仪表
  • mcp.rate_limit.exceeded.count -违反速率限制(标签: tool)

访问指标:

  • JSON: GET /actuator/metrics/mcp.tool.execution.count
  • 普罗米修斯: GET /actuator/prometheus

Prometheus查询示例:

# Request rate by tool
rate(mcp_tool_execution_count_total[5m])

# Error rate
rate(mcp_tool_execution_count_total{status="failure"}[5m])

# P95 latency
histogram_quantile(0.95, rate(mcp_tool_execution_duration_seconds_bucket[5m]))


### Advanced Tool Configuration

Configure per-tool overrides in `approved-tools.yml` for rate limits, timeouts, and size limits:

```yaml
approvedTools:
  # Simple format (uses all defaults)
  - simpleToolName
  
  # With custom rate limit
  - name: frequentOperation
    rateLimit:
      requests: 1000
      window: PT1H                      # ISO-8601 duration: 1 hour
  
  # With custom timeout
  - name: longRunningTask
    timeout: PT5M                       # 5 minutes for slow operations
    rateLimit:
      requests: 10
      window: PT1H
  
  # With custom size limits
  - name: largeDataUpload
    maxRequestBodySize: 50MB            # Allow larger request
    maxResponseBodySize: 100MB          # Allow larger response
    timeout: PT2M
  
  # Full configuration example
  - name: complexOperation
    timeout: PT1M
    maxRequestBodySize: 25MB
    maxResponseBodySize: 50MB
    rateLimit:
      requests: 50
      window: PT30M

ISO-8601持续时间格式:

  • PT30S =30秒
  • PT5M =5分钟
  • PT1H =1小时
  • PT2H30M =2小时30分钟

尺寸格式:

  • 10MB =10兆字节
  • 1GB =1 GB
  • 512KB =512千字节
  • 1048576 =字节(无后缀)

MCP资源和提示

服务器会自动公开资源和提示,以帮助AI代理有效地使用您的工具。

内置资源

  • 服务器配置 (mcp://server/config):当前服务器配置和功能

您可以通过编程方式注册自定义资源:

@Autowired
ResourceService resourceService;

// Register a text resource
resourceService.registerResource(
    "mcp://app/status",
    "Application Status",
    "Current application health and status",
    "application/json",
    () -> McpProtocol.ResourceContents.text(
        "mcp://app/status",
        "application/json",
        "{\"status\":\"healthy\",\"uptime\":\"5h30m\"}")
);

// Register a blob resource (Base64-encoded)
String base64Data = Base64.getEncoder().encodeToString(imageBytes);
resourceService.registerResource(
    "mcp://app/logo",
    "Application Logo",
    "Company logo image",
    "image/png",
    () -> McpProtocol.ResourceContents.blob(
        "mcp://app/logo",
        "image/png",
        base64Data)
);

内置提示

  • 欢迎:MCP服务器及其功能介绍
  • 工具使用帮助:有效使用MCP工具的指南

您可以通过编程方式注册自定义提示:

@Autowired
PromptService promptService;

promptService.registerPrompt(
    "api-best-practices",
    "Best practices for using this API",
    List.of(
        new McpProtocol.PromptArgument("operation", "Specific operation name", false)
    ),
    args -> {
        String operation = (String) args.getOrDefault("operation", "any operation");
        String message = String.format("""
            Best practices for %s:
            1. Always validate input parameters
            2. Handle rate limits gracefully  
            3. Check response status codes
            """, operation);
        
        return new McpProtocol.GetPromptResult(
            "API best practices guidance",
            List.of(new McpProtocol.PromptMessage("user", McpProtocol.Content.text(message)))
        );
    }
);

🛡️ 工具批准和管理

⚠️ 重要:工具批准是基于YAML的,默认情况下是拒绝的。使用管理REST API 发现 在开发过程中使用工具,然后在 approved-tools.yml (版本受控)。

开发流程

  1. 开发API:创建REST控制器或GraphQL解析器
  2. 发现:呼叫 /mcp/admin/tools/discovered 查看所有已发现的端点
  3. 出口:通过下载所有已发现工具的YAML模板 /mcp/admin/tools/yaml
  4. 批准:编辑 approved-tools.yml 批准人工智能代理的安全工具
  5. 重新加载:邮寄至 /mcp/admin/tools/reload (零停机时间)或重新启动应用程序

管理REST API

该库为工具发现和YAML生成提供了只读端点:

# Get summary statistics (total discovered vs approved)
GET /mcp/admin/tools/summary

# List all discovered tools with approval status
GET /mcp/admin/tools/discovered

# Generate YAML template for approved-tools.yml
GET /mcp/admin/tools/yaml?approvedOnly=false

# Refresh tool discovery (re-scan all endpoints)
POST /mcp/admin/tools/refresh

# Reload approved-tools.yml without restart (zero downtime)
POST /mcp/admin/tools/reload

例子

# Get summary of discovered tools
curl http://localhost:8080/mcp/admin/tools/summary

# List all discovered tools with approval status
curl http://localhost:8080/mcp/admin/tools/discovered

# Export tools in YAML format for approved-tools.yml
curl http://localhost:8080/mcp/admin/tools/yaml > approved-tools.yml

# Reload configuration after editing approved-tools.yml (no restart needed)
curl -X POST http://localhost:8080/mcp/admin/tools/reload

📖 运作原理

发现过程

  1. OpenAPI发现 (如果可用)

    • 解析OpenAPI规范
    • 提取具有参数和模式的操作
    • 使用正确的JSON模式生成工具定义
  2. REST发现 (回退)

    • 扫描 @RestController 豆子
    • 分析 @RequestMapping 方法
    • 从方法签名生成模式
  3. GraphQL发现 (如果可用)

    • GraphQL模式的反思
    • 发现查询和突变
    • 将GraphQL类型映射到JSON模式

审批工作流程

┌─────────────────┐
│  API Endpoint   │
│   Discovered    │
└────────┬────────┘
         │
         ▼
┌─────────────────┐      ┌──────────────┐
│ Determine Mode  │─────▶│ CONFIG_BASED │──▶ ✅ PRODUCTION (approved-tools.yml)
└────────┬────────┘      └──────────────┘
         │
         ▼
┌─────────────────┐
│ Check Approval  │
│ (YAML config)   │
└────────┬────────┘
         │
         ▼
      ✅ / ❌

建筑

┌─────────────────────────────────────────────────┐
│              Spring Boot Application            │
│  ┌───────────────────────────────────────────┐  │
│  │         Auto-Configuration                │  │
│  │  - Discovers REST endpoints               │  │
│  │  - Discovers GraphQL endpoints            │  │
│  │  - Parses OpenAPI specifications          │  │
│  │  - Registers MCP endpoints                │  │
│  └───────────────────────────────────────────┘  │
│                                                 │
│  ┌───────────────┐       ┌───────────────-───┐  │
│  │  Tool         │       │  Tool Approval    │  │
│  │  Registry     │◄──────┤  Service          │  │
│  │  - Discovery  │       │  - YAML config    │  │
│  │  - Filtering  │       │  - Approval check │  │
│  └───────┬───────┘       └────────────────-──┘  │
│          │                                      │
│          ▼                                      │
│  ┌───────────────────────────────────────────┐  │
│  │        MCP Controller (/mcp/sse)          │  │
│  │  - SSE endpoint                           │  │
│  │  - Protocol handling                      │  │
│  │  - HTTP tool execution                    │  │
│  └───────────────────────────────────────────┘  │
└─────────────────────────────────────────────────┘
                      │
                      │ SSE (Server-Sent Events)
                      ▼
              ┌─────────────-─┐
              │  AI Agent     │
              │ (Claude, etc) │
              └─────────────-─┘

工具审批流程

┌──────────────────┐
│  Endpoint        │
│  Discovered      │
│  (REST/GraphQL)  │
└────────┬─────────┘
         │
         ▼[LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- [Model Context Protocol](https://modelcontextprotocol.io) - The protocol specification
- [Spring Boot](https://spring.io/projects/spring-boot) - The application framework
- [Anthropic](https://www.anthropic.com) - MCP protocol development

## 📞 Support

- **Issues**: [GitHub Issues](https://github.com/girisenji/spring-boot-mcp-server/issues)
- **Discussions**: [GitHub Discussions](https://github.com/girisenji/spring-boot-mcp-server/discussions)
- **Email**: girisenji@gmail.com

## 🗺️ Roadmap

- [x] Config-driven tool approval
- [x] SSE transport implementation
- [x] Tool discovery and registry
- [x] Management REST API
- [x] Runtime configuration reload
- [x] Rate limiting and execution timeouts
- [ ] WebSocket transport support
- [ ] Resource and Prompt support
- [ ] Enhanced metrics and monitoring
- [ ] Audit logging
- [ ] Multi-tenant support

## 📚 Learn More

- [Model Context Protocol Specification](https://modelcontextprotocol.io)
- [MCP GitHub Repository](https://github.com/modelcontextprotocol)
- [Spring Boot Documentation](https://spring.io/projects/spring-boot)  
**Transport**: Server-Sent Events (SSE)  
**Format**: JSON-RPC 2.0

**Supported Methods**:
- `initialize`Application
Dependencies

The library requires only Spring Boot and Jackson (already included in Spring Boot):

```🔒 Security

**Tool Approval**: All tools are denied by default. Only tools explicitly listed in `approved-tools.yml` are exposed to AI agents.

**Input Validation**: Implement proper validation in your tools:

```java
@Override
public ToolResult execute(Map<String, Object> arguments) {
    // Validate required parameters
    if (!arguments.containsKey("path")) {
        return ToolResult.error("Missing required parameter: path");
    }
    
    String path = (String) arguments.get("path");
    
    // Validate input
    if (path.contains("..")) {
        return ToolResult.error("Path traversal not allowed");
    }
    
    // Safe execution
    return performOperation(path);
}

认证:与Spring Security集成以实现端点保护:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
            .requestMatchers("/mcp/sse").authenticated()
            .requestMatchers("/mcp/admin/**").hasRole("ADMIN")
        );
        return http.build();
    }
}

超文本传输安全协议:在生产环境中始终使用HTTPS:

server:
  port: 8443
  ssl:
    enabled: true
    key-store: classpath:keystore.p12
    key-store-password: ${KEYSTORE_PASSWORD}

🤝 贡献

欢迎投稿!请随时提交拉取请求。

看 贡献.md 指南 org.springframework.boot 弹簧启动板


No additional dependencies required.

**Application.java:**
```java
@SpringBootApplication
public class McpServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(McpServerApplication.class, args);
    }
}

UserController.java:

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @GetMapping
    public List<User> getAllUsers() {
        return List.of(
            new User(1L, "Alice"),
            new User(2L, "Bob")
        );
    }
}

批准的tools.yml:

approvedTools:
  - get_all_users

运行应用程序并将AI代理连接到 http://localhost:8080/mcp/sse

📋 需求

  • Java:21或以上
  • Spring Boot:3.2或更高
  • 构建工具:Maven或Gradle

可选依赖关系

  • 开放应用程序接口:用于OpenAPI发现的SpringDoc OpenAPI v2
  • 图查询语言:用于GraphQL发现的Spring GraphQL

🤝 贡献

欢迎投稿!请随时提交拉取请求。

📄 许可证

此项目在Apache License 2.0下获得许可-有关详细信息,请参阅License文件。

🙏 致谢

📞 支持

对于问题、疑问或贡献:

  • 在GitHub上创建问题
  • 联系维护人员

🗺️ 路线图

看 TODO.md 完整的执行计划和路线图。

当前焦点(v1.0.0):

  • ✅ REST/GraphQL端点自动发现
  • ✅ 基于HTTP的工具执行
  • ✅ 基于YAML的安全审批
  • ✅ SSE运输
  • ✅ 管理REST API
  • ✅ 增强的安全功能(速率限制、超时、大小限制、审计日志)

高优先级(v1.1.0+):

  • []WebSocket传输支持
  • []指标和监测
  • []性能优化

未来考虑:

  • []MCP资源和提示支持
  • []多租户支持
  • []扩展文档和示例

由...制作❤️ 对于AI社区