Comprehensive developer toolkit providing reusable skills for Java/Spring Boot, TypeScript/NestJS/React/Next.js, Python, PHP, AWS CloudFormation, AI/RAG, DevOps, and more.
82
82%
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Risky
Do not use without reviewing
This document provides comprehensive API documentation for implementing MCP servers with LangChain4j.
Primary interface for communicating with MCP servers.
Key Methods:
// Tool Management
List<ToolSpecification> listTools();
String executeTool(ToolExecutionRequest request);
// Resource Management
List<McpResource> listResources();
String getResource(String uri);
List<McpResourceTemplate> listResourceTemplates();
// Prompt Management
List<Prompt> listPrompts();
String getPrompt(String name);
// Lifecycle Management
void close();Builder for creating MCP clients with configuration options.
Configuration Methods:
McpClient client = new DefaultMcpClient.Builder()
.key("unique-client-id") // Unique identifier
.transport(transport) // Transport mechanism
.cacheToolList(true) // Enable tool caching
.logMessageHandler(handler) // Custom logging
.build();Builder for creating tool providers that bridge MCP servers to LangChain4j AI services.
Configuration Methods:
McpToolProvider provider = McpToolProvider.builder()
.mcpClients(client1, client2) // Add MCP clients
.failIfOneServerFails(false) // Configure failure handling
.filterToolNames("tool1", "tool2") // Filter by names
.filter((client, tool) -> logic) // Custom filtering
.build();For local process communication with npm packages or Docker containers.
McpTransport transport = new StdioMcpTransport.Builder()
.command(List.of("npm", "exec", "@modelcontextprotocol/server-everything@0.6.2"))
.logEvents(true)
.build();For HTTP-based communication with remote MCP servers.
McpTransport transport = new HttpMcpTransport.Builder()
.sseUrl("http://localhost:3001/sse")
.logRequests(true)
.logResponses(true)
.build();For streamable HTTP transport with enhanced performance.
McpTransport transport = new StreamableHttpMcpTransport.Builder()
.url("http://localhost:3001/mcp")
.logRequests(true)
.logResponses(true)
.build();Create AI services integrated with MCP tool providers.
Integration Methods:
AIAssistant assistant = AiServices.builder(AIAssistant.class)
.chatModel(chatModel)
.toolProvider(toolProvider)
.chatMemoryProvider(memoryProvider)
.build();Handle MCP-specific exceptions gracefully:
try {
String result = mcpClient.executeTool(request);
} catch (McpException e) {
log.error("MCP execution failed: {}", e.getMessage());
// Implement fallback logic
}Implement retry logic for unreliable MCP servers:
RetryTemplate retryTemplate = RetryTemplate.builder()
.maxAttempts(3)
.exponentialBackoff(1000, 2, 10000)
.build();
String result = retryTemplate.execute(context ->
mcpClient.executeTool(request));mcp:
fail-if-one-server-fails: false
cache-tools: true
servers:
github:
type: docker
command: ["/usr/local/bin/docker", "run", "-e", "GITHUB_TOKEN", "-i", "mcp/github"]
log-events: true
database:
type: stdio
command: ["/usr/bin/npm", "exec", "@modelcontextprotocol/server-sqlite@0.6.2"]
log-events: false@Configuration
@EnableConfigurationProperties(McpProperties.class)
public class McpConfiguration {
@Bean
public List<McpClient> mcpClients(McpProperties properties) {
return properties.getServers().entrySet().stream()
.map(entry -> createMcpClient(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
@Bean
public McpToolProvider mcpToolProvider(List<McpClient> mcpClients, McpProperties properties) {
return McpToolProvider.builder()
.mcpClients(mcpClients)
.failIfOneServerFails(properties.isFailIfOneServerFails())
.build();
}
}Define tools with proper schema:
ToolSpecification toolSpec = ToolSpecification.builder()
.name("database_query")
.description("Execute SQL queries against the database")
.inputSchema(Map.of(
"type", "object",
"properties", Map.of(
"sql", Map.of(
"type", "string",
"description", "SQL query to execute"
)
)
))
.build();Execute tools with structured requests:
ToolExecutionRequest request = ToolExecutionRequest.builder()
.name("database_query")
.arguments("{\"sql\": \"SELECT * FROM users LIMIT 10\"}")
.build();
String result = mcpClient.executeTool(request);Access and utilize MCP resources:
// List available resources
List<McpResource> resources = mcpClient.listResources();
// Get specific resource content
String content = mcpClient.getResource("resource://schema/database");
// Work with resource templates
List<McpResourceTemplate> templates = mcpClient.listResourceTemplates();Convert MCP resources to tools automatically:
DefaultMcpResourcesAsToolsPresenter presenter =
new DefaultMcpResourcesAsToolsPresenter();
mcpToolProvider.provideTools(presenter);
// Adds 'list_resources' and 'get_resource' tools automaticallyImplement security-conscious tool filtering:
McpToolProvider secureProvider = McpToolProvider.builder()
.mcpClients(mcpClient)
.filter((client, tool) -> {
// Check user permissions
if (tool.name().startsWith("admin_") && !currentUser.hasRole("ADMIN")) {
return false;
}
return true;
})
.build();Apply security controls to resource access:
public boolean canAccessResource(String uri, User user) {
if (uri.contains("sensitive/") && !user.hasRole("ADMIN")) {
return false;
}
return true;
}Implement intelligent caching:
// Enable tool caching for performance
McpClient client = new DefaultMcpClient.Builder()
.transport(transport)
.cacheToolList(true)
.build();
// Periodic cache refresh
@Scheduled(fixedRate = 300000) // 5 minutes
public void refreshToolCache() {
mcpClients.forEach(client -> {
try {
client.invalidateCache();
client.listTools(); // Preload cache
} catch (Exception e) {
log.warn("Cache refresh failed: {}", e.getMessage());
}
});
}Optimize connection management:
@Bean
public Executor mcpExecutor() {
return Executors.newFixedThreadPool(10); // Dedicated thread pool
}Setup for testing:
@TestConfiguration
public class MockMcpConfiguration {
@Bean
@Primary
public McpClient mockMcpClient() {
McpClient mock = Mockito.mock(McpClient.class);
when(mock.listTools()).thenReturn(List.of(
ToolSpecification.builder()
.name("test_tool")
.description("Test tool")
.build()
));
when(mock.executeTool(any(ToolExecutionRequest.class)))
.thenReturn("Mock result");
return mock;
}
}Test MCP integrations:
@SpringBootTest
class McpIntegrationTest {
@Autowired
private AIAssistant assistant;
@Test
void shouldExecuteToolsSuccessfully() {
String response = assistant.chat("Execute test tool");
assertThat(response).contains("Mock result");
}
}Monitor MCP server health:
@Component
public class McpHealthChecker {
@EventListener
@Async
public void checkHealth() {
mcpClients.forEach(client -> {
try {
client.listTools(); // Simple health check
healthRegistry.markHealthy(client.key());
} catch (Exception e) {
healthRegistry.markUnhealthy(client.key(), e.getMessage());
}
});
}
}Collect execution metrics:
@Bean
public Counter toolExecutionCounter(MeterRegistry meterRegistry) {
return meterRegistry.counter("mcp.tool.execution", "type", "total");
}
@Bean
public Timer toolExecutionTimer(MeterRegistry meterRegistry) {
return meterRegistry.timer("mcp.tool.execution.time");
}Handle version compatibility:
public class VersionedMcpClient {
public boolean isCompatible(String serverVersion) {
return semanticVersionChecker.isCompatible(
REQUIRED_MCP_VERSION, serverVersion);
}
public McpClient createClient(ServerConfig config) {
if (!isCompatible(config.getVersion())) {
throw new IncompatibleVersionException(
"Server version " + config.getVersion() +
" is not compatible with required " + REQUIRED_MCP_VERSION);
}
return new DefaultMcpClient.Builder()
.transport(createTransport(config))
.build();
}
}This API reference provides the complete foundation for implementing MCP servers and clients with LangChain4j, covering all major aspects from basic setup to advanced enterprise patterns.
plugins
developer-kit-ai
skills
chunking-strategy
prompt-engineering
developer-kit-aws
skills
aws
aws-cli-beast
aws-cost-optimization
aws-drawio-architecture-diagrams
aws-sam-bootstrap
aws-cloudformation
aws-cloudformation-auto-scaling
references
aws-cloudformation-bedrock
references
aws-cloudformation-cloudfront
references
aws-cloudformation-cloudwatch
references
aws-cloudformation-dynamodb
references
aws-cloudformation-ec2
aws-cloudformation-ecs
references
aws-cloudformation-elasticache
aws-cloudformation-iam
references
aws-cloudformation-lambda
references
aws-cloudformation-rds
aws-cloudformation-s3
references
aws-cloudformation-security
references
aws-cloudformation-task-ecs-deploy-gh
aws-cloudformation-vpc
developer-kit-core
skills
developer-kit-java
skills
aws-lambda-java-integration
aws-rds-spring-boot-integration
aws-sdk-java-v2-bedrock
aws-sdk-java-v2-core
aws-sdk-java-v2-dynamodb
aws-sdk-java-v2-kms
aws-sdk-java-v2-lambda
aws-sdk-java-v2-messaging
aws-sdk-java-v2-rds
aws-sdk-java-v2-s3
aws-sdk-java-v2-secrets-manager
graalvm-native-image
langchain4j
langchain4j-mcp-server-patterns
langchain4j-ai-services-patterns
references
langchain4j-mcp-server-patterns
references
langchain4j-rag-implementation-patterns
references
langchain4j-spring-boot-integration
langchain4j-testing-strategies
langchain4j-tool-function-calling-patterns
langchain4j-vector-stores-configuration
references
qdrant
references
spring-ai-mcp-server-patterns
references
spring-boot-actuator
spring-boot-cache
spring-boot-crud-patterns
spring-boot-dependency-injection
spring-boot-event-driven-patterns
spring-boot-openapi-documentation
spring-boot-project-creator
spring-boot-resilience4j
spring-boot-rest-api-standards
spring-boot-saga-pattern
spring-boot-security-jwt
assets
references
scripts
spring-boot-test-patterns
spring-data-jpa
references
spring-data-neo4j
references
unit-test-application-events
unit-test-bean-validation
unit-test-boundary-conditions
unit-test-caching
unit-test-config-properties
unit-test-controller-layer
unit-test-exception-handler
unit-test-json-serialization
unit-test-mapper-converter
unit-test-parameterized
unit-test-scheduled-async
unit-test-service-layer
unit-test-utility-methods
unit-test-wiremock-rest-api
developer-kit-php
skills
aws-lambda-php-integration
developer-kit-python
skills
aws-lambda-python-integration
developer-kit-tools
developer-kit-typescript
skills
aws-lambda-typescript-integration
better-auth
drizzle-orm-patterns
dynamodb-toolbox-patterns
references
nestjs
nestjs-best-practices
nestjs-code-review
nestjs-drizzle-crud-generator
scripts
nextjs-app-router
nextjs-authentication
nextjs-code-review
nextjs-data-fetching
references
nextjs-deployment
nextjs-performance
nx-monorepo
react-code-review
react-patterns
references
shadcn-ui
tailwind-css-patterns
references
tailwind-design-system
references
turborepo-monorepo
typescript-docs
typescript-security-review
zod-validation-utilities