Skip to main content
MCPAgent connects a LangChain-compatible chat model to MCP servers. It discovers MCP tools, resources, and prompts, exposes them as LangChain tools, runs a multi-step agent loop, and returns either a string or a Zod-validated structured result. Related source files: types.ts, remote.ts, and agents/index.ts.
Import agent-specific exports from @mcp-use/agent:

Constructor

Creates an MCP agent. The constructor supports explicit mode, where you provide a model and MCPClient or connectors, and simplified mode, where you provide a "provider/model" string and mcpServers configuration. Parameters
MCPAgentOptions
required
Agent configuration. Use either ExplicitModeOptions or SimplifiedModeOptions.
Returns
MCPAgent
Signature

Simplified mode

In simplified mode, MCPAgent creates the MCPClient and LLM during initialize(). The llm value must use the "provider/model" format.

Explicit mode

In explicit mode, you create the model and client yourself. Use this mode when you need full control over the LLM instance, client lifecycle, connectors, callbacks, or server manager.

Methods

getPackageVersion

Returns the installed mcp-use package version. Returns
string
Signature

initialize

Connects to MCP servers, creates LangChain tools, builds the system message, configures observability callbacks, and creates the underlying LangChain agent executor. In simplified mode, this also creates the MCPClient and LLM from the constructor options. Returns
Promise<void>
Signature
run() initializes the agent when connector management is enabled. Call initialize() yourself when you want explicit lifecycle control before stream(), streamEvents(), or repeated runs.

run

Runs a prompt to completion and returns the final result. Without a schema, the result is a string. With a Zod schema, the result is parsed and returned as the schema’s inferred type. Parameters
string
required
User request to send to the agent.
number
default:"constructor maxSteps"
Maximum model-call steps for this run. The constructor default is 5.
boolean
default:"true"
Whether the agent should initialize connections before the run and clean up connector-only runs after completion.
BaseMessage[]
default:"undefined"
Additional LangChain-formatted history for this run. The native agent places stored memory first (when enabled), then externalHistory, messages, and the current prompt. Supplying it does not clear or replace stored memory.
ZodSchema<T>
default:"undefined"
Schema for structured output. When present, run() returns Promise<T>.
AbortSignal
default:"undefined"
Abort signal passed to the underlying LangChain execution.
Returns
Promise<string | T>
Example
Signature
The positional overloads (run(query, maxSteps, manageConnector, externalHistory, outputSchema, signal)) are still supported for compatibility, but they are deprecated. Prefer the options object form.

stream

Streams high-level agent steps and returns the final answer as the async generator’s return value. Each yielded step represents a tool call. Tool observations are logged internally and may be empty in the yielded object. Parameters
RunOptions<T>
required
Same options object accepted by run.
Yields
string
Name of the tool the agent called.
any
Arguments passed to the tool.
string
Short text description of the tool call.
string
Tool observation text when available.
Returns
AsyncGenerator<AgentStep, string | T, void>
Example
Signature

streamEvents

Streams low-level LangChain StreamEvent objects from the underlying agent executor. Use this method for token streaming, detailed progress UIs, and custom event handling. Parameters
RunOptions<T>
required
Same options object accepted by run.
Returns
AsyncGenerator<StreamEvent, void, void>
Example
Signature

prettyStreamEvents

Streams low-level events through the built-in terminal formatter. This method is intended for CLIs and local development output. Parameters
RunOptions<T>
required
Same options object accepted by run.
Returns
AsyncGenerator<void, string, void>
Example
Signature

getConversationHistory

Returns a copy of the current conversation history. Conversation memory is enabled by default. Returns
BaseMessage[]
Signature

clearConversationHistory

Clears stored conversation history. When memory is enabled and a system message exists, the system message is preserved. Returns
void
Signature

getSystemMessage

Returns the active LangChain SystemMessage, or null before initialization when no system message has been created. Returns
SystemMessage | null
Signature

setSystemMessage

Replaces the active system message. If the agent is already initialized and tools are loaded, the underlying agent executor is recreated with the new message. Parameters
string
required
System message content.
Returns
void
Signature

setDisallowedTools

Sets the list of tool names that should not be exposed to the agent. If the agent is already initialized, reinitialize the agent for the change to affect generated tools. Parameters
string[]
required
Tool names to hide from the agent.
Returns
void
Signature

getDisallowedTools

Returns the current disallowed tool name list. Returns
string[]
Signature

setMetadata

Merges metadata into the current observability metadata. Keys are sanitized by replacing unsupported characters with underscores. Object values are serialized for validation and large serialized values are truncated. Parameters
Record<string, any>
required
Serializable key-value pairs to attach to observability traces.
Returns
void
Signature

getMetadata

Returns a copy of the current observability metadata. Returns
Record<string, any>
Signature

setTags

Adds tags to observability traces. Tags are sanitized, deduplicated, and limited to 50 characters. Parameters
string[]
required
Tags to attach to observability traces.
Returns
void
Signature

