langchain4j-mcp-server-patterns
Install this skill
npx skills add giuseppe-trisciuoglio/developer-kitWorks across Claude Code, Cursor, Codex, Copilot & Antigravity
LangChain4j MCP Server patterns provide a standardized architecture for connecting Java-based AI applications to the Model Context Protocol ecosystem. This implementation bridges LangChain4j services with external data and tools, allowing developers to expose internal functions, documentation, or prompt libraries as discoverable MCP entities. By structuring code into specific providers for tools, resources, and prompts, you establish a modular interface that remains protocol-agnostic. Whether utilizing standard input/output for local processes or HTTP for networked services, this pattern ensures that Java services can communicate with diverse AI clients without needing custom integration logic for every new source. The architecture promotes strict schema validation and clear separation of concerns, making it suitable for maintainable enterprise agent backends that require standardized connectivity.
When to Use This Skill
- β’Exposing internal Java database logic as executable tools for an AI agent
- β’Serving corporate documentation or static policy files as readable resources
- β’Creating reusable, version-controlled prompt templates for standardized AI workflows
- β’Building a local plugin system where tools are discovered dynamically at runtime
How to Invoke This Skill
Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:
- βimplement an mcp server in langchain4j
- βhow to create a custom mcp tool provider java
- βserve spring boot resources via mcp protocol
- βconnect langchain4j to an mcp client using stdio
- βdefine prompt templates for mcp server java
Pro Tips
- π‘Design tool providers with clear, single responsibilities and modularity to simplify maintenance, testing, and scalability as your AI agent's capabilities grow.
- π‘Prioritize robust error handling, logging, and observability within your MCP server to ensure reliable tool execution and quick debugging in production environments.
- π‘Leverage MCP's resource-based access control to securely manage and filter data sources, ensuring AI models receive relevant context without overexposure to sensitive information.
What this skill does
- β’Implementation of ToolProvider interfaces for dynamic function registration
- β’Support for ResourceListProvider and ResourceReadHandler to expose data streams
- β’Centralized prompt management using PromptListProvider and PromptGetHandler
- β’Abstracted transport layers supporting both Stdio and HTTP/SSE communication
- β’Seamless integration with Spring Boot through configuration beans
When not to use it
- βWhen the application does not require external interoperability with other MCP-compliant clients
- βIn environments where raw API calls or simple function calling is sufficient without standardization
- βFor extremely low-latency requirements where the protocol overhead of MCP is undesirable
Example workflow
- Define a ToolProvider class to declare input schemas and execute logic
- Register the provider within an MCPServer builder instance
- Configure the preferred transport layer using Stdio or HttpMcpTransport
- Start the server to make tools and resources discoverable to connected clients
- Instantiate an McpClient in the target application to bridge the remote functions
Prerequisites
- βLangChain4j core libraries
- βBasic understanding of JSON-RPC or MCP protocol flow
- βJava 17 or higher
Pitfalls & limitations
- !Complex schema definitions for tool inputs can lead to runtime serialization errors if not strictly matched
- !Blocking operations within tool execution may cause timeouts on the client side
- !Protocol overhead might introduce slight latency compared to direct method invocation
FAQ
How it compares
While manual integration requires writing custom controllers and parsing logic for every new connection, using MCP provides a vendor-neutral standard that allows your tools to work automatically across all MCP-compliant AI environments.
π Full skill instructions β original source: giuseppe-trisciuoglio/developer-kit
Implement Model Context Protocol (MCP) servers with LangChain4j to extend AI capabilities with standardized tools, resources, and prompt templates.
## When to Use
Use this skill when building:
- AI applications requiring external tool integration
- Enterprise MCP servers with multi-domain support (GitHub, databases, APIs)
- Dynamic tool providers with context-aware filtering
- Resource-based data access systems for AI models
- Prompt template servers for standardized AI interactions
- Scalable AI agents with resilient tool execution
- Multi-modal AI applications with diverse data sources
- Spring Boot applications with MCP integration
- Production-ready MCP servers with security and monitoring
## Quick Start
### Basic MCP Server
Create a simple MCP server with one tool:
MCPServer server = MCPServer.builder()
.server(new StdioServer.Builder())
.addToolProvider(new SimpleWeatherToolProvider())
.build();
server.start();### Spring Boot Integration
Configure MCP server in Spring Boot:
@Bean
public MCPSpringConfig mcpServer(List<ToolProvider> tools) {
return MCPSpringConfig.builder()
.tools(tools)
.server(new StdioServer.Builder())
.build();
}## Core Concepts
### MCP Architecture
MCP standardizes AI application connections:
- **Tools**: Executable functions (database queries, API calls)
- **Resources**: Data sources (files, schemas, documentation)
- **Prompts**: Pre-configured templates for tasks
- **Transport**: Communication layer (stdio, HTTP, WebSocket)
AI Application ββ MCP Client ββ Transport ββ MCP Server ββ External Service### Key Components
- **MCPServer**: Main server instance with configuration
- **ToolProvider**: Tool specification and execution interface
- **ResourceListProvider/ResourceReadHandler**: Resource access
- **PromptListProvider/PromptGetHandler**: Template management
- **Transport**: Communication mechanisms (stdio, HTTP)
## Implementation Patterns
### Tool Provider Pattern
Create tools with proper schema validation:
class WeatherToolProvider implements ToolProvider {
@Override
public List<ToolSpecification> listTools() {
return List.of(ToolSpecification.builder()
.name("get_weather")
.description("Get weather for a city")
.inputSchema(Map.of(
"type", "object",
"properties", Map.of(
"city", Map.of("type", "string", "description", "City name")
),
"required", List.of("city")
))
.build());
}
@Override
public String executeTool(String name, String arguments) {
// Parse arguments and execute tool logic
return "Weather data result";
}
}### Resource Provider Pattern
Provide static and dynamic resources:
class CompanyResourceProvider
implements ResourceListProvider, ResourceReadHandler {
@Override
public List<McpResource> listResources() {
return List.of(
McpResource.builder()
.uri("policies")
.name("Company Policies")
.mimeType("text/plain")
.build()
);
}
@Override
public String readResource(String uri) {
return loadResourceContent(uri);
}
}### Prompt Template Pattern
Create reusable prompt templates:
class PromptTemplateProvider
implements PromptListProvider, PromptGetHandler {
@Override
public List<Prompt> listPrompts() {
return List.of(
Prompt.builder()
.name("code-review")
.description("Review code for quality")
.build()
);
}
@Override
public String getPrompt(String name, Map<String, String> args) {
return applyTemplate(name, args);
}
}## Transport Configuration
### Stdio Transport
Local process communication:
McpTransport transport = new StdioMcpTransport.Builder()
.command(List.of("npm", "exec", "@modelcontextprotocol/server-everything"))
.logEvents(true)
.build();### HTTP Transport
Remote server communication:
McpTransport transport = new HttpMcpTransport.Builder()
.sseUrl("http://localhost:3001/sse")
.logRequests(true)
.logResponses(true)
.build();## Client Integration
### MCP Client Setup
Connect to MCP servers:
McpClient client = new DefaultMcpClient.Builder()
.key("my-client")
.transport(transport)
.cacheToolList(true)
.build();
// List available tools
List<ToolSpecification> tools = client.listTools();### Tool Provider Integration
Bridge MCP servers to LangChain4j AI services:
McpToolProvider provider = McpToolProvider.builder()
.mcpClients(mcpClient)
.failIfOneServerFails(false)
.filter((client, tool) -> filterByPermissions(tool))
.build();
// Integrate with AI service
AIAssistant assistant = AiServices.builder(AIAssistant.class)
.chatModel(chatModel)
.toolProvider(provider)
.build();## Security & Best Practices
### Tool Security
Implement secure tool filtering:
McpToolProvider secureProvider = McpToolProvider.builder()
.mcpClients(mcpClient)
.filter((client, tool) -> {
if (tool.name().startsWith("admin_") && !isAdmin()) {
return false;
}
return true;
})
.build();### Resource Security
Apply access controls to resources:
public boolean canAccessResource(String uri, User user) {
return resourceService.hasAccess(uri, user);
}### Error Handling
Implement robust error handling:
try {
String result = mcpClient.executeTool(request);
} catch (McpException e) {
log.error("MCP execution failed: {}", e.getMessage());
return fallbackResult();
}## Advanced Patterns
### Multi-Server Configuration
Configure multiple MCP servers:
@Bean
public List<McpClient> mcpClients(List<ServerConfig> configs) {
return configs.stream()
.map(this::createMcpClient)
.collect(Collectors.toList());
}
@Bean
public McpToolProvider multiServerProvider(List<McpClient> clients) {
return McpToolProvider.builder()
.mcpClients(clients)
.failIfOneServerFails(false)
.build();
}### Dynamic Tool Discovery
Runtime tool filtering based on context:
McpToolProvider contextualProvider = McpToolProvider.builder()
.mcpClients(clients)
.filter((client, tool) -> isToolAllowed(user, tool, context))
.build();### Health Monitoring
Monitor MCP server health:
@Component
public class McpHealthChecker {
@Scheduled(fixedRate = 30000) // 30 seconds
public void checkServers() {
mcpClients.forEach(client -> {
try {
client.listTools();
markHealthy(client.key());
} catch (Exception e) {
markUnhealthy(client.key(), e.getMessage());
}
});
}
}## Configuration
### Application Properties
Configure MCP servers in application.yml:
mcp:
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"]
log-events: false### Spring Boot Configuration
Configure MCP with Spring Boot:
@Configuration
@EnableConfigurationProperties(McpProperties.class)
public class McpConfiguration {
@Bean
public MCPServer mcpServer(List<ToolProvider> providers) {
return MCPServer.builder()
.server(new StdioServer.Builder())
.addToolProvider(providers)
.enableLogging(true)
.build();
}
}## Examples
Refer to [examples.md](./references/examples.md) for comprehensive implementation examples including:
- Basic MCP server setup
- Multi-tool enterprise servers
- Resource and prompt providers
- Spring Boot integration
- Error handling patterns
- Security implementations
## API Reference
Complete API documentation is available in [api-reference.md](./references/api-reference.md) covering:
- Core MCP classes and interfaces
- Transport configuration
- Client and server patterns
- Error handling strategies
- Configuration management
- Testing and validation
## Best Practices
1. **Resource Management**: Always close MCP clients properly using try-with-resources
2. **Error Handling**: Implement graceful degradation when servers fail
3. **Security**: Use tool filtering and resource access controls
4. **Performance**: Enable caching and optimize tool execution
5. **Monitoring**: Implement health checks and observability
6. **Testing**: Create comprehensive test suites with mocks
7. **Documentation**: Document tools, resources, and prompts clearly
8. **Configuration**: Use structured configuration for maintainability
## References
- [LangChain4j Documentation](https://langchain4j.com/docs/)
- [Model Context Protocol Specification](https://modelcontextprotocol.org/)
- [API Reference](./references/api-reference.md)
- [Examples](./references/examples.md)
How to Use This Skill Unit
Option A: Project-Specific (Recommended)
- Click "Download" above
- In your project, create the directory:
.agent/skills/langchain4j-mcp-server-patterns/ - Save the file as
SKILL.md - The agent will automatically discover the skill based on its description.
Option B: Global Installation (All Agents)
Save the file to these locations to make it available across all projects:
- Claude Code:
~/.claude/skills/giuseppe-trisciuoglio/developer-kit/langchain4j-mcp-server-patterns/SKILL.md - Cursor:
~/.cursor/skills/giuseppe-trisciuoglio/developer-kit/langchain4j-mcp-server-patterns/SKILL.md - Antigravity:
~/.gemini/antigravity/skills/giuseppe-trisciuoglio/developer-kit/langchain4j-mcp-server-patterns/SKILL.md
π Install with CLI:npx skills add giuseppe-trisciuoglio/developer-kit
