config

package
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 19, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

README

Examples

These programs exercise agent-sdk-go (github.com/agenticenv/agent-sdk-go). Agents run as Temporal workflows, so a running Temporal service is mandatory for every example below.

Prerequisite: These examples use agent-sdk-go on the Temporal runtime. A running Temporal server is required before you run them. See Temporal setup for Docker, Temporal CLI, ports, Cloud, and self-hosted options.

Default connection

The examples use TEMPORAL_HOST, TEMPORAL_PORT, and TEMPORAL_NAMESPACE from .env (default: localhost, 7233, default). Adjust if your Temporal runs elsewhere.

Examples overview

Example What it demonstrates
simple_agent Minimal agent, no tools — Temporal config, system prompt, LLM client, single Run(); prints AgentResponse.Usage (token counts) when the provider reports them
agent_with_temporal_client Caller-owned Temporal client — WithTemporalClient + WithTaskQueue; create and close client yourself (TLS, API key, Cloud)
agent_with_conversation In-memory conversation with WithConversation — multi-turn context, same conversationID for Run
agent_with_tools Built-in tools (echo, calculator, weather, wikipedia, search) with auto-approval
agent_with_stream Streaming with Stream + partial content (content_delta, tool_call, complete); prints aggregated token usage on complete
agent_with_stream_conversation Stream + conversation; event handling to avoid duplicate output (ContentDelta vs Complete)
agent_with_tools_approval Tools + WithApprovalHandler — user approves or rejects each tool run (Run only)
agent_with_run_async RunAsyncresultCh + approvalCh; use req.Respond (no WithApprovalHandler)
agent_with_custom_tools Custom tools via WithTools — implementing interfaces.Tool
agent_with_tool_authorizer Custom tool authorization via interfaces.ToolAuthorizer — denied calls surface as tool_result with denied status
multiple_agents Multiple agents with WithInstanceId — sequential or concurrent
agent_with_subagents Main agent + math specialist — WithSubAgents, separate task queues
agent_with_json_response Structured LLM output — WithResponseFormat + interfaces.JSONSchema (JSON with schema; no tools)
agent_with_reasoning Generic interfaces.LLMReasoning via WithLLMSamplingStream to observe thinking_delta (e.g. Anthropic)
agent_with_worker Agent and worker in separate processes — DisableLocalWorker + NewAgentWorker; agent uses Stream
durable_agent Same split-process layout — agent uses Stream (WithStream); durability scenarios: durable_agent/README.md
agent_with_mcp_config MCP via WithMCPConfig — transport from env: mcp.MCPStdio (command, JSON args/env) or mcp.MCPStreamableHTTP (URL, optional bearer/OAuth); see examples/env.sample
agent_with_mcp_client Same transports via mcpclient.NewClient + WithMCPClients; same env vars as agent_with_mcp_config

Setup

cp env.sample .env
# Edit .env: set LLM_APIKEY, LLM_MODEL (see LLM_PROVIDER: openai, anthropic, or gemini)

Run examples

Minimal agent (no tools)
go run ./simple_agent "Hello, what can you do?"
Agent with caller-owned Temporal client

Uses WithTemporalClient and WithTaskQueue. The example creates the Temporal client, passes it to the agent, and closes it when done. Use this pattern for TLS, Temporal Cloud API keys, or other connection options.

go run ./agent_with_temporal_client "Hello, what can you do?"
Agent with conversation (multi-turn)

Uses in-memory conversation. Run interactive mode (no args) for multi-turn in one process—history is shared across turns. With args, runs a single turn (useful for testing).

# Interactive: type prompts, get responses; history shared. Type 'exit' to end.
go run ./agent_with_conversation

# Single turn (new process each run; no shared history)
go run ./agent_with_conversation "Hello, remember I'm Alice"
Agent with tools
go run ./agent_with_tools "What's the weather in Tokyo?"
Streaming (partial content as tokens arrive)
go run ./agent_with_stream "What's the current time and what's 17 * 23?"
Structured JSON response (WithResponseFormat)

