Messages API

Purpose and Scope

The Messages API is the main direct prompting surface for Claude in the TypeScript SDK. Use it when an application wants to own the conversation loop, choose the model, pass the current transcript, and decide how to react to Claude’s response. The official Claude docs frame this mode as direct model prompting access, in contrast with Claude Managed Agents, which provide a managed harness for longer asynchronous work. In this repository, the same idea appears in the first getting started sample: create an Anthropic client, call the messages resource, and inspect the returned message content.

Sources: README.md, examples/demo.ts

A message request is intentionally explicit. The caller supplies a model, a maximum output token budget, and a messages array containing conversation turns. The README uses a single user turn that says hello to Claude, while the runnable demo uses the default environment-based client and sends a user message to a Sonnet model. Those examples show the minimum mental model: the SDK does not hide the conversation behind a chat session object; each create call receives the prompt state that should be sent to Claude for that turn.

Sources: README.md, examples/demo.ts

Relevant Source Files

  • README.md — introduces the official TypeScript SDK, installation, supported runtimes, and the canonical getting started call to the messages resource.
  • api.md — generated API documentation for the repository; use it with the typed source exports when checking full request and response details.
  • src/resources/messages/index.ts — re-exports the Messages resource, message request and response types, streaming event types, content block types, tool-related types, token-counting types, and batch types.
  • tests/api-resources/messages/messages.test.ts — exercises create and countTokens with required parameters, optional parameters, and response helper methods.
  • examples/demo.ts — small runnable example that constructs the client from ANTHROPIC_API_KEY and sends a basic message request.

Core Request Shape

At the SDK level, the smallest create request contains a token limit, an array of message turns, and a model identifier. Tests validate that the required parameter set works with a user message containing text content and a Claude model name. The README mirrors that shape and logs the response content. In practice, this means most applications start by building a transcript of alternating user and assistant turns, then pass that transcript in one request. The SDK handles serialization and returns a typed message result rather than a raw fetch response by default.

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

The optional parameter test is useful because it shows the breadth of features carried by the same endpoint. A create request may include cache control, container selection, inference geography, metadata, output configuration, service tier, stop sequences, streaming selection, system instructions, sampling parameters, thinking configuration, tool choice, tool definitions, and user profile selection. Not every application needs these fields at first, but they are part of the same public resource contract, so teams can add structured outputs, tool use, or request attribution without switching to a different resource.

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

Response Handling and SDK Helpers

The messages tests demonstrate that SDK calls return a promise-like API object with multiple ways to consume the result. Awaiting the create call yields the parsed message data, while asResponse exposes the underlying Response object and withResponse returns both the parsed data and raw response together. This is important for production integrations that need headers, status information, or diagnostics alongside the typed result. The default path remains simple for application code, but the helper methods allow infrastructure code to capture transport metadata without reimplementing request handling.

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

Response content is exposed through the message object, and the README’s getting started sample prints the content field directly. The generated messages index also exports many content-related types, including text blocks, document blocks, image parameters, citations, deltas, stop reasons, and output token details. Those exports signal that a response is not limited to one plain string in every scenario. Applications should inspect content blocks according to the capabilities they requested, especially when using tools, citations, structured output, vision, or streaming flows covered by adjacent pages.

Sources: README.md, src/resources/messages/index.ts

System-to-Code Mapping

Reader taskSDK surfaceSource signal
Send a basic Claude promptclient messages create call with model, max token limit, and message turnsREADME.md and examples/demo.ts show minimal user-message calls
Add advanced request behavioroptional fields on the create parameter objecttests/api-resources/messages/messages.test.ts covers cache control, metadata, output config, tools, thinking, and service tier
Count input tokens before generationmessages token counting calltests/api-resources/messages/messages.test.ts includes required and optional count token cases
Use typed content and eventsexported message, block, delta, stream, and tool typessrc/resources/messages/index.ts re-exports the generated type surface
Inspect raw transport detailsresponse helper methods on the request promisetests/api-resources/messages/messages.test.ts validates raw response and combined data response access

API Components

The central resource is the generated Messages export surfaced through the Anthropic client. The index file re-exports Message, MessageParam, ContentBlock, ContentBlockParam, TextBlock, StopReason, RawMessageStreamEvent, MessageDeltaEvent, MessageTokensCount, and many specialized block and tool types. This organization matters for TypeScript users because imports can be written against the public package surface rather than private generated files. It also means that feature-specific pages, such as streaming, tool use, structured outputs, and token counting, share the same type vocabulary as basic message creation.

Sources: src/resources/messages/index.ts

The token counting path belongs beside message creation rather than in a separate unrelated utility. Tests call countTokens with the same core prompt shape of model plus messages, and the optional case repeats several generation-related fields such as cache control, output configuration, and system content. That symmetry lets an application estimate or validate a request before sending it for generation. It is especially useful when prompts are assembled dynamically from documents, retrieved context, user input, tools, or cached system instructions and the application needs predictable budget enforcement.

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

Common Usage Flow

A typical implementation begins with authentication through the Anthropic client, normally using the ANTHROPIC_API_KEY environment variable. The demo constructs the client without an explicit key, documenting the environment default in a comment, then defines an async main function, calls the messages resource, and prints the result. The README shows the same client with an explicit apiKey option using the same environment variable. Together these examples support both quick scripts and server applications that prefer explicit configuration during dependency injection or bootstrapping.

Sources: README.md, examples/demo.ts

After the client exists, build the request from the application state. For a single-turn interaction, add one user message and choose an appropriate model. For multi-turn conversations, send the relevant prior turns in the messages array so Claude has the context it needs. Add top-level system instructions when stable behavior should apply to the whole request. Official docs also describe mid-conversation system messages for supported platforms and models; that pattern is useful when new system-level instructions become relevant later without rewriting the stable prefix of an existing prompt cache strategy.

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

Implementation Details and Edge Cases

The optional create test includes sampling controls such as temperature, top_p, and top_k, while the official Claude docs warn that some newer Opus models reject non-default sampling parameters. Treat the SDK types and tests as the repository’s generated client contract, and treat current model documentation as the source of model-specific constraints. In other words, a field can be part of the SDK request shape while still being invalid for a particular model family or platform. Prefer omitting sampling controls unless the target model documentation says they are supported.

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

The same endpoint also carries advanced features that may change how the response should be processed. Tool definitions can cause Claude to request tool execution rather than only produce natural-language text. Output configuration can ask for JSON schema shaped output. Thinking configuration can affect visible or summarized reasoning behavior. Streaming changes the consumption model from one complete message to event handling. The generated messages index exports the types that these features need, but each feature deserves its own implementation pattern, tests, and error handling strategy.

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

Next Steps

Start with the README or examples demo when validating credentials and the first request. Then read the Messages Resource Reference for method-level details, Streaming Responses for event-oriented generation, Models and Token Counting for budget checks, Structured Outputs for schema-driven responses, and Tool Use Overview when Claude should call application functions. If the task is long-running, asynchronous, or better served by managed infrastructure, compare this direct Messages API flow with the Managed Agents overview before designing the conversation loop.