MCP Client
The mcp module (github.com/ijaidev/gojent/mcp) is a client-only adapter that connects Gojent applications to Model Context Protocol (MCP) servers over stdio or Streamable HTTP and exposes their tools as standard tool.Tool values. It never serves MCP itself, and your configured agent.Policy and agent.Approver remain the final authority for every tool call.
Connect a stdio server and register tools
Install the module with go get github.com/ijaidev/gojent/mcp. Configure servers with mcp.ServerConfig, connect once with client.Connect, inspect ServerStatus, and pass client.Tools() into agent.Config.Tools:
package main
import (
"context"
"fmt"
"log"
"github.com/ijaidev/gojent/core/agent"
"github.com/ijaidev/gojent/mcp"
"github.com/ijaidev/gojent/providers/mockllm"
)
func connectStdioMCP(ctx context.Context) error {
client := mcp.New()
defer func() { _ = client.Close() }()
statuses, err := client.Connect(ctx, []mcp.ServerConfig{{
Name: "workspace",
Command: "my-mcp-server",
Args: []string{"--root", "/workspace"},
Env: []string{"WORKSPACE=/workspace"},
AllowedTools: []string{"read_file", "search"},
DeniedTools: []string{"write_file"},
}})
if err != nil {
return err
}
for _, status := range statuses {
if status.Status != mcp.StatusConnected {
return status.Err
}
}
mcpTools, err := client.Tools()
if err != nil {
return err
}
assistant, err := agent.New(agent.Config{
Name: "mcp-agent",
Model: mockllm.New("Ready."),
Tools: mcpTools,
})
if err != nil {
return err
}
resp, err := assistant.Generate(ctx, "List workspace files.")
if err != nil {
return err
}
fmt.Println(resp.Text)
return nil
}
func main() {
if err := connectStdioMCP(context.Background()); err != nil {
log.Fatal(err)
}
}
Naming, filtering, origin lookup, and instructions
- Minimal child environment:
Envis the complete allowlist passed to a stdio child process (plus a small platform minimum); no other host environment variables leak into the subprocess. - Tool filtering and collision checks:
AllowedToolsandDeniedToolsmatch the server’s declared MCP tool names before normalization (emptyAllowedToolspermits all tools;DeniedToolswins overAllowedTools). Surviving tools are normalized to<server>_<tool>using ASCII normalization, and collisions fail withmcp.ErrToolNameCollisionbefore any model call. - Exact origin recovery:
client.ToolOrigin(name)returns the exact configuredserverNameand raw MCP tool name for any normalized tool inclient.Tools(), tracking live refreshes and reconnects without string splitting. - Server instructions:
client.Instructions()exposes each server’s initialization instructions to your host application; Gojent never injects untrusted server instructions into an agent’s system prompt automatically. - Advisory annotations & schema passthrough: MCP tool annotations map onto advisory
tool.Annotations, but Gojent’sPolicyandApproverremain the final gate. MCP servers validate their own input schemas rather than using Gojent’s struct-tag schema subset.
Streamable HTTP, AuthHook, and SSRF protections
Replace Command with URL to connect a Streamable HTTP server, optionally adding static Headers, a custom HTTPClient, or an AuthHook:
package main
import (
"context"
"log"
"net/http"
"github.com/ijaidev/gojent/mcp"
)
type tokenAuth struct{ token string }
func (a tokenAuth) Apply(_ context.Context, req *http.Request) error {
req.Header.Set("Authorization", "Bearer "+a.token)
return nil
}
func (a tokenAuth) Challenge(_ context.Context, _ *http.Request, _ *http.Response) error {
return mcp.ErrAuthRequired
}
func connectHTTPMCP(ctx context.Context, apiKey string) (*mcp.Client, []mcp.ServerStatus, error) {
client := mcp.New()
statuses, err := client.Connect(ctx, []mcp.ServerConfig{{
Name: "remote",
URL: "https://mcp.example.com/mcp",
Headers: map[string]string{"X-API-Key": apiKey},
Auth: tokenAuth{token: "secret-token"},
}})
if err != nil {
_ = client.Close()
return nil, nil, err
}
return client, statuses, nil
}
func main() {
client, statuses, err := connectHTTPMCP(context.Background(), "api-key")
if err != nil {
log.Fatal(err)
}
defer func() { _ = client.Close() }()
for _, status := range statuses {
if status.Status != mcp.StatusConnected {
log.Fatal(status.Err)
}
}
if _, err := client.Tools(); err != nil {
log.Fatal(err)
}
}
Security and transport guarantees on HTTP servers:
- HTTPS and redirect rules: Plain
http://is accepted only for loopback hosts. Scheme changes and non-loopback cross-origin redirects are refused before forwarding headers or bodies; loopback-to-loopback redirects remain allowed with credential headers stripped. A customHTTPClientowns its own redirect and SSRF policy. AuthHookand credential redaction:AuthHook.Applyruns on every request andAuthHook.Challengehandles HTTP401/403to refresh and retry once; unobtainable credentials reportmcp.StatusAuthRequired. The adapter never logs or returns header values, and HTTP errors (including*url.Error) redact userinfo, query parameters, and fragments while preservingerrors.Is/errors.Asinspection.
Timeouts, result caps, elicitation, and live refresh
TimeoutsandMaxResultBytes:ServerConfig.TimeoutsboundsConnect(default30s),Catalog(30s), andCall(2m); negative values disable individual deadlines, while the caller’sctxremains an upper bound.MaxResultBytes(defaultmcp.DefaultMaxResultBytes, 4 MiB) caps combined text, file data, file metadata, and structured payloads delivered to the model, truncating at UTF-8 boundaries and appendingmcp.TruncationMarker.isErrorresponses surface as tool errors.- Elicitation (
WithElicitationHandler): Servers requesting host form or URL input during a tool call invoke yourElicitationHandlerup to bounded rounds; declining, canceling, or omitting a handler declines immediately without blocking and surfaces a tool error. - Catalog refresh &
Reconnect: Registermcp.WithCatalogChangeHandlerto react to servertools,resources, orpromptslist-changed notifications. A running*agent.Agentretains the tools it was constructed with; rebuild new agents/runs fromclient.Tools()when notified. Callclient.Reconnect(ctx, serverName)to replace one server’s session cleanly without disrupting other connected servers.
package main
import (
"log"
"github.com/ijaidev/gojent/mcp"
)
func main() {
client := mcp.New(mcp.WithCatalogChangeHandler(func(change mcp.CatalogChange) {
if change.Err != nil {
log.Printf("%s %s refresh failed: %v", change.Server, change.Kind, change.Err)
return
}
// Rebuild future runs using client.Tools(), client.Resources(), or client.Prompts().
}))
defer func() { _ = client.Close() }()
}
Resources and prompts host APIs
Resources and prompts are host APIs, never model tools. Lists follow pagination automatically, ReadResource maps payloads to llm.TextPart and llm.FilePart, and GetPrompt returns llm.Message slices ready to pass to (*agent.Agent).GenerateMessages or StreamMessages:
package main
import (
"context"
"github.com/ijaidev/gojent/mcp"
)
func loadHostContext(ctx context.Context, client *mcp.Client) error {
resources, err := client.Resources(ctx, "workspace")
if err != nil {
return err
}
if len(resources) > 0 {
contents, err := client.ReadResource(ctx, "workspace", resources[0].URI)
if err != nil {
return err
}
// contents[*].Part is an llm.TextPart or llm.FilePart.
_ = contents
}
templates, err := client.ResourceTemplates(ctx, "workspace")
if err != nil {
return err
}
_ = templates
prompts, err := client.Prompts(ctx, "workspace")
if err != nil {
return err
}
if len(prompts) > 0 {
prompt, err := client.GetPrompt(ctx, "workspace", prompts[0].Name,
map[string]string{"topic": "Go"})
if err != nil {
return err
}
// Pass prompt.Messages to (*agent.Agent).GenerateMessages.
_ = prompt
}
return nil
}
func main() {
_ = loadHostContext
}
See the runnable demo in mcp/examples/stdio and full Go documentation on pkg.go.dev.