Claude Code

Agent SDK capability matrix

Permissions, hooks, MCP, SessionStore, cost tracking, OpenTelemetry, secure deployment and cache strategy.

Agent SDK starts the Claude Code loop and coordinates models, tools, permissions, hooks, MCP, sessions and telemetry. This page organizes the detailed official SDK documentation into a production capability matrix.

For custom tools, prompts, streaming, structured output, approvals and SDK slash commands, see runtime patterns.

Use the CLI for a person working in a terminal. SDK permission, session, observability and isolation design matters when embedding agents in products, CI, background jobs or multitenant services.

#Capability overview

CapabilityProblem solvedProduction concern
Permission modesControl automatic executionallowedTools preapproves; it does not define the entire inventory
canUseToolRuntime user or business approvalUnderstand rules that can resolve requests before the callback
HooksIntercept tools, lifecycle and stoppingPrefer PreToolUse for mandatory auditing and blocking
MCPInternal APIs, databases, browsers and SaaSUse tool search for large catalogs; control auth and output size
SessionStoreCross-host transcript recoveryDoes not store workspaces, CLAUDE.md or checkpoint blobs
Cost trackingTokens, model usage and estimatesClient estimates are not final bills
OpenTelemetryMetrics, logs and tracesNever use console exporters on SDK stdout
Secure deploymentFile, network, credential and tenant isolationSeparate cwd, config, environment and egress per tenant

#Permission evaluation order

SDK tool requests follow this order:

OrderLayerResult
1HooksCan deny, record or rewrite input
2Deny rulesMatching scoped rules such as Bash(rm *) block even in bypass mode
3Ask rulesDelegate to canUseTool for user/business approval
4Permission modeGlobal bypassPermissions, acceptEdits, plan, dontAsk policies
5Allow rulesMatching requests are approved automatically
6canUseToolInvoked only if unresolved above

Common misconceptions:

ConfigurationActual behavior
allowedTools: [Read] + bypassPermissionsRead is allowed; other tools can still pass through bypass
disallowedTools: [Bash]Removes Bash's definition entirely
disallowedTools: [Bash(rm *)]Bash remains visible but matching commands are blocked
dontAsk with a small allowlistSuitable for read-only or narrow tasks; other actions denied
Relying only on canUseToolEarlier rules or modes may approve without calling it

#Use hooks

Hooks place security, audit and business rules before or after model actions.

ScenarioRecommendation
Block dangerous commandsInspect Bash in PreToolUse and deny matches
Audit every toolRecord tool, session, agent and result summary before/after use
Format or validate filesRun formatters/tests after Edit or Write
Inject short-lived credentialsExternal broker injects before execution; keep long-lived secrets out of prompts
Notify on completionStop/completion events can trigger messages, webhooks or ticket updates

A hook's allow does not bypass later deny, ask or permission rules. Put mandatory checks in PreToolUse rather than only canUseTool.

#Connect MCP

MCP supplies external tools. Plan production transport, authentication and output limits according to catalog size.

Design areaRecommendation
Transportstdio locally; HTTP/SSE/WebSocket remotely
AuthOAuth or short-lived tokens; no secrets in prompts or repositories
Tool searchEnable for large inventories instead of sending every schema upfront
Output sizeBound results; provide pagination or summaries
Human approvalrequires-user-interaction or ask rules for high-risk tools
GatewayVerify tool search/deferred tools forwarding to avoid cache misses

Tool output becomes conversation context. Long logs, full-table queries and complete HTML increase subsequent costs.

#SessionStore

Transcripts default to ~/.claude/projects/. SessionStore can mirror them to S3, Redis, a database or a custom backend so another worker can resume.

MethodRequired?Purpose
appendYesAppend entries externally after local transcript writes
loadYesLoad history before resume
listSessionsOptionalList or continue recent sessions
deleteOptionalDelete a session; append-only stores may implement a no-op
listSubkeysOptionalRestore subagent transcripts

Boundaries:

Not managed by SessionStoreYour responsibility
Workspace filesPersistent volumes, object storage or per-task directories
CLAUDE.md and auto memoryIsolate or disable separately
Checkpoint blobsPersist separately for cross-host rewind
MCP server stateManaged by the server/external service

Monitor mirror_error. The agent may keep running after external append failure, while recovery is already incomplete.

#Cost tracking

The message stream exposes per-step and per-model usage plus a total estimate at query completion.

Field/conceptPurpose
Assistant usageInput/output tokens per step
Result total_cost_usdClient-side estimate for one query
Result model_usagePer-model accounting for multiple models or fallback
cache_creation_input_tokensInputs written to cache this turn
cache_read_input_tokensInputs read from cache this turn

Parallel tool calls may produce multiple assistant messages sharing one message ID and usage. Deduplicate by ID for step-level accounting.

SDK costs are local estimates affected by version, model recognition and price updates. Use them for observability and budget alerts, not as the sole basis for customer billing or settlement.

#OpenTelemetry

Enable OTLP in production to connect agent execution to existing observability.

CLAUDE_CODE_ENABLE_TELEMETRY=1
CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1
OTEL_TRACES_EXPORTER=otlp
OTEL_METRICS_EXPORTER=otlp
OTEL_LOGS_EXPORTER=otlp
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.example.com:4318
SignalWhat it shows
MetricsSessions, tokens, costs, tool decisions and changed lines
Log eventsPrompt/API/tool/error summaries
TracesModel, tool, hook and agent-step latency chains

SDK subprocess communication uses stdout/stderr. A console OTEL exporter can contaminate that channel; do not use it.

#Secure deployment

Agents read files, execute commands, access networks and call services. Use least privilege, isolation and layered controls.

ResourceControl
FilesystemSeparate cwd per tenant/task; read-only mounts where appropriate
NetworkEgress allowlists, proxies or offline sandboxes
CredentialsBroker-injected short-lived credentials rather than long-lived keys
SettingssettingSources: [] with explicit options for multitenancy
Config directoryPer-tenant CLAUDE_CONFIG_DIR
Auto memoryDisable in shared environments with CLAUDE_CODE_DISABLE_AUTO_MEMORY=1
ProcessDocker, sandbox-runtime, gVisor, Firecracker or CI isolation

Treat prompt injection as part of the normal threat model for uploads, websites, issues and READMEs. Network and credential boundaries are more dependable than assuming the model will ignore malicious instructions.

#Five-minute / one-hour cache strategy

SDK scenarioRecommendation
Single query()Steps reuse prefixes naturally; avoid switching model/effort mid-run
Repeated query() with resumeSame session, model and effort improve reuse
Multiple workers with SessionStoreTranscript recovery does not guarantee provider cache beyond TTL or across keys
API key / Passion8 / Bedrock / VertexDesign around a five-minute default TTL
Claude subscriptionPlans commonly support one-hour intervals
Many MCP toolsTool search stabilizes prefixes and avoids full schema repetition
Permission/settings changesChanged tools/system prefixes may rebuild cache
SubagentsIndependent contexts and caches; cost scales with agent count

Translate /usage into telemetry and business metrics by tenant, session, agent, model, tool and cache reads/writes.

#Official references

Support

Need help?

For setup, billing, or model issues, email us. Check the status page for uptime.

WeChat / QQ support is available at the bottom right.