Uses agent.WithResponseFormat with interfaces.ResponseFormatJSON, Name, and interfaces.JSONSchema. No tools—keeps the run in structured-output mode. Prints validated, indented JSON.

go run ./agent_with_json_response
go run ./agent_with_json_response "What is the capital of Japan?"
Reasoning / thinking (WithLLMSampling + LLMReasoning)

Sets WithLLMSampling with Reasoning: &interfaces.LLMReasoning{Enabled, Effort, BudgetTokens} and uses Stream so you can see thinking_delta events when the provider emits them (e.g. Anthropic extended thinking). Pick a model that supports reasoning/thinking for your LLM_PROVIDER.

go run ./agent_with_reasoning
go run ./agent_with_reasoning "Why is the sky blue? One short paragraph."
Streaming + conversation (event handling pattern)

Interactive multi-turn with Stream. Demonstrates how to handle ContentDelta/Content and Complete to avoid printing the same text twice.

go run ./agent_with_stream_conversation
go run ./agent_with_stream_conversation "What is 5 * 8?"
Sub-agents (main agent + specialist)

Two agents in one process: main agent with a math specialist registered via WithSubAgents. Requires workers on both task queues (each NewAgent starts its own embedded worker). Main agent uses default tool approval (RequireAll): delegating to the specialist prompts on stdin (y / n). Specialist uses AutoToolApprovalPolicy so calculator does not prompt. Same stdin pattern as agent_with_tools_approval.

go run ./agent_with_subagents "What is 987 times 654?"
Tools + approval, custom tools, multiple agents, worker split
go run ./agent_with_tools_approval "What is 15 + 27?"
go run ./agent_with_run_async "What is 15 + 27?"
go run ./agent_with_custom_tools "Reverse 'hello world'"
go run ./agent_with_tool_authorizer "Get the protected note for roadmap."
go run ./multiple_agents "What is 7 times 8?"
go run ./multiple_agents concurrent "What is 7 times 8?"

# Agent and worker in separate processes: two terminals — worker in terminal 1,
# agent in terminal 2 (after the worker is up).
go run ./agent_with_worker/worker    # terminal 1: worker
go run ./agent_with_worker/agent "Hello from remote agent!"   # terminal 2: agent

# durable_agent: same two-terminal flow; streaming REPL. Scenarios:
# durable_agent/README.md
go run ./durable_agent/worker       # terminal 1
go run ./durable_agent/agent "Hello from remote agent!"   # terminal 2
MCP (WithMCPConfig vs WithMCPClients)

Two examples use the same env-driven transport but wire the agent differently:

  • agent_with_mcp_configagent.WithMCPConfig(agent.MCPServers{<serverName>: mcpCfg}). The SDK builds the default MCP client per server.
  • agent_with_mcp_clientmcpclient.NewClient(<serverName>, transport, opts...) then agent.WithMCPClients(client).

Transport must be set explicitly with MCP_TRANSPORT: stdio or streamable_http (see aliases in env.sample). See env.sample for every variable.

  • Remote — streamable_http: set MCP_STREAMABLE_HTTP_URL. Auth optional: MCP_BEARER_TOKEN, or OAuth trio MCP_CLIENT_ID + MCP_CLIENT_SECRET + MCP_TOKEN_URL (OAuth wins over bearer when all three are set). MCP_SKIP_TLS_VERIFY=true for dev TLS only.
  • Local — stdio: set MCP_STDIO_COMMAND and optional MCP_STDIO_ARGS (JSON string array) and MCP_STDIO_ENV (JSON string→string object).

Shared optional knobs: MCP_SERVER_NAME, MCP_TIMEOUT_SECONDS, MCP_RETRY_ATTEMPTS, MCP_ALLOW_TOOLS / MCP_BLOCK_TOOLS (comma-separated; only one list type).

go run ./agent_with_mcp_config
go run ./agent_with_mcp_config "List tools you can call."

go run ./agent_with_mcp_client
go run ./agent_with_mcp_client "List tools you can call."

Logging