getTags

Returns a copy of the current observability tags. Returns
string[]
Signature

flush

Flushes observability traces through the configured ObservabilityManager. Use this in serverless functions before the function exits. Returns
Promise<void>
Signature

close

Closes agent resources, shuts down observability handlers, clears tools and the executor, closes the client or disconnects direct connectors, and marks the agent as uninitialized. Returns
Promise<void>
Signature

Properties

toolsUsedNames

Public array of tool names called during agent execution. The array is appended to as runs execute. Type

observabilityManager

Public ObservabilityManager instance used to create callbacks, flush traces, and shut down observability integrations. Type

Types

MCPAgentOptions

Union of explicit and simplified constructor options. Signature

ExplicitModeOptions

Options for constructing an agent from a pre-instantiated LLM plus an MCPClient or direct connectors. Fields
LanguageModel
required
LangChain-compatible chat model instance.
MCPClient
MCP client. Required when connectors is omitted and required for useServerManager.
BaseConnector[]
Direct connectors. Required when client is omitted.
number
Default maximum agent steps. Defaults to 5.
boolean
Initialize automatically when a run starts and connector management did not initialize the agent. Defaults to false.
boolean
Store conversation history across runs. Defaults to true.
string | null
System prompt override. Defaults to null.
string | null
Template override used when generating the system message from tools. Defaults to null.
string | null
Extra instructions appended to the generated system prompt. Defaults to null.
string[]
Tool names to hide from the agent. Defaults to [].
StructuredToolInterface[]
Extra LangChain tools to add after MCP tools are created. Defaults to [].
string[]
Initial tool usage list. Defaults to [].
boolean
Expose MCP resources as tools. Defaults to true.
boolean
Expose MCP prompts as tools. Defaults to true.
boolean
Use ServerManager tools instead of exposing all server tools directly. Defaults to false.
boolean
Enable verbose observability output. Defaults to false.
boolean
Enable observability callback setup. Defaults to true.
LangChainAdapter
Custom adapter for converting MCP tools, resources, and prompts to LangChain tools.
(client: MCPClient) => ServerManager
Factory for custom server manager instances.
BaseCallbackHandler[]
Custom LangChain callback handlers.
Signature

SimplifiedModeOptions

Options for constructing an agent from an LLM string and MCP server configuration. The agent creates the LLM and client internally during initialization. Fields
string
required
LLM identifier in "provider/model" format, such as "openai/gpt-4o" or "anthropic/claude-sonnet-4-6".
Record<string, MCPServerConfig>
required
MCP server connection configuration keyed by server name.
LLMConfig
Provider-specific LLM configuration such as apiKey, temperature, maxTokens, and topP.
number
Default maximum agent steps. Defaults to 5.
boolean
Initialize automatically when a run starts and connector management did not initialize the agent. Defaults to false.
boolean
Store conversation history across runs. Defaults to true.
string | null
System prompt override. Defaults to null.
string | null
Template override used when generating the system message from tools. Defaults to null.
string | null
Extra instructions appended to the generated system prompt. Defaults to null.
string[]
Tool names to hide from the agent. Defaults to [].
StructuredToolInterface[]
Extra LangChain tools to add after MCP tools are created. Defaults to [].
boolean
Expose MCP resources as tools. Defaults to true.
boolean
Expose MCP prompts as tools. Defaults to true.
boolean
Use ServerManager tools instead of exposing all server tools directly. Defaults to false.
boolean
Enable verbose observability output. Defaults to false.
boolean
Enable observability callback setup. Defaults to true.
BaseCallbackHandler[]
Custom LangChain callback handlers.
Signature

MCPServerConfig

Configuration for an MCP server in simplified mode. Fields
string
Command for a stdio server.
string[]
Arguments passed to command.
Record<string, string>
Environment variables for the server process.
string
URL for a remote HTTP MCP server.
Record<string, string>
Headers sent to remote MCP servers.
string
Bearer token value accepted by existing config shapes.
string
Bearer token value accepted by existing config shapes.
Signature

LLMConfig

Configuration passed to internally created LangChain model instances in simplified mode. Fields
string
Provider API key. If omitted, the provider-specific environment variable is used.
number
Sampling temperature.
number
Maximum output tokens.
number
Nucleus sampling value.
any
Additional provider-specific LangChain model options.
Signature

RunOptions

Options object accepted by run, stream, streamEvents, and prettyStreamEvents. Fields
string
required
User request to send to the agent.
number
Per-call step limit override.
boolean
Whether the agent manages initialization and connector cleanup for the call.
BaseMessage[]
Additional history appended after the native agent’s stored memory and before provider messages and the current prompt.
ZodSchema<T>
Zod schema for structured output.
AbortSignal
Abort signal for cancellation.
Signature
RunOptions is defined in the mcp_agent.ts source file. It is used structurally by the public methods, so you can pass an object with these fields without importing the interface.