Messages Resource Reference

Purpose and Scope

The stable Messages resource is the primary SDK surface for direct Claude prompting in @anthropic-ai/sdk. It is the API you use when you want application-controlled conversation state, custom agent loops, explicit tool orchestration, streaming, token counting, or structured output parsing rather than the managed infrastructure of Claude Managed Agents. In code, callers normally access it as client.messages, create a request with model, max_tokens, and messages, and then inspect the returned assistant message content. The repository tests exercise this surface as a first-class generated resource rather than as a README-only convenience path.

Sources: src/resources/messages/index.ts, tests/api-resources/messages/messages.test.ts, tests/resources/messages/parse.test.ts, api.md

The Messages API request model is conversation-oriented. A messages array supplies turns such as { role: 'user', content: 'Hello, world' }, while top-level fields control generation, output limits, tools, cache behavior, and system instructions. Official Claude docs describe this API as best suited for fine-grained control and custom agent loops. That framing matches the SDK tests: the stable resource focuses on direct request construction and response handling, while Managed Agents live under beta resources elsewhere in the package family.

Sources: tests/api-resources/messages/messages.test.ts, src/resources/messages/index.ts

Relevant Source Files

  • src/resources/messages/index.ts - Barrel export for the stable messages namespace. It re-exports Messages, message batch support, and a large set of request, response, streaming, tool, citation, document, code execution, JSON output, thinking, usage, and token-counting types.
  • tests/api-resources/messages/messages.test.ts - Generated API resource tests for client.messages.create() and client.messages.countTokens(), including required-only calls, optional parameter coverage, and response wrapper helpers.
  • tests/resources/messages/parse.test.ts - Focused tests for Messages.parse(), including Zod-backed structured output parsing, request forwarding to /v1/messages, non-enumerable parsed output attachment, and validation failure behavior.
  • api.md - Repository API reference source path for generated public API documentation associated with the SDK surface.

Public Entry Points

The stable entry point is client.messages, reached from an Anthropic client instance imported from @anthropic-ai/sdk. The generated tests construct that client with an explicit apiKey and a test baseURL, then call client.messages.create() and client.messages.countTokens(). These tests also verify the Stainless response helper contract: the returned promise can be awaited for parsed data, .asResponse() yields the raw Response, and .withResponse() returns both the parsed data and raw response object. That means production code can choose a high-level or transport-aware style without changing the request payload.

Sources: tests/api-resources/messages/messages.test.ts

The messages namespace is also a type hub. The barrel export exposes Messages plus core message types such as Message, MessageParam, ContentBlock, ContentBlockParam, TextBlock, StopReason, Metadata, and Model. It also exports specialized types for citations, documents, images, PDFs, containers, server tool use, code execution tool results, memory tools, thinking blocks, output configuration, JSON output formats, token counts, raw stream events, and deltas. This breadth is important for TypeScript users: the resource is not only a method container, but also the canonical import location for many compile-time contracts around message construction and interpretation.

Sources: src/resources/messages/index.ts

Method Reference

MethodPurposeRequired fields shown in testsNotable behavior
client.messages.create(params)Create a Claude message response from a conversation request.model, max_tokens, messagesSupports raw response helpers and a broad optional request shape.
client.messages.countTokens(params)Count tokens for a prospective message request.model, messagesUses the same response helper pattern as create in generated tests.
messages.parse(params)Create a message and parse structured text output according to an output format helper.model, max_tokens, messages, output_config.format in the parse testCalls /v1/messages, validates parsed output, and throws on schema mismatch.

The create test demonstrates the minimal request shape: model: 'claude-opus-4-6', max_tokens: 1024, and one user message. The optional-parameter test is more valuable as a reference because it shows the stable resource accepting modern Claude request features in a single payload. Those include ephemeral cache control, a container identifier, inference geography, user metadata, JSON-schema output configuration, service tier, stop sequences, stream: false, rich system text blocks with citations, thinking configuration, tool choice, custom tools, sampling fields, and a user_profile_id. Some model families may reject particular sampling options according to product documentation, so application code should treat these as SDK request fields rather than a guarantee that every model accepts every value.