Examples send conversation (user prompt, assistant response) to stdout and internal logs to stderr. By default only errors are logged.

  • See logs while evaluating: Set LOG_LEVEL=info or LOG_LEVEL=debug in .env, or run:
    LOG_LEVEL=debug go run ./simple_agent "Hello, what can you do?"
    
  • Save logs to a file: Redirect stderr to a file:
    LOG_LEVEL=info go run ./simple_agent "Hello" 2>debug.log
    
  • Suppress logs: Show only conversation output:
    go run ./simple_agent "Hello" 2>/dev/null
    

Env vars

Env var Description
TEMPORAL_HOST, TEMPORAL_PORT, TEMPORAL_NAMESPACE, TEMPORAL_TASKQUEUE Temporal connection
LLM_PROVIDER openai, anthropic, or gemini (see env.sample)
LLM_APIKEY API key
LLM_MODEL e.g. gpt-4o, claude-3-5-sonnet-20241022
LLM_BASEURL Optional (custom/proxy endpoints)
LOG_LEVEL error (default), warn, info, debug — logs go to stderr
SERPER_API_KEY For search tool
MCP_TRANSPORT Required for MCP examples: stdio or streamable_http (aliases: local, http, remote, …)
MCP_SERVER_NAME Optional server id for wiring (defaults: local for stdio, remote for HTTP)
MCP_STREAMABLE_HTTP_URL Remote MCP base URL (required for streamable_http)
MCP_STDIO_COMMAND Executable for local subprocess MCP (required for stdio)
MCP_STDIO_ARGS Optional JSON array of argv strings, e.g. ["-y","@scope/pkg","/dir"]
MCP_STDIO_ENV Optional JSON object of extra subprocess env vars
MCP_BEARER_TOKEN Optional static bearer for MCP HTTP; ignored when OAuth env trio is all set
MCP_TIMEOUT_SECONDS Optional; positive seconds cap MCP connect+RPC timeout
MCP_RETRY_ATTEMPTS Optional; max attempts per MCP operation when > 0
MCP_ALLOW_TOOLS, MCP_BLOCK_TOOLS Optional comma-separated allow/block tool lists (mutually exclusive)
MCP_CLIENT_ID, MCP_CLIENT_SECRET, MCP_TOKEN_URL Optional together: OAuth2 client credentials for MCP HTTP transport
MCP_SKIP_TLS_VERIFY Optional; set to true to skip TLS verify for MCP/token HTTP (dev only)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyMCPStreamableHTTPAuth added in v0.1.2

func ApplyMCPStreamableHTTPAuth(transport *mcp.MCPStreamableHTTP, m *MCPSettings)

ApplyMCPStreamableHTTPAuth sets optional auth on transport from m and process env. Unauthenticated MCP (URL only) is valid. When the OAuth trio is set, OAuth is used; otherwise m.BearerToken sets a bearer token when non-empty. MCP_SKIP_TLS_VERIFY=true sets SkipTLSVerify.

func FormatNewAgentError added in v0.1.3

func FormatNewAgentError(prefix string, err error) string

FormatNewAgentError formats errors from [agent.NewAgent] or [agent.NewAgentWorker] for log output when running examples from a clone of this repository. It appends a pointer to temporal-setup.md when the failure is a Temporal connection or namespace timeout from this SDK.

func MCPDefaultServerName added in v0.1.2

func MCPDefaultServerName(cfg *Config) string

MCPDefaultServerName returns MCP_SERVER_NAME or a default from transport (local / remote).

func MCPLoadTransport added in v0.1.2

func MCPLoadTransport(cfg *Config) (mcp.MCPTransportConfig, error)

MCPLoadTransport builds mcp.MCPStdio or mcp.MCPStreamableHTTP from cfg and process env. streamable_http requires MCP_STREAMABLE_HTTP_URL. stdio requires MCP_STDIO_COMMAND; optional MCP_STDIO_ARGS (JSON array) and MCP_STDIO_ENV (JSON object).

func MCPToolFilterFromConfig added in v0.1.2

func MCPToolFilterFromConfig(cfg *Config) (mcp.MCPToolFilter, error)

