Back to AI Tools & Agents

langchain4j-mcp-server-patterns

LangChain4jMCPAI agentstoolingserver patternsSpring Boot AIcustom AIdeveloper kit
⭐ 282πŸ“„ MITπŸ•’ 2026-06-15Source β†—

Install this skill

npx skills add giuseppe-trisciuoglio/developer-kit

Works 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

  1. Define a ToolProvider class to declare input schemas and execute logic
  2. Register the provider within an MCPServer builder instance
  3. Configure the preferred transport layer using Stdio or HttpMcpTransport
  4. Start the server to make tools and resources discoverable to connected clients
  5. 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

Does this support non-Java clients?
Yes, because the server follows the standard Model Context Protocol, any compatible MCP client can communicate with it.
Can I use this without Spring Boot?
Yes, the server architecture is modular and can be initialized in any standard Java main method or container.
What is the difference between a tool and a resource?
Tools are executable functions that perform actions, while resources are data sources that provide information or content.

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.

Source & trust

⭐ 282 starsπŸ“„ MITπŸ•’ Updated 2026-06-15
πŸ“„ Full skill instructions β€” original source: giuseppe-trisciuoglio/developer-kit
# LangChain4j MCP Server Implementation Patterns

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)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/langchain4j-mcp-server-patterns/
  3. Save the file as SKILL.md
  4. 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

Read the Master Guide: Mastering Agent Skills β†’

Recommended Rules

View more rules β†’

Recommended Workflows

View more workflows β†’

Recommended MCP Servers

View more MCP servers β†’

Take It Further

Maximize your productivity with these powerful resources

πŸ“‹

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
πŸ“–

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid ai tools & agents issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under AI Tools & Agents and is published by Giuseppe Trisciuoglio, maintained in giuseppe-trisciuoglio/developer-kit.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.