langchain4j-mcp-server-patterns
Provides LangChain4j patterns for implementing MCP (Model Context Protocol) servers, creating Java AI tools, exposing tool calling capabilities, and integrating MCP clients with AI services. Use when building a Java MCP server, implementing tool calling in Java, connecting LangChain4j to external MCP servers, or securing tool exposure for agent workflows.
What this skill does
# LangChain4j MCP Server Implementation Patterns
## Overview
Use this skill to design and implement Model Context Protocol (MCP) integrations with LangChain4j.
The main concerns are:
- defining a clean tool, resource, and prompt surface
- choosing the right transport and bootstrap model
- filtering unsafe capabilities before exposing them to agents or applications
Keep `SKILL.md` focused on the implementation flow. Use the bundled references for expanded examples and API-level detail.
## When to Use
Use this skill when:
- building a Java MCP server that exposes tools, resources, or prompts
- integrating LangChain4j with one or more external MCP servers
- wiring MCP support into a Spring Boot application
- filtering available tools by tenant, user role, or runtime context
- adding observability, resilience, and safe failure handling around MCP interactions
- reviewing an MCP integration for prompt-injection and side-effect risks
Typical trigger phrases include `langchain4j mcp`, `java mcp server`, `mcp tool provider`, `spring boot mcp`, and `connect langchain4j to mcp`.
## Instructions
### 1. Design the MCP surface before writing code
Decide what the server should expose:
- tools for actions with clear inputs and side effects
- resources for read-only or structured data access
- prompts only when a reusable template adds real value
Keep names stable, descriptions concrete, and schemas small enough for a client or model to understand quickly.
### 2. Implement providers with narrow responsibilities
Use separate classes for each concern:
- tool provider for executable functions
- resource provider for discoverable and readable data
- prompt provider for reusable prompt templates
Validate arguments before execution and return clear error messages for invalid input or unavailable dependencies.
### 3. Choose the transport intentionally
Use:
- stdio for local integrations, CLI tools, and sidecar processes
- HTTP or SSE for remote or shared services
Pin external server versions and document how the process is started, authenticated, and monitored.
### 4. Bridge MCP into LangChain4j carefully
When consuming MCP servers from LangChain4j:
- initialize clients during application startup
- cache tool lists only when stale metadata is acceptable
- filter tools by trust level, environment, or user permissions
- fail closed for dangerous tools rather than exposing everything by default
### 5. Add resilience and security controls
At minimum:
- bound execution time for external calls
- log server and tool identity for each failure
- sanitize content returned by external resources before using it downstream
- isolate privileged tools behind allowlists, qualifiers, or role checks
### 6. Validate the full workflow
Before shipping:
- verify tool discovery and invocation with a real MCP client
- test disconnected or slow server behavior
- confirm that tool filtering matches the intended authorization model
- check that prompts and resources do not leak secrets or unsafe instructions
## Examples
### Example 1: Minimal tool provider and stdio server bootstrap
```java
class WeatherToolProvider implements ToolProvider {
@Override
public List<ToolSpecification> listTools() {
return List.of(
ToolSpecification.builder()
.name("get_weather")
.description("Return the current weather for a city")
.inputSchema(Map.of(
"type", "object",
"properties", Map.of(
"city", Map.of("type", "string")
),
"required", List.of("city")
))
.build()
);
}
@Override
public String executeTool(String name, String arguments) {
return weatherService.lookup(arguments);
}
}
MCPServer server = MCPServer.builder()
.server(new StdioServer.Builder())
.addToolProvider(new WeatherToolProvider())
.build();
server.start();
```
Use this pattern for local tool execution or a sidecar process started by another application.
### Example 2: Expose MCP tools to a LangChain4j AI service with filtering
```java
McpToolProvider toolProvider = McpToolProvider.builder()
.mcpClients(mcpClients)
.failIfOneServerFails(false)
.filter((client, tool) -> !tool.name().startsWith("admin_"))
.build();
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(chatModel)
.toolProvider(toolProvider)
.build();
```
Use this pattern when you want LangChain4j to consume external MCP servers while still enforcing trust boundaries.
## Best Practices
- Keep each tool focused, deterministic, and well-described.
- Prefer explicit schemas over free-form string arguments.
- Separate read-only resources from tools with side effects.
- Filter or disable privileged tools by default.
- Pin external MCP server packages or container versions.
- Capture metrics for connection failures, invocation latency, and tool error rates.
- Store longer protocol details and framework-specific wiring in `references/` instead of expanding `SKILL.md` indefinitely.
## Constraints and Warnings
- External MCP servers are untrusted integration boundaries and may expose malicious or misleading content.
- Do not forward raw resource content directly into autonomous tool execution without validation.
- Some LangChain4j and MCP APIs evolve quickly; adapt class names and builders to the versions already used in the project.
- Long-running or stateful tools need explicit timeout, cancellation, and cleanup behavior.
- Stdio-based servers require process lifecycle management and robust logging.
## References
- `references/examples.md`
- `references/api-reference.md`
## Related Skills
- `prompt-engineering`
- `spring-ai`
- `clean-architecture`
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.