MCPToolFilterFromConfig returns allow/block lists from comma-separated MCP_ALLOW_TOOLS / MCP_BLOCK_TOOLS.

func MCPUsesOAuthFromEnv added in v0.1.2

func MCPUsesOAuthFromEnv() bool

MCPUsesOAuthFromEnv reports whether OAuth2 client-credentials env vars are all non-empty.

func NewLLMClientFromConfig

func NewLLMClientFromConfig(cfg *Config) (interfaces.LLMClient, error)

NewLLMClientFromConfig creates an LLM client from config using the new llm.Option-based API. BaseURL is applied only for OpenAI; set LLM_BASEURL when using a non-default OpenAI-compatible API.

func NewLoggerFromLogConfig

func NewLoggerFromLogConfig(cfg *Config) logger.Logger

NewLoggerFromLogConfig returns logger.Logger for use with the agent. Logs to stderr so conversation (stdout) stays separate; set LOG_LEVEL=info or debug to see logs.

Types

type Config

type Config struct {
	Host      string
	Port      int
	Namespace string
	TaskQueue string
	LogLevel  string
	Provider  interfaces.LLMProvider
	APIKey    string
	Model     string
	// BaseURL is optional and only used for the OpenAI client (custom or Azure-compatible endpoints).
	// Ignored for Anthropic and Gemini.
	BaseURL string

	MCP MCPSettings
}

func LoadFromEnv

func LoadFromEnv() *Config

LoadFromEnv loads config from environment variables. .env is loaded on package init if present.

func (*Config) MCPTimeout added in v0.1.2

func (cfg *Config) MCPTimeout() time.Duration

MCPTimeout returns cfg.MCP.TimeoutSeconds as a duration, or zero if unset (applies to any MCP transport).

type MCPSettings added in v0.1.2

type MCPSettings struct {
	// Transport is required for MCPLoadTransport: stdio or streamable_http (aliases: local; http, remote, streamable).
	Transport string
	// StreamableHTTPURL is the remote MCP endpoint when transport is streamable_http.
	StreamableHTTPURL string
	// StdioCommand is the executable for MCP stdio transport (required when transport is stdio).
	StdioCommand string
	// StdioArgsRaw is JSON array of strings for subprocess argv, e.g. ["-y","@scope/mcp-server","/data"].
	StdioArgsRaw string
	// StdioEnvRaw is JSON object of extra env vars for the subprocess, e.g. {"API_KEY":"..."}.
	StdioEnvRaw string
	// BearerToken is an optional static bearer for MCP HTTP. Ignored when OAuth env trio is all set.
	BearerToken string
	// Name is the stable server id for this MCP connection (empty defaults to local for stdio, remote for HTTP).
	Name string
	// RetryAttempts is max connect+RPC attempts per operation when > 0; zero uses SDK default.
	RetryAttempts int
	// AllowTools is comma-separated tool names to allow-list (optional); mutually exclusive with BlockTools in validation.
	AllowTools string
	// BlockTools is comma-separated tool names to block-list (optional).
	BlockTools string
	// TimeoutSeconds caps each MCP connect+RPC attempt when > 0 (seconds). Zero uses SDK defaults.
	TimeoutSeconds int
}

MCPSettings holds MCP_* environment values for agent_with_mcp_* examples. This is not github.com/agenticenv/agent-sdk-go/pkg/agent.MCPConfig (per-server agent transport + filter).

Directories

Path Synopsis
agent_with_run_async demonstrates RunAsync: result and approval channels without WithApprovalHandler or Stream.
agent_with_run_async demonstrates RunAsync: result and approval channels without WithApprovalHandler or Stream.
agent_with_temporal_client demonstrates using WithTemporalClient to pass a pre-configured Temporal client to the agent.
agent_with_temporal_client demonstrates using WithTemporalClient to pass a pre-configured Temporal client to the agent.
agent_with_worker
agent command
Interactive streaming REPL for the agent_with_worker example.
Interactive streaming REPL for the agent_with_worker example.
worker command
durable_agent
agent command
Interactive streaming REPL for the durable_agent example.
Interactive streaming REPL for the durable_agent example.
worker command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL