fastMCP4J
About
Fast lightweight Java MCP server framework - Build Model Context Protocol servers with minimal boilerplate and full TypeScript SDK compatibility
Details
- Author
- terseprompts
- Categories
- Developer Tools, Other
Jump to
Setup
Install fastMCP4J in your MCP client (Claude Desktop, Cursor, Windsurf, and others).
Repository: https://github.com/terseprompts/fastMCP4J
Follow the installation instructions in the repository README, then restart your MCP client.
Java library for building MCP servers — annotation-driven, minimal dependencies
AI Agents →Share this skill with Claude for code generation
Lightweight. 12 dependencies. No containers.
Note: Beta release (v0.3.1-beta) — Multi-class modules, bash tools, telemetry. API stable.
<dependency> <groupId>io.github.terseprompts.fastmcp</groupId> <artifactId>fastmcp-java</artifactId> <version>0.3.1-beta</version> </dependency>
dependencies { implementation 'io.github.terseprompts.fastmcp:fastmcp-java:0.3.1-beta' }
@McpServer(name = "Assistant", version = "1.0") public class MyAssistant { @McpTool(description = "Summarize text") public String summarize(@McpParam(description = "Text") String text) { return "Summary: " + text.substring(0, Math.min(100, text.length())); } public static void main(String[] args) { FastMCP.server(MyAssistant.class) .stdio() // or .sse() or .streamable() .run(); } }
mvn exec:java -Dexec.mainClass="com.example.MyAssistant"
That's it. Your MCP server is running.
@McpTool(description = "Add two numbers") public int add(int a, int b) { return a + b; }
@McpTool(description = "Process data") @McpAsync // ← just add this public Mono<String> process(@McpContext Context ctx, String input) { return Mono.fromCallable(() -> { ctx.reportProgress(50, "Processing..."); return slowOperation(input); }); }
@McpServer(name = "MyServer", version = "1.0") @McpMemory // ← just add this public class MyServer { // AI now remembers things across sessions }
@McpServer(name = "MyServer", version = "1.0") @McpMemory // AI remembers @McpTodo // AI manages tasks @McpPlanner // AI breaks tasks into steps @McpFileRead // AI reads your files @McpFileWrite // AI writes files public class MyServer { // All tools enabled, zero implementation needed }
@McpServer( name = "MyServer", version = "1.0", modules = {StringTools.class, MathTools.class} // Explicit modules ) public class MyServer { // Tools from StringTools and MathTools are included }
Or use package scanning for auto-discovery:
@McpServer( name = "MyServer", version = "1.0", scanBasePackage = "com.example.tools" // Auto-discover all tools ) public class MyServer { // All @McpTool classes in the package are included }
@McpServer(name = "MyServer", version = "1.0") @McpBash(timeout = 30) // Shell command execution with security guardrails public class MyServer { // Provides 'execute_command' tool with OS-aware shell selection }
@McpServer(name = "MyServer", version = "1.0") @McpTelemetry(enabled = true, exportConsole = true) // Metrics & tracing public class MyServer { // Automatic tool invocation tracking with console export }
FastMCP.server(MyServer.class) .stdio() // For CLI tools, local agents .sse() // For web clients, long-lived connections .streamable() // For bidirectional streaming (recommended) .run();
FastMCP.server(MyServer.class) .port(3000) // HTTP port .requestTimeout(Duration.ofMinutes(5)) // Request timeout .keepAliveSeconds(30) // Keep-alive interval .capabilities(c -> c .tools(true) .resources(true, true) .prompts(true)) .run();
Add visual polish to your server, tools, resources, and prompts.
@McpServer( name = "my-server", icons = { "data:image/svg+xml;base64,...:image/svg+xml:64x64:light", "data:image/svg+xml;base64,...:image/svg+xml:64x64:dark" } ) @McpTool( description = "My tool", icons = {"https://example.com/icon.png"} ) public class MyServer { }
@McpResource(uri = "config://settings") public String getSettings() { return "{\"theme\": \"dark\"}"; } @McpPrompt(name = "code-review") public String codeReviewPrompt(@McpParam(description = "Code to review") String code) { return "Review this code:\n" + code; }
Add ONE annotation, get complete functionality.
@McpTool(description = "Create task") public String createTask( @McpParam( description = "Task name", examples = {"backup", "sync"}, constraints = "Cannot be empty", defaultValue = "default", required = false ) String taskName ) { return "Created: " + taskName; }
@McpPreHook— Runs before tool is called. ReceivesMap<String, Object> arguments.
@McpPostHook— Runs after tool completes. ReceivesMap<String, Object> arguments, Object result.
Use for logging, validation, authentication, audit trails, metrics.
@McpServer(name = "MyServer", version = "1.0") public class MyServer { @McpTool(description = "Calculate") public int calculate(int x, int y) { return x + y; } // Run before ALL tools () @McpPreHook(toolName = "", order = 1) void authenticate(Map<String, Object> args) { String token = (String) args.get("token"); if (!isValid(token)) throw new SecurityException("Unauthorized"); } // Run after specific tool only @McpPostHook(toolName = "calculate", order = 1) void logResult(Map<String, Object> args, Object result) { System.out.println("Result: " + result); } public static void main(String[] args) { FastMCP.server(MyServer.class).stdio().run(); } }
- toolName— Target specific tool name, or""for all tools. Empty = inferred from method name
- order— Execution priority (lower = first). Default:0
- Pre-hook:Map<String, Object> arguments— Tool input arguments
- Post-hook:Map<String, Object> arguments, Object result— Input + output
@McpContext— Inject request context into your tool.
Access client info, session data, request metadata.
@McpServer(name = "MyServer", version = "1.0") public class MyServer { @McpTool(description = "Get client info") public String getClientInfo(@McpContext Context context) { return "Client: " + context.getClientId(); } @McpTool(description = "Get session ID") public String getSessionId(@McpContext Context context) { return "Session: " + context.getSessionId(); } @McpTool(description = "Read file with context") public String readFile(@McpContext Context context, String path) { context.info("Reading file: " + path); // Access request headers (e.g., for auth) Map<String, String> headers = context.getRequestHeaders(); String authHeader = headers.get("Authorization"); // ... read file return "Content"; } public static void main(String[] args) { FastMCP.server(MyServer.class).stdio().run(); } }
- getClientId()— Client identifier
- getSessionId()— Session identifier
- getToolName()— Current tool name
- getRequestHeaders()— Client request headers (e.g., auth tokens, custom headers)
- info(String)— Log info message
- warning(String)— Log warning
- error(String)— Log error
- reportProgress(int, String)— Report progress percentage
- listResources()— List available resources
- listPrompts()— List available prompts
Execute shell commands with OS-aware shell selection and built-in security guardrails.
@McpServer(name = "MyServer", version = "1.0") @McpBash( timeout = 30, // Command timeout in seconds visibleAfterBasePath = "/sandbox/", // Whitelist allowed directories notAllowedPaths = {"/etc", "/root"} // Blacklist dangerous paths ) public class MyServer { }
- Directory validation (whitelist/blacklist)
- Dangerous command blocking (rm -rf, wget, curl, ssh, etc.)
- Directory traversal prevention
- Cross-platform path handling (Windows/Unix)
- Windows:cmd.exe
- macOS:/bin/zsh
- Linux:/bin/bash
Collect metrics and traces for tool invocations.
@McpServer(name = "MyServer", version = "1.0") @McpTelemetry( enabled = true, exportConsole = true, // Human-readable output exportOtlp = false, // OpenTelemetry export sampleRate = 1.0, // 100% sampling includeArguments = false, // Don't log sensitive args metricExportIntervalMs = 60_000 ) public class MyServer { }
- Tool invocation counters
- Execution duration histograms
- Error rates
Split tools across multiple classes for better organization.
@McpServer( name = "MyServer", version = "1.0", modules = {StringTools.class, MathTools.class} )
@McpServer( name = "MyServer", version = "1.0", scanBasePackage = "com.example.tools" )
Raw MCP SDK: 35+ lines per toolFastMCP4J: ~8 lines per tool
- Cold start: <500ms
- Tool invocation: <5ms
- Memory: ~64MB
- Purpose-built for MCP — not a general AI framework
- Architecture— How it works
- Roadmap— What's next
- Contributing— PRs welcome
- Changelog— Version history
- Claude Skill— For AI agents
This is a web browser that enables your coding agent, such as Claude Code, to visit websites on your behalf and assist you in identifying bugs or creating UI test cases.
A Java plugin that exposes the Jadx decompiler API over HTTP for interaction with MCP clients.
Specialized tools for analyzing and migrating Java applications from Java EE 8 (javax.) to Jakarta EE 9+ (jakarta.).
Java Archive Reader Protocol MCP server - Give AI agents X-ray vision into compiled Java code by decompiling JAR/WAR/EAR files and Maven/Gradle dependencies
A Model Context Protocol (MCP) server for searching Java documentation. This server enables AI assistants to search and retrieve Java API documentation from JSON files.
Allows AI assistants to remotely drive the JetBrains debugger via MCP, including breakpoints, stepping, and variable inspection.
Resolves your Gradle project’s real classpath and returns Java source, method signatures, and class structure for any dependency class—using the version your build actually uses, not random files from ~/.gradle/caches.
Legacy Java to Microservices Refactoring
A community gateway to migrate legacy Jakarta EE monoliths into Spring Boot using AST parsing.
Search for and retrieve detailed information, including READMEs and metadata, for Maven packages from Maven Central.
Access real-time Maven Central intelligence for fast and accurate dependency information.
Sign in to leave a review
Use Google, GitHub, or an email account so ratings stay tied to real people.
No reviews posted yet.





