Skip to content

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.

xml
<dependency>
    <groupId>dev.openhusky</groupId>
    <artifactId>openhusky-mcp</artifactId>
    <version>0.3.0</version>
</dependency>
kotlin
implementation("dev.openhusky:openhusky-mcp:0.3.0")

Transports: StdioMcpTransport vs. StreamableHttpMcpTransport ​

FeatureStdioMcpTransportStreamableHttpMcpTransport
Protocol FramingNewline-delimited JSON-RPC 2.0 over child process stdin / stdoutHTTP POST accepting application/json or text/event-stream (SSE via SseReader)
Session LifecycleSubprocess 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
AuthenticationSubprocess environment variables (env)Custom static headers + dynamic McpAuthProvider with single-shot HTTP 401 refresh retry (OAuthMcpAuthProvider for OAuth 2.1 PKCE)
Cancellation & ProgressAbortSignal fails pending future; routes notifications/progress by _meta.progressTokenAbortSignal cancels HTTP request and closes stream immediately; parses SSE progress notifications
Diagnostics & BoundsVirtual-thread stderr ring buffer (64 lines) included in unexpected-exit errorsDEFAULT_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:

json
{
  "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:

java
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 with resilientStartup = false and McpToolNaming.MCP_PREFIXED.
  • resilientStartup(boolean): When true, failed server handshakes are logged and recorded in mcp.startupErrors() instead of aborting startup; when false (default), startup fails fast and closes already-started servers.
  • authProviderFactory(Function<McpServerConfig.StreamableHttp, McpAuthProvider>): Supplies custom auth providers (e.g., OAuthMcpAuthProvider backed by McpOAuthClient with RFC 9728 / RFC 8414 discovery and RFC 7591 dynamic client registration).
  • refreshAllTools(): Re-queries tools/list on active clients and updates mcp.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}$:

StrategyFormatExample (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() returns ToolExecutionMode.PARALLEL_SAFE; otherwise ToolExecutionMode.SEQUENTIAL.
  • Fail-Closed readOnly() Flag (trustReadOnlyHint): McpToolAdapter.readOnly() returns true only when both trustReadOnlyHint == true (defaults to false) and annotations.readOnlyHint == true. This prevents an untrusted remote MCP server from bypassing PermissionPolicy.readOnly() or allowReadOnlyTools() simply by self-declaring readOnlyHint: true.
  • Multimodal & Structured Results: Converts MCP TextItem → TextBlock, ImageItem → ContentBlock.ImageBlock, EmbeddedResourceItem / ResourceLinkItem → formatted text blocks, and attaches structuredContent, mcpServer, and mcpToolName to ToolResult.details().
  • Progress & Cancellation: Forwards notifications/progress to ToolContext.emitProgress(...) and propagates AbortSignal cancellation to the underlying transport.

java
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();

Released under the MIT License. Built with Java 21 Virtual Threads.