Documentation
¶
Overview ¶
Package client provides an HTTP client for interacting with the HostMCP server. It implements the MCP (Model Context Protocol) over SSE (Server-Sent Events) and HTTP POST, allowing AI assistants to call tools on the HostMCP server such as listing containers, getting logs, executing commands, etc.
clientパッケージはHostMCPサーバーと通信するためのHTTPクライアントを提供します。 MCP(Model Context Protocol)をSSE(Server-Sent Events)とHTTP POSTで実装し、 AIアシスタントがHostMCPサーバー上のツール(コンテナ一覧取得、ログ取得、 コマンド実行など)を呼び出すことを可能にします。
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP client for HostMCP server that manages SSE connections and JSON-RPC communication with the MCP server.
The client maintains: - baseURL: The base URL of the HostMCP server (e.g., "http://localhost:18080") - httpClient: Standard HTTP client with timeout for regular requests - sseHTTPClient: HTTP client without timeout for long-lived SSE connections - sessionID: Unique identifier for the MCP session, obtained during SSE connection - sseConn: The active SSE connection response - messages: Channel for receiving parsed SSE messages - errors: Channel for receiving SSE connection errors - ctx/cancel: Context for managing client lifecycle and cancellation - mu: Mutex for thread-safe access to shared state - timeout: Timeout duration for HTTP requests and tool call responses
ClientはHostMCPサーバー用のHTTPクライアントで、SSE接続と MCPサーバーとのJSON-RPC通信を管理します。
クライアントは以下を維持します: - baseURL: HostMCPサーバーのベースURL(例:"http://localhost:18080") - httpClient: 通常リクエスト用のタイムアウト付き標準HTTPクライアント - sseHTTPClient: 長期接続のSSE用タイムアウトなしHTTPクライアント - sessionID: SSE接続時に取得するMCPセッションの一意識別子 - sseConn: アクティブなSSE接続レスポンス - messages: 解析済みSSEメッセージを受信するチャネル - errors: SSE接続エラーを受信するチャネル - ctx/cancel: クライアントのライフサイクルとキャンセル管理用コンテキスト - mu: 共有状態へのスレッドセーフなアクセス用ミューテックス - timeout: HTTPリクエストとツール呼び出しレスポンスのタイムアウト時間
func NewClient ¶
NewClient creates a new HostMCP HTTP client configured to connect to the specified server. It initializes two HTTP clients: one with a 30-second timeout for regular requests, and another without timeout for SSE connections that need to stay open indefinitely.
Parameters:
- baseURL: The base URL of the HostMCP server (e.g., "http://localhost:18080")
Returns:
- A pointer to the newly created Client instance
NewClientは指定されたサーバーに接続するための新しいHostMCP HTTPクライアントを作成します。 2つのHTTPクライアントを初期化します:通常リクエスト用の30秒タイムアウト付きクライアントと、 無期限に開いたままにする必要があるSSE接続用のタイムアウトなしクライアントです。
パラメータ:
- baseURL: HostMCPサーバーのベースURL(例:"http://localhost:18080")
戻り値:
- 新しく作成されたClientインスタンスへのポインタ
func (*Client) CallTool ¶
func (c *Client) CallTool(name string, arguments map[string]interface{}) (*ToolResult, error)
CallTool calls an MCP tool on the HostMCP server using JSON-RPC 2.0 over HTTP POST. The response is received asynchronously via the SSE channel.
The tool call process: 1. Validates that the client is connected (has session ID) 2. Creates a JSON-RPC request with method "tools/call" 3. Sends the request to /message endpoint with session ID 4. Waits for response on the SSE channel (with 30-second timeout) 5. Parses and returns the result or error
Parameters:
- name: The name of the tool to call (e.g., "list_containers", "get_logs")
- arguments: Tool-specific arguments as key-value pairs
Returns:
- *ToolResult: The tool execution result on success
- error: Error if not connected, request fails, or tool execution fails
CallToolはJSON-RPC 2.0 over HTTP POSTを使用してHostMCPサーバー上のMCPツールを呼び出します。 レスポンスはSSEチャネル経由で非同期に受信されます。
ツール呼び出しプロセス: 1. クライアントが接続されている(セッションIDを持っている)ことを検証 2. メソッド「tools/call」でJSON-RPCリクエストを作成 3. セッションID付きで/messageエンドポイントにリクエストを送信 4. SSEチャネルでレスポンスを待機(30秒タイムアウト付き) 5. 結果またはエラーを解析して返却
パラメータ:
- name: 呼び出すツールの名前(例:「list_containers」、「get_logs」)
- arguments: ツール固有の引数(キー値ペア)
戻り値:
- *ToolResult: 成功時のツール実行結果
- error: 未接続、リクエスト失敗、またはツール実行失敗時のエラー
func (*Client) Close ¶
Close closes the client connection and releases all resources. It cancels the client context (which stops the SSE reader goroutine) and closes the SSE connection if one exists.
This method is safe to call multiple times.
Returns:
- nil if closed successfully or already closed
- error if closing the SSE connection fails
Closeはクライアント接続を閉じ、すべてのリソースを解放します。 クライアントコンテキストをキャンセルし(SSEリーダーgoroutineを停止)、 SSE接続が存在する場合は閉じます。
このメソッドは複数回呼び出しても安全です。
戻り値:
- 正常に閉じた場合または既に閉じている場合はnil
- SSE接続のクローズに失敗した場合はerror
func (*Client) Connect ¶
Connect establishes an SSE connection to the HostMCP server, retrieves the session ID, and performs the MCP initialization handshake.
The connection process: 1. Sends GET request to /sse endpoint with appropriate headers 2. Reads the "endpoint" event from the SSE stream to get the session ID 3. Starts a background goroutine to continuously read SSE messages 4. Performs MCP initialize handshake with the server
This method is idempotent - if already connected, it returns immediately without error.
Returns:
- nil on successful connection and initialization
- error if connection or initialization fails
ConnectはHostMCPサーバーへのSSE接続を確立し、セッションIDを取得し、 MCP初期化ハンドシェイクを実行します。
接続プロセス: 1. 適切なヘッダー付きで/sseエンドポイントにGETリクエストを送信 2. SSEストリームから「endpoint」イベントを読み取ってセッションIDを取得 3. SSEメッセージを継続的に読み取るバックグラウンドgoroutineを開始 4. サーバーとMCP初期化ハンドシェイクを実行
このメソッドは冪等です - 既に接続済みの場合、エラーなしで即座に戻ります。
戻り値:
- 接続と初期化が成功した場合はnil
- 接続または初期化が失敗した場合はerror
func (*Client) HealthCheck ¶
HealthCheck checks if the HostMCP server is running and healthy. It sends a GET request to the /health endpoint and verifies a 200 OK response.
This is useful for: - Verifying server availability before establishing SSE connection - Monitoring server health in production - Quick connectivity tests
Returns:
- nil if server is healthy
- error if server is unreachable or returns non-200 status
HealthCheckはHostMCPサーバーが実行中で正常かどうかをチェックします。 /healthエンドポイントにGETリクエストを送信し、200 OKレスポンスを確認します。
以下の用途に有用です: - SSE接続確立前のサーバー可用性確認 - 継続的なサーバーヘルスモニタリング - 簡易接続テスト
戻り値:
- サーバーが正常な場合はnil
- サーバーに到達できないまたは非200ステータスの場合はerror
func (*Client) SetClientSuffix ¶
SetClientSuffix sets a suffix that will be appended to the client name. The resulting client name will be "hostmcp-go-client_<suffix>". This helps distinguish different callers (e.g., AI vs manual user).
SetClientSuffixはクライアント名に追加されるサフィックスを設定します。 結果のクライアント名は"hostmcp-go-client_<suffix>"になります。 これにより異なる呼び出し元(例:AIと手動ユーザー)を区別できます。
func (*Client) SetTimeout ¶
SetTimeout sets the timeout for HTTP requests and tool call response waiting. This affects both the HTTP client timeout and the SSE response wait timeout. Must be called before Connect() to take effect for the HTTP client. The default timeout is 30 seconds.
SetTimeoutはHTTPリクエストとツール呼び出しレスポンス待機のタイムアウトを設定します。 HTTPクライアントのタイムアウトとSSEレスポンス待機タイムアウトの両方に影響します。 HTTPクライアントに反映させるにはConnect()の前に呼び出す必要があります。 デフォルトのタイムアウトは30秒です。
type Content ¶
Content represents a single content block in an MCP response. Currently supports text content type, which is the most common.
Fields: - Type: Content type (e.g., "text", "image") - Text: The actual text content
ContentはMCPレスポンス内の単一コンテンツブロックを表します。 現在は最も一般的なテキストコンテンツタイプをサポートしています。
フィールド: - Type: コンテンツタイプ(例:「text」、「image」) - Text: 実際のテキストコンテンツ
type InitializeResponse ¶
type InitializeResponse struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id"`
Result any `json:"result,omitempty"`
Error *JSONRPCError `json:"error,omitempty"`
}
InitializeResponse represents the response for the MCP initialize method. It has a generic Result type since initialization responses vary by server.
Fields: - JSONRPC: Protocol version, always "2.0" - ID: Request identifier matching the initialize request - Result: Server capabilities and information (any type) - Error: Error information if initialization failed
InitializeResponseはMCP initializeメソッドのレスポンスを表します。 初期化レスポンスはサーバーによって異なるため、汎用的なResult型を持ちます。
フィールド: - JSONRPC: プロトコルバージョン、常に「2.0」 - ID: 初期化リクエストに対応するリクエスト識別子 - Result: サーバーの機能と情報(任意の型) - Error: 初期化が失敗した場合のエラー情報
type JSONRPCError ¶
type JSONRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
JSONRPCError represents an error in JSON-RPC 2.0 format. Standard error codes are defined by the JSON-RPC specification: - -32700: Parse error - -32600: Invalid request - -32601: Method not found - -32602: Invalid params - -32603: Internal error
Fields: - Code: Numeric error code - Message: Human-readable error description - Data: Additional error data (optional)
JSONRPCErrorはJSON-RPC 2.0形式のエラーを表します。 標準エラーコードはJSON-RPC仕様で定義されています: - -32700: 解析エラー - -32600: 無効なリクエスト - -32601: メソッドが見つからない - -32602: 無効なパラメータ - -32603: 内部エラー
フィールド: - Code: 数値エラーコード - Message: 人が読めるエラー説明 - Data: 追加のエラーデータ(オプション)
type JSONRPCRequest ¶
type JSONRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id"`
Method string `json:"method"`
Params interface{} `json:"params,omitempty"`
}
JSONRPCRequest represents a JSON-RPC 2.0 request structure used for communicating with the HostMCP server.
Fields: - JSONRPC: Protocol version, always "2.0" - ID: Request identifier for matching responses - Method: The method to invoke (e.g., "initialize", "tools/call") - Params: Optional parameters for the method
JSONRPCRequestはHostMCPサーバーとの通信に使用される JSON-RPC 2.0リクエスト構造体を表します。
フィールド: - JSONRPC: プロトコルバージョン、常に「2.0」 - ID: レスポンスとのマッチング用リクエスト識別子 - Method: 呼び出すメソッド(例:「initialize」、「tools/call」) - Params: メソッドのオプションパラメータ
type JSONRPCResponse ¶
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id"`
Result *ToolResult `json:"result,omitempty"`
Error *JSONRPCError `json:"error,omitempty"`
}
JSONRPCResponse represents a JSON-RPC 2.0 response for tool calls. It contains either a successful result or an error, but not both.
Fields: - JSONRPC: Protocol version, always "2.0" - ID: Request identifier matching the original request - Result: Tool execution result (present on success) - Error: Error information (present on failure)
JSONRPCResponseはツール呼び出し用のJSON-RPC 2.0レスポンスを表します。 成功した結果またはエラーのいずれかを含みますが、両方は含みません。
フィールド: - JSONRPC: プロトコルバージョン、常に「2.0」 - ID: 元のリクエストに対応するリクエスト識別子 - Result: ツール実行結果(成功時に存在) - Error: エラー情報(失敗時に存在)
type ToolResult ¶
type ToolResult struct {
Content []Content `json:"content"`
IsError bool `json:"isError,omitempty"`
}
ToolResult represents the result of an MCP tool call. It follows the MCP content structure for returning tool outputs.
Fields: - Content: Array of content blocks (typically text results) - IsError: True if the tool execution failed (tool-level error, not JSON-RPC error)
ToolResultはMCPツール呼び出しの結果を表します。 ツール出力を返すためのMCPコンテンツ構造に従います。
フィールド: - Content: コンテンツブロックの配列(通常はテキスト結果) - IsError: ツール実行が失敗した場合はtrue(JSON-RPCエラーではなくツールレベルのエラー)