Model Context Protocol (openhusky-mcp)
openhusky-mcp implements a native Java 21 Model Context Protocol (2025-11-25) client over both Stdio and Streamable HTTP transports, translating external MCP tools into openhusky-core AgentTool instances.
<dependency>
<groupId>dev.openhusky</groupId>
<artifactId>openhusky-mcp</artifactId>
<version>0.3.0</version>
</dependency>implementation("dev.openhusky:openhusky-mcp:0.3.0")Transports: StdioMcpTransport vs. StreamableHttpMcpTransport
| Feature | StdioMcpTransport | StreamableHttpMcpTransport |
|---|---|---|
| Protocol Framing | Newline-delimited JSON-RPC 2.0 over child process stdin / stdout | HTTP POST accepting application/json or text/event-stream (SSE via SseReader) |
| Session Lifecycle | Subprocess lifetime; graceful stdin EOF + shutdownGracePeriod (2s default) on close() | Tracks Mcp-Session-Id header; sends DELETE on close(); lock-protected HTTP 404 session re-initialization |
| Authentication | Subprocess environment variables (env) | Custom static headers + dynamic McpAuthProvider with single-shot HTTP 401 refresh retry (OAuthMcpAuthProvider for OAuth 2.1 PKCE) |
| Cancellation & Progress | AbortSignal fails pending future; routes notifications/progress by _meta.progressToken | AbortSignal cancels HTTP request and closes stream immediately; parses SSE progress notifications |
| Diagnostics & Bounds | Virtual-thread stderr ring buffer (64 lines) included in unexpected-exit errors | DEFAULT_MAX_RESPONSE_BODY_BYTES = 16 MiB; default connectTimeout = 15s, requestTimeout = 60s; honors EnvProxySelector |
Configuration via mcp.json or Programmatic McpServerConfig
McpToolkit (dev.openhusky.mcp.McpToolkit) parses standard mcpServers JSON configurations with ${ENV_VAR} and ${ENV_VAR:-default} placeholder expansion:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "${WORKSPACE_DIR:-/tmp/ws}"],
"cwd": "${WORKSPACE_DIR:-/tmp/ws}",
"timeoutSeconds": 30,
"trustReadOnlyHint": false
},
"docs": {
"url": "https://mcp.example.com/mcp",
"headers": {
"Authorization": "Bearer ${DOCS_MCP_TOKEN}"
},
"timeoutMs": 45000,
"trustReadOnlyHint": true
},
"enterprise-saas": {
"url": "https://api.vendor.com/mcp",
"oauth": {
"clientId": "${OAUTH_CLIENT_ID}",
"scopes": ["mcp:tools", "mcp:read"],
"redirectUri": "http://127.0.0.1:3080/oauth/callback"
}
}
}
}Load mcp.json or construct servers programmatically, and always close McpToolkit (AutoCloseable) on shutdown:
try (McpToolkit mcp = McpToolkit.builder()
.servers(McpServerConfig.parseMcpJson(Files.readString(Path.of("mcp.json"))))
.naming(McpToolNaming.MCP_PREFIXED)
.resilientStartup(true) // Degrade gracefully if one optional MCP server is unreachable
.build()) {
if (!mcp.startupErrors().isEmpty()) {
mcp.startupErrors().forEach((server, err) ->
log.warn("MCP server '{}' unavailable: {}", server, err.getMessage()));
}
AgentRuntime runtime = AgentRuntime.builder()
.provider(provider)
.model(model)
.tools(mcp.tools())
.permissionPolicy(PermissionPolicy.failClosed()
.allow("mcp__docs__*")
.requireApproval("mcp__filesystem__write_file")
.build())
.approvalHandler(approvalHandler)
.build();
}McpToolkit.Builder Options
McpToolkit.fromJsonFile(Path)/fromJson(String): Fast convenience constructors withresilientStartup = falseandMcpToolNaming.MCP_PREFIXED.resilientStartup(boolean): Whentrue, failed server handshakes are logged and recorded inmcp.startupErrors()instead of aborting startup; whenfalse(default), startup fails fast and closes already-started servers.authProviderFactory(Function<McpServerConfig.StreamableHttp, McpAuthProvider>): Supplies custom auth providers (e.g.,OAuthMcpAuthProviderbacked byMcpOAuthClientwith RFC 9728 / RFC 8414 discovery and RFC 7591 dynamic client registration).refreshAllTools(): Re-queriestools/liston active clients and updatesmcp.tools()atomically.
Tool Naming, McpToolAdapter & Security Semantics
Tool Naming (McpToolNaming)
McpToolNaming maps (serverName, toolName) into LLM-safe identifiers matching ^[a-zA-Z0-9_-]{1,64}$:
| Strategy | Format | Example (server="docs", tool="search.api") |
|---|---|---|
MCP_PREFIXED (default) | mcp__<server>__<tool> | mcp__docs__search_api |
SERVER_PREFIXED | <server>__<tool> | docs__search_api |
RAW | <tool> | search_api |
If the formatted name exceeds 64 characters, McpToolNaming truncates to 55 characters and appends _<8-char-SHA256> to guarantee uniqueness without exceeding OpenAI/Anthropic/Gemini limits.
McpToolAdapter Behavior
- Concurrency Mapping: When an MCP tool declares
annotations.readOnlyHint == true,McpToolAdapter.executionMode()returnsToolExecutionMode.PARALLEL_SAFE; otherwiseToolExecutionMode.SEQUENTIAL. - Fail-Closed
readOnly()Flag (trustReadOnlyHint):McpToolAdapter.readOnly()returnstrueonly when bothtrustReadOnlyHint == true(defaults tofalse) andannotations.readOnlyHint == true. This prevents an untrusted remote MCP server from bypassingPermissionPolicy.readOnly()orallowReadOnlyTools()simply by self-declaringreadOnlyHint: true. - Multimodal & Structured Results: Converts MCP
TextItem→TextBlock,ImageItem→ContentBlock.ImageBlock,EmbeddedResourceItem/ResourceLinkItem→ formatted text blocks, and attachesstructuredContent,mcpServer, andmcpToolNametoToolResult.details(). - Progress & Cancellation: Forwards
notifications/progresstoToolContext.emitProgress(...)and propagatesAbortSignalcancellation to the underlying transport.
Recommended PermissionPolicy Patterns for MCP
PermissionPolicy policy = PermissionPolicy.failClosed()
// Allow all tools from a trusted read-only internal documentation server
.allow("mcp__docs__*")
// Require interactive HITL approval for write operations on a GitHub or filesystem MCP server
.requireApproval("mcp__filesystem__write_file", "mcp__filesystem__edit_file", "mcp__github__create_*")
// Explicitly allow safe read operations
.allow("mcp__filesystem__read_file", "mcp__filesystem__list_directory")
.build();