Sources: tests/api-resources/messages/messages.test.ts

Request Shape and Type Surface

A message request is built from a few stable primitives. messages carries the conversation turns, model selects the Claude model, and max_tokens bounds the generated output for creation. Optional system instructions can be supplied as text blocks, and official Claude docs also describe mid-conversation system messages as a way to append a system-role instruction later in the message sequence without rewriting an earlier cached prefix. The SDK export list includes MidConversationSystemBlockParam, which indicates that this pattern is represented in the generated TypeScript surface alongside ordinary message and content block types.

Sources: src/resources/messages/index.ts, tests/api-resources/messages/messages.test.ts

Tool and output features are represented as typed request fragments rather than separate ad hoc APIs. The optional create test defines a custom tool with name, description, input_schema, allowed_callers, defer_loading, eager_input_streaming, input_examples, strict, and type: 'custom', then pairs it with tool_choice. Output shaping appears through output_config, where the test uses effort: 'low' and a JSON Schema format. The barrel export mirrors this by exposing types for JSON output formats, tool use blocks, server tool callers, code execution tools, and tool result blocks.

Sources: src/resources/messages/index.ts, tests/api-resources/messages/messages.test.ts

Structured Output Parsing

Messages.parse() is a helper-oriented path for callers who want validated structured data rather than only raw assistant text. The parse test builds a Zod schema with city, temperature, and conditions, wraps it with zodOutputFormat(), and sends that format inside output_config. The mocked transport receives a POST to /v1/messages with the expected model, token limit, messages, and JSON-schema output format. After the mock response returns a text content block containing JSON, the helper exposes a top-level parsed_output object matching the schema.

Sources: tests/resources/messages/parse.test.ts

The parse behavior deliberately preserves the original message shape. The test checks that result.content[0] still looks like a normal text block containing the JSON string, while the parsed value is attached separately. It also notes that parsed_output on the content block is non-enumerable, so consumers should read it intentionally rather than expecting it to appear during ordinary object enumeration. A second test supplies JSON that does not satisfy the schema and expects the call to reject, which is the right failure mode for workflows that depend on typed downstream data.

Sources: tests/resources/messages/parse.test.ts

Usage Patterns

import Anthropic from '@anthropic-ai/sdk';
 
const client = new Anthropic({
  apiKey: process.env['ANTHROPIC_API_KEY'],
});
 
const message = await client.messages.create({
  model: 'claude-opus-4-6',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Hello, Claude' }],
});
 
console.log(message.content);

Use create() when you need a generated assistant message and want to own the conversation loop in your application. Use countTokens() before sending or replaying a request when token budgeting matters, especially for long prompts, tool definitions, documents, or cached-prefix designs. Use parse() when the assistant’s text is expected to be machine-readable JSON and you want the SDK helper to validate that output against a schema. These paths can coexist: a production workflow might count a request, create a response, and reserve parsing for the subset of turns that require structured data.

Sources: tests/api-resources/messages/messages.test.ts, tests/resources/messages/parse.test.ts

Testing Signals and Next Steps

The tests provide strong signals about the public contract. Generated resource tests verify that create() and countTokens() accept required parameters, support optional parameters, and return values compatible with Stainless response helpers. The parse tests verify helper behavior below the public client level by mocking the transport and asserting the exact endpoint path, request body shape, parsed result, and validation error handling. Together, these tests show that the stable Messages resource is both a generated API client surface and a convenience layer for structured-output workflows.

Sources: tests/api-resources/messages/messages.test.ts, tests/resources/messages/parse.test.ts

For broader usage guidance, read the pages on the Messages API, streaming responses, models and token counting, structured outputs, and tool use. If you are deciding between direct prompting and managed infrastructure, compare this resource with the Managed Agents overview: Messages gives you direct model access and control over state, while Managed Agents provide an agent harness for long-running asynchronous work. For implementation work in this repository, start with the exported types in src/resources/messages/index.ts, then confirm behavioral expectations in the resource and parse tests before adding examples or higher-level helpers.